import { useState, useEffect, Fragment } from "react";
import React from "react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Badge } from "./ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "./ui/alert-dialog";
import { Label } from "./ui/label";
import { Checkbox } from "./ui/checkbox";
import { Textarea } from "./ui/textarea";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "./ui/command";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from "./ui/pagination";
import { Plus, Edit, Trash2, Search, Package, Filter, Upload, Pencil, Image as ImageIcon, Check, FileImage, X, ChevronDown, ChevronRight, ChevronLeft, ArrowLeft, GitBranch, Save, History, ArrowUp, ArrowDown } from "lucide-react";
import exampleBendingDiagram from 'figma:asset/2a806b875fb2a7ce7cfbc897e685c9aa1903ddd3.png';
import { BendingStep, BendingDataInput } from "./BendingDataInput";
import { DrawingCanvas } from "./DrawingCanvas";
import { BOMItemSelectionDialog } from "./BOMItemSelectionDialog";
import { BendingDetailCards } from "./BendingDetailCards";
import { toast } from "sonner@2.0.3";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { StatCards } from "./organisms/StatCards";
import { SearchFilter } from "./organisms/SearchFilter";
import { DetailViewActions } from "./organisms/DetailViewActions";
import { ListActions } from "./organisms/ListActions";
import { FormActions } from "./organisms/FormActions";
import { TableActionButtons } from "./organisms/TableActionButtons";
import { ScreenVersionHistory } from "./organisms/ScreenVersionHistory";
import { DataTable, Column } from "./organisms/DataTable";
import { MobileItemListTemplate, MobileItemListItem } from "./templates/MobileItemListTemplate";
import { IntegratedListTemplateV2, TabOption, TableColumn } from "./templates/IntegratedListTemplateV2";
import { useData, ItemMaster, BendingDetail, BOMLine, SpecificationMaster, MaterialItemName, ItemRevision } from "./contexts/DataContext";
import { validateForm, hasErrors } from "./utils/validation";
import { Alert, AlertDescription } from "./ui/alert";
import { useVersionControl, VersionControlDialog, VersionHistoryViewer } from "./VersionControl";
import { RevisionHistoryDialog, RevisionSelector, RevisionBadge, getDisplayDataByRevision, RevisionDisplayConfig } from "./RevisionHistoryViewer";
import { DynamicSelectField, HybridSelectField } from "./DynamicSelectField";

// 옵션 정의
interface ItemOption {
  id: string;
  name: string;
  label: string;
  valueType: "Y/N" | "SELECT";
  selectableValues?: string[];
  defaultValue: string;
}

// 단가 이력
interface PriceHistory {
  id: string;
  effectiveDate: string;
  purchasePrice?: number;
  salesPrice?: number;
  marginRate?: number;
  note?: string;
}

// 첨부파일
interface FileAttachment {
  id: string;
  name: string;
  size: number;
  type: string;
  uploadedAt: string;
  url?: string;
}

// 절곡품 전개도 데이터
interface BendingDetail {
  id: string;
  no: number; // 번호
  input: number; // 입력
  elongation: number; // 연신율 (기본값 -1)
  calculated: number; // 연신율 계산 후
  sum: number; // 합계
  shaded: boolean; // 음영 여부
  aAngle?: number; // A각
}

// BOM 라인
interface BOMLine {
  id: string;
  childItemCode: string;
  childItemName: string;
  specification?: string; // 규격
  material?: string; // 재질
  width?: number; // 폭
  quantity: number;
  unit: string;
  unitPrice?: number;
  quantityFormula?: string; // 수량 계산식 (예: "W * 2", "H + 100")
  note?: string;
  // 절곡품 관련
  isBending?: boolean; // 절곡품 여부
  bendingDiagram?: string; // 전개도 이미지 URL
  bendingDetails?: BendingDetail[]; // 전개도 상세 데이터
}

// 품목 분류 체계
const ITEM_CATEGORIES = {
  "본체부품": {
    "가이드시스템": ["가이드레일"],
    "케이스시스템": ["케이스 전면부", "케이스 접검구", "케이스 린텔부", "케이스 후면코너부"],
    "차단부": ["슬랫(방화)", "스크린(투명)", "연결부품"],
    "하단마감재": ["하단마감재(스크린용)", "하단마감재(철재용)", "마찰볼"],
  },
  "안전장치": {
    "감지시스템": ["감지샤프트 60.5파이", "감지샤프트 114.3파이", "감지센서"],
    "연기차단재": ["화이바원단 W50", "화이바원단 W80"],
  },
  "구동장치": {
    "전동개폐기": ["150KG급", "300KG급", "400KG급", "500KG급 이상"],
    "감속기": [],
    "체인/벨트": [],
  },
  "제어장치": {
    "연동제어기": ["매립형", "노출형", "무선형"],
    "센서류": ["광전센서", "리미트센서"],
    "스위치류": [],
  },
  "구조재/부속품": {
    "앵글": [],
    "브라켓": [],
    "무게명찰": [],
    "컨베이트": [],
    "볼트/너트": [],
  },
  "철강재": {
    "SUS 철판": ["1.2T", "1.6T", "2.0T"],
    "EGI 철판": ["1.2T", "1.6T", "2.3T"],
    "강관/파이프": ["60.5파이", "114.3파이", "기타"],
    "차단재": ["스라트(철재)"],
  },
};

// 가이드레일 코드 체계
const GUIDE_RAIL_CODE_SYSTEM = {
  제품구분: {
    "가이드레일(벽면형)": "R",
    "가이드레일(측면형)": "S",
  },
  종류: {
    "본체": "M",
    "본체(철재)": "T",
    "C형": "C",
    "D형": "D",
    "SUS 마감재": "S",
    "SUS 마감재①": "S",
    "SUS 마감재②": "U",
    "본체디딤": "M",
  }
};

// 가이드레일 세부 옵션
const GUIDE_RAIL_OPTIONS = {
  모델유형: ["가이드레일(벽면형)", "가이드레일(측면형)"],
  모델선택: {
    "가이드레일(벽면형)": ["본체", "본체(철재)", "C형", "D형", "SUS 마감재"],
    "가이드레일(측면형)": ["본체디딤", "본체(철재)", "C형", "D형", "SUS 마감재①", "SUS 마감재②"],
  },
  인정여부: ["인정", "비인정"],
  규격길이: ["2438", "3000", "3500", "4000", "4300"], // 인정제품 규격 길이 (mm)
  레일형태: ["일반형", "특수형"],
  마감형태: ["무도장", "파우더도장", "아노다이징"],
};

// 부품 유형별 분류 체계 (품목명 코드 포함)
const PART_TYPE_CATEGORIES = {
  ASSEMBLY: {
    label: "조립 부품 (Assembly Part)",
    categories: [
      { value: "guide_rail_wall", label: "가이드레일(벽면형)", code: "R" },
      { value: "guide_rail_side", label: "가이드레일(측면형)", code: "S" },
      { value: "case", label: "케이스", code: "C" },
      { value: "bottom_finish_screen", label: "하단마감재(스크린)", code: "B" },
      { value: "bottom_finish_steel", label: "하단마감재(철재)", code: "T" },
    ]
  },
  BENDING: {
    label: "절곡 부품 (Bending Part)",
    categories: [
      { value: "guide_rail_wall", label: "가이드레일(벽면형)", code: "R" },
      { value: "guide_rail_side", label: "가이드레일(측면형)", code: "S" },
      { value: "case", label: "케이스", code: "C" },
      { value: "bottom_finish_screen", label: "하단마감재(스크린)", code: "B" },
      { value: "bottom_finish_steel", label: "하단마감재(철재)", code: "T" },
      { value: "l_bar", label: "L-Bar", code: "L" },
      { value: "smoke_barrier", label: "연기차단재", code: "G" },
    ]
  },
  PURCHASED: {
    label: "구매 부품 (Purchased Part)",
    categories: [
      { value: "electric_opener", label: "전동개폐기", code: "E" },
    ]
  }
};

// 부품 분류별 종류 옵션 (종류 코드 포함)
const PART_ITEM_NAMES = {
  guide_rail_wall: [
    { value: "RM", label: "분체", code: "M" },
    { value: "RT", label: "분체(철재)", code: "T" },
    { value: "RC", label: "C형", code: "C" },
    { value: "RD", label: "D형", code: "D" },
    { value: "RS", label: "SUS 마감재", code: "S" },
    { value: "RM2", label: "분체티딩", code: "M" },
  ],
  guide_rail_side: [
    { value: "SC", label: "C형", code: "C" },
    { value: "SD", label: "D형", code: "D" },
    { value: "SS", label: "SUS 마감재①", code: "S" },
    { value: "SU", label: "SUS 마감재②", code: "U" },
    { value: "SF", label: "전면부", code: "F" },
    { value: "SP", label: "점검구", code: "P" },
  ],
  case: [
    { value: "CF", label: "전면부", code: "F" },
    { value: "CP", label: "점검구", code: "P" },
    { value: "CL", label: "린텔부", code: "L" },
    { value: "CB", label: "후면코너부", code: "B" },
  ],
  bottom_finish_screen: [
    { value: "BS", label: "SUS", code: "S" },
    { value: "BE", label: "EGI", code: "E" },
  ],
  bottom_finish_steel: [
    { value: "TS", label: "SUS", code: "S" },
    { value: "TE", label: "EGI", code: "E" },
  ],
  l_bar: [
    { value: "LA", label: "스크린용", code: "A" },
  ],
  smoke_barrier: [
    { value: "GI", label: "화이바원단(W50)", code: "I" },
    { value: "GI2", label: "화이바원단(W80)", code: "I" },
  ],
  // 레거시 호환성을 위한 이전 키 (기존 코드 동작 유지)
  guide_rail: [
    { value: "RC", label: "측면형-C형 (C)", code: "C", type: "R" },
    { value: "RD", label: "측면형-D형 (D)", code: "D", type: "R" },
    { value: "RS", label: "측면형-SUS마감재① (S)", code: "S", type: "R" },
    { value: "RU", label: "측면형-SUS마감재② (U)", code: "U", type: "R" },
    { value: "RM", label: "측면형-분체디팅 (M)", code: "M", type: "R" },
    { value: "RT", label: "측면형-분체(절재) (T)", code: "T", type: "R" },
    { value: "SC", label: "벽면형-C형 (C)", code: "C", type: "S" },
    { value: "SD", label: "벽면형-D형 (D)", code: "D", type: "S" },
    { value: "SS", label: "벽면형-SUS마감재① (S)", code: "S", type: "S" },
    { value: "SU", label: "벽면형-SUS마감재② (U)", code: "U", type: "S" },
    { value: "SM", label: "벽면형-분체디팅 (M)", code: "M", type: "S" },
    { value: "ST", label: "벽면형-분체(절재) (T)", code: "T", type: "S" },
  ],
  bottom_finish: [
    { value: "bottom_bar", label: "하장바" },
    { value: "bottom_bar_reinforce", label: "하장바 보강" },
    { value: "bottom_bar_separate_finish", label: "하장바 별도마감" },
  ],
};

export function ItemManagement() {
  const { itemMasters, addItemMaster, updateItemMaster, deleteItemMaster, resetAllData, pricing, deletePricing, specificationMasters, materialItemNames, addMaterialItemName, updateMaterialItemName, deleteMaterialItemName, itemMasterFields } = useData();
  
  // 버전 관리 Hook
  const {
    screenVersion,
    isVersionDialogOpen,
    setIsVersionDialogOpen,
    requestVersionUpdate,
    confirmVersionUpdate,
    cancelVersionUpdate
  } = useVersionControl("품목관리", "/components/ItemManagement.tsx");
  
  const [view, setView] = useState<"list" | "create" | "edit" | "view">("list");
  const [selectedItem, setSelectedItem] = useState<ItemMaster | null>(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterType, setFilterType] = useState<string>("all");
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [itemToDelete, setItemToDelete] = useState<ItemMaster | null>(null);
  
  // 페이징 상태
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;
  
  // 일괄 삭제 관련 상태
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [isBulkDeleteDialogOpen, setIsBulkDeleteDialogOpen] = useState(false);
  const [isDeleteAllDialogOpen, setIsDeleteAllDialogOpen] = useState(false);
  
  // 단가 표시 권한 (임시로 상태로 관리, 추후 권한 시스템과 연동 예정)
  const [canViewPrice, setCanViewPrice] = useState(true); // true: 단가 표시, false: 단가 숨김
  
  // 버전 관리 - 수정 사유 입력
  const [isRevisionDialogOpen, setIsRevisionDialogOpen] = useState(false);
  const [revisionReason, setRevisionReason] = useState("");
  const [pendingUpdates, setPendingUpdates] = useState<any>(null);
  
  // 수정 이력 조회
  const [isViewingHistory, setIsViewingHistory] = useState(false);
  const [selectedRevisionNumber, setSelectedRevisionNumber] = useState<number | null>(null);
  
  // 수정 이력 다이얼로그
  const [isRevisionHistoryOpen, setIsRevisionHistoryOpen] = useState(false);
  const [selectedItemForHistory, setSelectedItemForHistory] = useState<ItemMaster | null>(null);
  
  // 품목 상세 조회 시 버전 선택
  const [selectedRevision, setSelectedRevision] = useState<string>("current");
  
  // BOM 절곡품 수정 다이얼로그 상태
  const [editBendingDialog, setEditBendingDialog] = useState<{
    isOpen: boolean;
    bomLine: BOMLine | null;
    parentItemCode: string;
  }>({
    isOpen: false,
    bomLine: null,
    parentItemCode: "",
  });
  
  // 절곡품 수정 임시 데이터
  const [tempBendingData, setTempBendingData] = useState<{
    bendingDiagram?: string;
    bendingDetails: BendingDetail[];
  }>({
    bendingDetails: []
  });
  
  // 페이징 상태
  const [currentPageFG, setCurrentPageFG] = useState(1);
  const [currentPageAssembly, setCurrentPageAssembly] = useState(1);
  const [currentPageBending, setCurrentPageBending] = useState(1);
  const [currentPagePurchased, setCurrentPagePurchased] = useState(1);
  const [currentPageSM, setCurrentPageSM] = useState(1);
  const [currentPageRM, setCurrentPageRM] = useState(1);
  const [currentPageCS, setCurrentPageCS] = useState(1);
  
  // BOM 확장/축소 상태
  const [expandedBomItems, setExpandedBomItems] = useState<Set<string>>(new Set());
  
  // 폼 상태
  const [formData, setFormData] = useState({
    itemName: "",
    productName: "",
    specification: "",
    itemType: "" as "" | "FG" | "PT" | "SM" | "RM" | "CS",
    productCategory: "" as "" | "SCREEN" | "STEEL",
    partType: "" as "" | "ASSEMBLY" | "BENDING" | "PURCHASED", // 부품 유형
    partUsage: "" as "" | "GUIDE_RAIL" | "BOTTOM_FINISH" | "CASE" | "DOOR" | "BRACKET" | "GENERAL", // 부품 용도
    category1: "",
    category2: "",
    category3: "",
    // 가이드레일 세부 정보
    guideRailModelType: "",
    guideRailModel: "",
    // 조립 부품 세부 정보
    installationType: "", // 설치 유형 (벽면형/측면형/혼합형)
    assemblyType: "", // 종류 (M/T/C/D/S/U 등)
    sideSpecWidth: "", // 측면 규격 가로 (mm)
    sideSpecHeight: "", // 측면 규격 세로 (mm)
    assemblyLength: "", // 길이 (2438/3000/3500/4000/4300)
    // 전동개폐기 세부 정보
    electricOpenerPower: "", // 전원 (220V/380V)
    electricOpenerVolt: "", // 볼트
    electricOpenerCapacity: "", // 용량 (150/300/400/500/600/800/1000 KG)
    unit: "",
    description: "",
    isSaleable: false, // 판매가능 여부
    needsBOM: true, // 부품구성(BOM) 필요 여부
    bendingDetails: [] as BendingDetail[], // 절곡품 전개도 상세 데이터
    // 절곡품 추가 정보
    material: "", // 재질 (EGI 1.55T, SUS 1.2T 등)
    length: "", // 길이/목함 (mm)
    bendingLength: "", // 절곡품 길이 규격 (2438/3000/3500/4000/4300 등)
    // 인정 정���
    certificationNumber: "", // 인정번호
    certificationStartDate: "", // 인정 유효기간 시작일
    certificationEndDate: "", // 인정 유효기간 종료일
    specificationFileName: "", // 시방서 파일명
    certificationFileName: "", // 인정서 파일명
    // 품목 관리
    isActive: true, // 품목 활성/비활성
    lotAbbreviation: "", // 로트 약자 (제품만 사용)
    note: "", // 비고 (제품만 사용)
  });

  // BOM 및 절곡 관련 상태
  const [bomLines, setBomLines] = useState<BOMLine[]>([]);
  const [isBending, setIsBending] = useState(false);
  const [bendingData, setBendingData] = useState<BendingStep[]>([]);
  const [drawingImage, setDrawingImage] = useState<string>("");
  const [isDrawingCanvasOpen, setIsDrawingCanvasOpen] = useState(false);
  
  // 절곡 전개도 관련 상태
  const [bendingDiagram, setBendingDiagram] = useState<string>("");
  const [bendingDiagramFile, setBendingDiagramFile] = useState<File | null>(null);
  const [bendingDiagramInputMethod, setBendingDiagramInputMethod] = useState<"file" | "drawing">("file"); // 입력방식
  
  // 첨부파일 상태 (시방서/인정서)
  const [specificationFile, setSpecificationFile] = useState<string>("");
  const [certificationFile, setCertificationFile] = useState<string>("");
  
  // 파일 업로드 핸들러
  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>, fileType: 'specification' | 'certification') => {
    const file = e.target.files?.[0];
    if (file) {
      // PDF 파일만 허용
      if (file.type !== 'application/pdf') {
        toast.error("PDF 파일만 업로드 가능합니다.");
        return;
      }
      
      const reader = new FileReader();
      reader.onloadend = () => {
        const base64 = reader.result as string;
        if (fileType === 'specification') {
          setSpecificationFile(base64);
          setFormData(prev => ({ ...prev, specificationFileName: file.name }));
          toast.success("시방서가 업로드되었습니다.");
        } else {
          setCertificationFile(base64);
          setFormData(prev => ({ ...prev, certificationFileName: file.name }));
          toast.success("인정서가 업로드되었습니다.");
        }
      };
      reader.readAsDataURL(file);
    }
  };
  
  // 파일 삭제 핸들러
  const handleFileRemove = (fileType: 'specification' | 'certification') => {
    if (fileType === 'specification') {
      setSpecificationFile("");
      setFormData(prev => ({ ...prev, specificationFileName: "" }));
      toast.success("시방서가 삭제되었습니다.");
    } else {
      setCertificationFile("");
      setFormData(prev => ({ ...prev, certificationFileName: "" }));
      toast.success("인정서가 삭제되었습니다.");
    }
  };
  
  // BOM 품목 검색 상태 (각 라인별 검색어와 팝오버 열림 상태)
  const [bomSearchStates, setBomSearchStates] = useState<Record<string, { searchValue: string; isOpen: boolean }>>({});
  
  // BOM 품목 선택 다이얼로그 상태
  const [bomDialogOpen, setBomDialogOpen] = useState(false);
  const [selectedBomLineId, setSelectedBomLineId] = useState<string>("");
  const [bomDialogTab, setBomDialogTab] = useState<string>("PT");

  // Validation errors state
  const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});

  // 전체 삭제 다이얼로그 상태 추적
  useEffect(() => {
    console.log('isDeleteAllDialogOpen 상태:', isDeleteAllDialogOpen);
  }, [isDeleteAllDialogOpen]);

  // Clear specific validation error
  const clearFieldError = (field: string) => {
    if (validationErrors[field]) {
      setValidationErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  // 절곡 전개도 상세 입력 합계를 자동으로 길이/목함에 반영
  useEffect(() => {
    if (formData.itemType === "PT" && formData.partType === "BENDING") {
      const bendingDetails = (formData as any).bendingDetails as BendingDetail[] | undefined;
      if (bendingDetails && bendingDetails.length > 0) {
        // 마지막 행의 합계를 계산 (전체 합계)
        let totalSum = 0;
        for (let i = 0; i < bendingDetails.length; i++) {
          const d = bendingDetails[i];
          totalSum += d.input + d.elongation;
        }
        // 길이/목함 필드에 자동 반영 (소수점 2자리까지)
        const totalSumRounded = Math.round(totalSum * 100) / 100;
        const newLength = totalSumRounded > 0 ? totalSumRounded.toString() : "";
        if (formData.length !== newLength) {
          setFormData(prev => ({
            ...prev,
            length: newLength
          }));
        }
      }
    }
  }, [JSON.stringify((formData as any).bendingDetails), formData.itemType, formData.partType]);

  // 가이드레일 선택 시 품목명 자동 생성
  useEffect(() => {
    if (formData.category1 === "guide_rail" && formData.guideRailModelType && formData.guideRailModel) {
      const autoItemName = generateGuideRailItemName();
      if (autoItemName && formData.itemName !== autoItemName) {
        setFormData(prev => ({
          ...prev,
          itemName: autoItemName,
          unit: prev.unit || "EA" // 가이드레일은 기본적으로 EA 단위
        }));
      }
    }
  }, [formData.guideRailModelType, formData.guideRailModel, formData.category1]);

  // 샘플 데이터 (DataContext 사용으로 주석 처리)
  /* const [items, setItems] = useState<Item[]>([
    {
      id: "1",
      itemCode: "알루미늄 압출재-6063-T5",
      itemName: "알루미늄 압출재",
      itemType: "RM",
      unit: "M",
      specification: "6063-T5",
      purchasePrice: 8000,
      marginRate: 20,
      salesPrice: 9600,
      safetyStock: 100,
      leadTime: 7,
      minOrderQty: 10,
      createdAt: "2025-01-15",
    },
    {
      id: "2",
      itemCode: "가이드���일 (가변)-SUS 1.2T",
      itemName: "가이드레일 (가변)",
      itemType: "PT",
      unit: "EA",
      category1: "스크린",
      category2: "롤러",
      category3: "일반형",
      specification: "SUS 1.2T",
      processingCost: 3000,
      marginRate: 25,
      salesPrice: 3750,
      yieldRate: 2,
      safetyStock: 50,
      leadTime: 3,
      bom: [
        {
          id: "bom-pt-1",
          childItemCode: "알루미늄 압출재-6063-T5",
          childItemName: "알루미늄 압출재",
          quantity: 1,
          unit: "M",
          unitPrice: 8000,
          note: "가이드레일 소재"
        }
      ],
      createdAt: "2025-01-16",
    },
    {
      id: "3",
      itemCode: "스크린 셔터 (표준형)",
      itemName: "스크린 셔터 (표준형)",
      itemType: "FG",
      productCategory: "SCREEN",
      unit: "SET",
      category1: "���크린",
      category2: "블라인드",
      category3: "베네시안",
      laborCost: 100000,
      installCost: 50000,
      marginRate: 30,
      salesPrice: 450000,
      safetyStock: 10,
      leadTime: 14,
      options: [
        {
          id: "o1",
          name: "MOTOR",
          label: "모터 포함",
          valueType: "Y/N",
          defaultValue: "Y",
        },
      ],
      bom: [
        {
          id: "bom-1",
          childItemCode: "알루미늄 압출재-6063-T5",
          childItemName: "알루미늄 압출재",
          quantity: 1,
          unit: "M",
          unitPrice: 8000,
          quantityFormula: "(W + H) * 2 / 1000",
          note: "프레임: (폭+높이) x 2 / 1000m"
        },
        {
          id: "bom-2",
          childItemCode: "PT-ROLL-001",
          childItemName: "롤러",
          quantity: 1,
          unit: "EA",
          unitPrice: 15000,
          note: "상단 롤러"
        },
        {
          id: "bom-3",
          childItemCode: "PT-FABRIC-001",
          childItemName: "원단",
          quantity: 1,
          unit: "M2",
          unitPrice: 12000,
          quantityFormula: "W * H / 1000000",
          note: "원단 면적: 가로 x 세로 / 1,000,000"
        },
        {
          id: "bom-4",
          childItemCode: "포장재-골판지 5겹",
          childItemName: "포장재",
          quantity: 1,
          unit: "EA",
          unitPrice: 500,
          note: "포장박스"
        }
      ],
      createdAt: "2025-01-17",
    },
    {
      id: "4",
      itemCode: "포장재-골판지 5겹",
      itemName: "포장재",
      itemType: "SM",
      unit: "EA",
      category1: "부자재",
      category2: "포장",
      category3: "박스",
      specification: "골판지 5겹",
      purchasePrice: 500,
      marginRate: 15,
      salesPrice: 575,
      safetyStock: 200,
      leadTime: 5,
      minOrderQty: 100,
      createdAt: "2025-01-18",
    },
    {
      id: "5",
      itemCode: "장갑-면-L",
      itemName: "장갑",
      itemType: "CS",
      unit: "켤레",
      category1: "소모품",
      category2: "안전용품",
      specification: "면-L",
      purchasePrice: 1500,
      marginRate: 10,
      salesPrice: 1650,
      safetyStock: 500,
      leadTime: 2,
      minOrderQty: 50,
      createdAt: "2025-01-19",
    },
    {
      id: "6",
      itemCode: "롤스크린 (고급형)-SCREEN-002",
      itemName: "롤스크린 (고급형)",
      itemType: "FG",
      productCategory: "SCREEN",
      unit: "SET",
      category1: "스크린",
      category2: "롤",
      category3: "고급형",
      specification: "SCREEN-002",
      laborCost: 120000,
      installCost: 60000,
      marginRate: 32,
      salesPrice: 550000,
      safetyStock: 8,
      leadTime: 14,
      options: [
        {
          id: "o3",
          name: "REMOTE",
          label: "리모컨 포함",
          valueType: "Y/N",
          defaultValue: "N",
        },
      ],
      bom: [
        {
          id: "bom-roll-1",
          childItemCode: "알루미늄 압출재-6063-T5",
          childItemName: "알루미늄 압출재",
          quantity: 1,
          unit: "M",
          unitPrice: 8000,
          quantityFormula: "W / 1000 * 1.1",
          note: "상단바: 폭 / 1000 x 1.1 (여유)"
        },
        {
          id: "bom-roll-2",
          childItemCode: "PT-ROLL-001",
          childItemName: "롤러",
          quantity: 1,
          unit: "EA",
          unitPrice: 18000,
          note: "고급형 롤���"
        },
        {
          id: "bom-roll-3",
          childItemCode: "PT-FABRIC-PREMIUM",
          childItemName: "프리미엄 원단",
          quantity: 1,
          unit: "M2",
          unitPrice: 15000,
          quantityFormula: "W * H / 1000000 * 1.05",
          note: "원단 면적 + 5% 여유"
        },
        {
          id: "bom-roll-4",
          childItemCode: "CHAIN-001",
          childItemName: "체인",
          quantity: 1,
          unit: "M",
          unitPrice: 2000,
          quantityFormula: "H / 1000 * 2",
          note: "높이 x 2배"
        }
      ],
      createdAt: "2025-01-20",
    },
    {
      id: "7",
      itemCode: "철재문 (표준형)-STEEL-001",
      itemName: "철재문 (표준형)",
      itemType: "FG",
      productCategory: "STEEL",
      unit: "SET",
      category1: "철재",
      category2: "문",
      category3: "표준형",
      specification: "STEEL-001",
      laborCost: 150000,
      installCost: 80000,
      marginRate: 35,
      salesPrice: 650000,
      safetyStock: 5,
      leadTime: 21,
      options: [
        {
          id: "o2",
          name: "LOCK",
          label: "도어락 포함",
          valueType: "Y/N",
          defaultValue: "Y",
        },
      ],
      bom: [
        {
          id: "bom-steel-1",
          childItemCode: "STEEL-FRAME-001",
          childItemName: "철재 프레임",
          quantity: 1,
          unit: "M",
          unitPrice: 25000,
          quantityFormula: "(W + H) * 2 / 1000",
          note: "프���임: (폭+높이) x 2 / 1000m"
        },
        {
          id: "bom-steel-2",
          childItemCode: "STEEL-PLATE-001",
          childItemName: "철판",
          quantity: 1,
          unit: "M2",
          unitPrice: 35000,
          quantityFormula: "W * H / 1000000",
          note: "철판 면적: 가로 x 세로 / 1,000,000"
        },
        {
          id: "bom-steel-3",
          childItemCode: "HINGE-001",
          childItemName: "경첩",
          quantity: 3,
          unit: "EA",
          unitPrice: 8000,
          note: "3개 기본"
        },
        {
          id: "bom-steel-4",
          childItemCode: "LOCK-001",
          childItemName: "도어락",
          quantity: 1,
          unit: "EA",
          unitPrice: 45000,
          note: "도어락"
        }
      ],
      createdAt: "2025-01-20",
    },
  ]); */

  // DataContext의 itemMasters를 items로 사용
  const items = itemMasters;

  // 가이드레일 품목코드 자동 생성 함수
  const generateGuideRailItemCode = () => {
    const { guideRailModelType, guideRailModel, length } = formData;
    
    if (!guideRailModelType || !guideRailModel || !length) return "";
    
    // 제품 구분 코드
    const productCode = GUIDE_RAIL_CODE_SYSTEM.제품구분[guideRailModelType as keyof typeof GUIDE_RAIL_CODE_SYSTEM.제품구분];
    
    // 종류 코드
    const typeCode = GUIDE_RAIL_CODE_SYSTEM.종류[guideRailModel as keyof typeof GUIDE_RAIL_CODE_SYSTEM.종류];
    
    if (!productCode || !typeCode) return "";
    
    // 길이 축약 (길이를 100으로 나눈 후 정수 부분만 사용)
    const lengthCode = Math.floor(parseFloat(length) / 100).toString().padStart(2, '0');
    
    return `${productCode}${typeCode}${lengthCode}`;
  };

  // 가이드레일 품목명 자동 생성 함수
  const generateGuideRailItemName = () => {
    const { guideRailModelType, guideRailModel } = formData;
    
    if (!guideRailModelType || !guideRailModel) return "";
    
    return `${guideRailModelType} ${guideRailModel}`;
  };

  // 가이드레일 규격 자동 생성 함수
  const generateGuideRailSpecification = () => {
    const { length } = formData;
    
    if (!length) return "";
    
    return length;
  };

  // 조립부품 품목코드 한글 포맷 함수
  const formatItemCodeForAssembly = (item: ItemMaster): string => {
    // 품목코드가 이미 있으면 그대로 반환
    return item.itemCode || '';
  };

  // 품목코드 자동 생성 함수
  const generateItemCode = (itemName: string, specification: string) => {
    // 조립 부품인 경우 - 새로운 코드 체계: 품목명 한글 + 설치유형 한글 + (측면규격*길이)
    if (formData.partType === "ASSEMBLY" && formData.itemName && formData.installationType) {
      // 설치유형 한글 텍스트 추출
      const installationTypeMap: Record<string, string> = {
        "standard": "표준형"
      };
      
      const installationTypeKorean = installationTypeMap[formData.installationType] || formData.installationType;
      
      // 품목명 한글 + 설치유형 한글
      let code = `${formData.itemName}${installationTypeKorean}`;
      
      // 측면규격과 길이가 있는 경우 추가
      if (formData.sideSpecWidth && formData.sideSpecHeight && formData.assemblyLength) {
        // 길이 코드 변환
        let lengthCode = "";
        const lengthNum = parseInt(formData.assemblyLength);
        if (lengthNum === 1219) lengthCode = "12";
        else if (lengthNum === 2438) lengthCode = "24";
        else if (lengthNum === 3000) lengthCode = "30";
        else if (lengthNum === 3500) lengthCode = "35";
        else if (lengthNum === 4000) lengthCode = "40";
        else if (lengthNum === 4150) lengthCode = "41";
        else if (lengthNum === 4200) lengthCode = "42";
        else if (lengthNum === 4300) lengthCode = "43";
        else {
          lengthCode = Math.floor(lengthNum / 100).toString().padStart(2, '0');
        }
        
        code += `${formData.sideSpecWidth}*${formData.sideSpecHeight}*${lengthCode}`;
      }
      
      return code;
    }
    
    // 절곡 부품인 경우 - 새로운 코드 체계: 품목명코드 + 종류코드 + 길이코드
    if (formData.partType === "BENDING" && formData.category2 && formData.category3) {
      // category2: 품목명 코드 (R, S, C, B, T, L, G)
      // category3: 종류 코드 (M, T, C, D, S, U, F, P, L, B, E, I, A)
      // bendingLength: 모양&길이 (W50x3000, 1219, 2438 등)
      
      let lengthCode = "";
      
      if (formData.bendingLength) {
        const bendingLengthValue = formData.bendingLength;
        
        // W50x3000 형식 처리
        if (bendingLengthValue.startsWith("W")) {
          if (bendingLengthValue === "W50x3000") lengthCode = "53";
          else if (bendingLengthValue === "W50x4000") lengthCode = "54";
          else if (bendingLengthValue === "W80x3000") lengthCode = "83";
          else if (bendingLengthValue === "W80x4000") lengthCode = "84";
          else {
            // 파싱: W50x3000 -> 50, 3000
            const match = bendingLengthValue.match(/W(\d+)x(\d+)/);
            if (match) {
              const width = parseInt(match[1]);
              const length = parseInt(match[2]);
              const widthDigit = Math.floor(width / 10);
              const lengthDigit = Math.floor(length / 1000);
              lengthCode = `${widthDigit}${lengthDigit}`;
            }
          }
        } else {
          // 숫자만 있는 형식 (길이만)
          const lengthNum = parseInt(bendingLengthValue);
          if (lengthNum === 1219) lengthCode = "12";
          else if (lengthNum === 2438) lengthCode = "24";
          else if (lengthNum === 3000) lengthCode = "30";
          else if (lengthNum === 3500) lengthCode = "35";
          else if (lengthNum === 4000) lengthCode = "40";
          else if (lengthNum === 4150) lengthCode = "41";
          else if (lengthNum === 4200) lengthCode = "42";
          else if (lengthNum === 4300) lengthCode = "43";
          else {
            lengthCode = Math.floor(lengthNum / 100).toString().padStart(2, '0');
          }
        }
      }
      
      // 형식: 품목명코드 + 종류코드 + 길이코드 (예: RC24, RM12, CF30, BS24, LA12, GI53)
      return `${formData.category2}${formData.category3}${lengthCode}`;
    }
    
    // 레거시 호환: 이전 방식으로 등록된 데이터 처리
    if (formData.partType === "BENDING" && formData.category1 && itemName && formData.bendingLength) {
      // 가이드레일인 경우 특별한 코드 체계 적용
      if (formData.category1 === "guide_rail") {
        // PART_ITEM_NAMES에서 선택된 항목 찾기
        const selectedItem = PART_ITEM_NAMES.guide_rail.find(item => item.label === itemName);
        
        if (selectedItem && selectedItem.type && selectedItem.code) {
          // 모양&길이 파싱
          let sizeCode = "";
          const bendingLengthValue = formData.bendingLength;
          
          if (bendingLengthValue.startsWith("W")) {
            // "W50x3000" 형식
            if (bendingLengthValue === "W50x3000") sizeCode = "53";
            else if (bendingLengthValue === "W50x4000") sizeCode = "54";
            else if (bendingLengthValue === "W80x3000") sizeCode = "83";
            else if (bendingLengthValue === "W80x4000") sizeCode = "84";
            else {
              // 파싱: W50x3000 -> 50, 3000
              const match = bendingLengthValue.match(/W(\d+)x(\d+)/);
              if (match) {
                const width = parseInt(match[1]);
                const length = parseInt(match[2]);
                const widthDigit = Math.floor(width / 10);
                const lengthDigit = Math.floor(length / 1000);
                sizeCode = `${widthDigit}${lengthDigit}`;
              }
            }
          } else {
            // 숫자만 있는 형식 (길이만)
            const lengthNum = parseInt(bendingLengthValue);
            if (lengthNum === 1219) sizeCode = "12";
            else if (lengthNum === 2438) sizeCode = "24";
            else if (lengthNum === 3000) sizeCode = "30";
            else if (lengthNum === 3500) sizeCode = "35";
            else if (lengthNum === 4000) sizeCode = "40";
            else if (lengthNum === 4150) sizeCode = "41";
            else if (lengthNum === 4200) sizeCode = "42";
            else if (lengthNum === 4300) sizeCode = "43";
            else {
              sizeCode = Math.floor(lengthNum / 100).toString().padStart(2, '0');
            }
          }
          
          // 형식: 제품구분(R/S) + 종류코드(C/D/S/U/M/T) + 길이축약(12/24/30/35/40/41/42/43)
          return `${selectedItem.type}${selectedItem.code}${sizeCode}`;
        }
      }
      
      // 케이스인 경우
      if (formData.category1 === "case") {
        // PART_ITEM_NAMES에서 선택된 항목 찾기
        const selectedItem = PART_ITEM_NAMES.case.find(item => item.label === itemName);
        
        if (selectedItem && selectedItem.code) {
          // 모양&길이 파싱
          let sizeCode = "";
          const bendingLengthValue = formData.bendingLength;
          
          const lengthNum = parseInt(bendingLengthValue);
          if (lengthNum === 1219) sizeCode = "12";
          else if (lengthNum === 2438) sizeCode = "24";
          else if (lengthNum === 3000) sizeCode = "30";
          else if (lengthNum === 3500) sizeCode = "35";
          else if (lengthNum === 4000) sizeCode = "40";
          else if (lengthNum === 4150) sizeCode = "41";
          else if (lengthNum === 4200) sizeCode = "42";
          else if (lengthNum === 4300) sizeCode = "43";
          else {
            sizeCode = Math.floor(lengthNum / 100).toString().padStart(2, '0');
          }
          
          // 형식: 케이스코드(F/P/L/B) + 길이축약(12/24/30/35/40/41/42/43)
          return `${selectedItem.code}${sizeCode}`;
        }
      }
      
      const category1Label = PART_TYPE_CATEGORIES.BENDING.categories.find(cat => cat.value === formData.category1)?.label || "";
      
      const lengthNum = parseInt(formData.bendingLength);
      let lengthCode = "";
      
      if (lengthNum === 1219) lengthCode = "12";
      else if (lengthNum === 2438) lengthCode = "24";
      else if (lengthNum === 3000) lengthCode = "30";
      else if (lengthNum === 3500) lengthCode = "35";
      else if (lengthNum === 4000) lengthCode = "40";
      else if (lengthNum === 4150) lengthCode = "41";
      else if (lengthNum === 4200) lengthCode = "42";
      else if (lengthNum === 4300) lengthCode = "43";
      else {
        lengthCode = Math.floor(lengthNum / 100).toString().padStart(2, '0');
      }
      
      return `${category1Label}${itemName.trim()}${lengthCode}`;
    }
    
    // 가이드레일인 경우 특별한 코드 생성 규칙 적용 (절곡/구매 부품)
    if (formData.category1 === "guide_rail" && formData.guideRailModelType && formData.guideRailModel) {
      return generateGuideRailItemCode();
    }
    
    if (!itemName) return "";
    
    // 품목명과 규격을 조합하여 품목코드 생성
    const name = itemName.trim();
    const spec = specification ? `-${specification.trim()}` : "";
    return `${name}${spec}`;
  };

  // 필터링된 품목
  const filteredItems = itemMasters.filter((item) => {
    const matchesSearch =
      item.itemCode?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.itemName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.specification?.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesType = filterType === "all" || item.itemType === filterType;
    
    return matchesSearch && matchesType;
  }).sort((a, b) => {
    // ID를 숫자로 변환하여 내림차순 정렬 (최신 항목이 위로)
    return Number(b.id) - Number(a.id);
  });

  // 페이징 계산 - 각 탭별로
  const fgItems = filteredItems.filter(item => item.itemType === 'FG').sort((a, b) => {
    const dateA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
    const dateB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
    return dateB - dateA;
  });
  const assemblyItems = filteredItems.filter(item => (item as any).partType === 'ASSEMBLY').sort((a, b) => {
    const dateA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
    const dateB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
    return dateB - dateA;
  });
  const bendingItems = filteredItems.filter(item => (item as any).partType === 'BENDING').sort((a, b) => {
    const dateA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
    const dateB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
    return dateB - dateA;
  });
  const purchasedItems = filteredItems.filter(item => (item as any).partType === 'PURCHASED').sort((a, b) => {
    const dateA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
    const dateB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
    return dateB - dateA;
  });
  const smItems = filteredItems.filter(item => item.itemType === 'SM').sort((a, b) => {
    const dateA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
    const dateB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
    return dateB - dateA;
  });
  const rmItems = filteredItems.filter(item => item.itemType === 'RM').sort((a, b) => {
    const dateA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
    const dateB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
    return dateB - dateA;
  });
  const csItems = filteredItems.filter(item => item.itemType === 'CS').sort((a, b) => {
    const dateA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
    const dateB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
    return dateB - dateA;
  });

  // 각 탭별 페이징 계산
  const getPaginatedData = (items: ItemMaster[], currentPage: number) => {
    const totalPages = Math.ceil(items.length / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const paginatedItems = items.slice(startIndex, endIndex);
    return { totalPages, startIndex, endIndex, paginatedItems };
  };

  const fgPagination = getPaginatedData(fgItems, currentPageFG);
  const assemblyPagination = getPaginatedData(assemblyItems, currentPageAssembly);
  const bendingPagination = getPaginatedData(bendingItems, currentPageBending);
  const purchasedPagination = getPaginatedData(purchasedItems, currentPagePurchased);
  const smPagination = getPaginatedData(smItems, currentPageSM);
  const rmPagination = getPaginatedData(rmItems, currentPageRM);
  const csPagination = getPaginatedData(csItems, currentPageCS);

  // 전체 탭용 (기존 로직 유지)
  const totalPages = Math.ceil(filteredItems.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const paginatedItems = filteredItems.slice(startIndex, endIndex);

  // 필터나 검색어 변경 시 첫 페이지로 이동
  React.useEffect(() => {
    setCurrentPage(1);
    setCurrentPageFG(1);
    setCurrentPageAssembly(1);
    setCurrentPageBending(1);
    setCurrentPagePurchased(1);
    setCurrentPageSM(1);
    setCurrentPageRM(1);
    setCurrentPageCS(1);
  }, [filterType, searchTerm]);

  // 폼 데이터만 초기화 (뷰는 변경하지 않음)
  const resetFormData = () => {
    setSelectedItem(null);
    setFormData({
      itemName: "",
      specification: "",
      itemType: "",
      productCategory: "",
      productName: "",
      partType: "",
      partUsage: "",
      category1: "",
      category2: "",
      category3: "",
      guideRailModelType: "",
      guideRailModel: "",
      installationType: "",
      assemblyType: "",
      sideSpecWidth: "",
      sideSpecHeight: "",
      assemblyLength: "",
      electricOpenerPower: "",
      electricOpenerVolt: "",
      electricOpenerCapacity: "",
      unit: "",
      description: "",
      isSaleable: false,
      needsBOM: true,
      bendingDetails: [] as BendingDetail[],
      material: "",
      length: "",
      bendingLength: "",
      certificationNumber: "",
      certificationStartDate: "",
      certificationEndDate: "",
      specificationFileName: "",
      certificationFileName: "",
      isActive: true,
      lotAbbreviation: "",
      note: "",
    } as any);
    setBomLines([]);
    setIsBending(false);
    setBendingData([]);
    setDrawingImage("");
    setBendingDiagram("");
    setBendingDiagramFile(null);
    setBendingDiagramInputMethod("file");
    setSpecificationFile("");
    setCertificationFile("");
  };

  // 뷰 변경 시 폼 데이터 초기화 또는 로드
  const handleViewChange = (newView: "list" | "create" | "edit" | "view", item?: ItemMaster | null) => {
    setView(newView);
    
    if (newView === "list") {
      // 리스트로 돌아갈 때 모든 선택 초기화
      resetFormData();
    } else if (newView === "create") {
      // 신규 등록 시 폼 데이터만 초기화
      resetFormData();
    } else if (newView === "view" && item) {
      // 상세보기 시 선택된 품목만 설정
      setSelectedItem(item);
    } else if (newView === "edit" && item) {
      // 수정 시 기존 데이터 로드
      setFormData({
        itemName: item.itemName || "",
        specification: item.specification || "",
        itemType: item.itemType || "FG",
        productCategory: item.productCategory || "",
        productName: (item as any).productName || "",
        partType: (item as any).partType || "",
        partUsage: (item as any).partUsage || "",
        category1: item.category1 || "",
        category2: item.category2 || "",
        category3: item.category3 || "",
        guideRailModelType: (item as any).guideRailModelType || "",
        guideRailModel: (item as any).guideRailModel || "",
        installationType: (item as any).installationType || "",
        assemblyType: (item as any).assemblyType || "",
        sideSpecWidth: (item as any).sideSpecWidth || "",
        sideSpecHeight: (item as any).sideSpecHeight || "",
        assemblyLength: (item as any).assemblyLength || "",
        electricOpenerPower: (item as any).electricOpenerPower || "",
        electricOpenerVolt: (item as any).electricOpenerVolt || "",
        electricOpenerCapacity: (item as any).electricOpenerCapacity || "",
        unit: item.unit || "",
        description: "",
        isSaleable: (item as any).isSaleable || false,
        needsBOM: item.bom && item.bom.length > 0 ? true : false,
        bendingDetails: (item as any).bendingDetails || [],
        material: (item as any).material || "",
        length: (item as any).length || "",
        bendingLength: (item as any).bendingLength || "",
        certificationNumber: (item as any).certificationNumber || "",
        certificationStartDate: (item as any).certificationStartDate || "",
        certificationEndDate: (item as any).certificationEndDate || "",
        specificationFileName: (item as any).specificationFileName || "",
        certificationFileName: (item as any).certificationFileName || "",
        isActive: (item as any).isActive !== undefined ? (item as any).isActive : true,
        lotAbbreviation: (item as any).lotAbbreviation || "",
        note: (item as any).note || "",
      } as any);
      setBomLines(item.bom || []);
      const diagram = (item as any).bendingDiagram || "";
      setBendingDiagram(diagram);
      setDrawingImage(diagram);
      
      // 첨부파일 로드
      if ((item as any).specificationFile) {
        setSpecificationFile((item as any).specificationFile);
      }
      if ((item as any).certificationFile) {
        setCertificationFile((item as any).certificationFile);
      }
      
      setSelectedItem(item);
    }
  };

  // 품목 저장
  const handleSaveItem = () => {
    // 모든 validation errors를 수집
    const errors: Record<string, string> = {};

    // 기본 필수 필드
    if (!formData.itemType) {
      errors.itemType = "품목 유형을 선택해주세요";
    }
    
    // 부품인 경우 부품 유형 필수
    if (formData.itemType === "PT" && !formData.partType) {
      errors.partType = "부품 유형을 선택해주세요";
    }

    // 구매 부품인 경우 대분류 필수
    if (formData.itemType === "PT" && formData.partType === "PURCHASED" && !formData.category1) {
      errors.category1 = "대분류를 선택해주세요";
    }

    // 제품인 경우 상품명 필수
    if (formData.itemType === "FG" && !formData.productName.trim()) {
      errors.productName = "상품명을 입력해주세요";
    }

    // 제품인 경우 품목명 필수
    if (formData.itemType === "FG" && !formData.itemName.trim()) {
      errors.itemName = "품목명을 입력해주세요";
    }

    // 조립 부품인 경우 필수 입력값 체크
    if (formData.itemType === "PT" && formData.partType === "ASSEMBLY") {
      if (!formData.category1) {
        errors.category1 = "품목명을 선택해주세요";
      }
      
      if (!formData.installationType) {
        errors.installationType = "설치 유형을 선택해주세요";
      }
      
      // 측면 규격 및 길이 필수 체크 (모든 조립 부품 공통)
      if (!formData.sideSpecWidth) {
        errors.sideSpecWidth = "측면 규격 (가로)를 입력해주세요";
      }
      if (!formData.sideSpecHeight) {
        errors.sideSpecHeight = "측면 규격 (세로)를 입력해주세요";
      }
      if (!formData.assemblyLength) {
        errors.assemblyLength = "길이를 선택해주세요";
      }
    }
    
    // 절곡품인 경우 필수 입력값 체크
    if (formData.itemType === "PT" && formData.partType === "BENDING") {
      if (!formData.itemName) {
        errors.itemName = "품목명을 선택해주세요";
      }
      if (!formData.material) {
        errors.material = "재질을 선택해주세요";
      }
      if (!formData.length) {
        errors.length = "길이/목함을 입력해주세요";
      }
      if (!formData.bendingLength) {
        errors.bendingLength = "길이를 선택해주세요";
      }
      
      // 절곡 데이터 또는 절곡 도면 중 하나는 필수
      const hasBendingData = bendingData && bendingData.length > 0;
      const hasBendingDiagram = bendingDiagram && bendingDiagram.trim() !== "";
      
      if (!hasBendingData && !hasBendingDiagram) {
        errors.bendingInfo = "절곡 데이터 또는 절곡 형태보기 중 최소 1개를 입력해주세요";
      }
    }

    // 구매 부품인 경우 필수 입력값 체크
    if (formData.itemType === "PT" && formData.partType === "PURCHASED") {
      // 대분류 필수
      if (!formData.category1) {
        errors.category1 = "대분류를 선택해주세요";
      }
      
      // 전동개폐기인 경우
      if (formData.category1 === "electric_opener") {
        if (!formData.electricOpenerPower) {
          errors.electricOpenerPower = "전원을 선택해주세요";
        }
        if (!formData.electricOpenerCapacity) {
          errors.electricOpenerCapacity = "용량을 선택해주세요";
        }
      }
    }

    // 에러가 있으면 설정하고 종료
    if (Object.keys(errors).length > 0) {
      setValidationErrors(errors);
      
      // 에러 개수에 따라 메시지 변경
      const errorCount = Object.keys(errors).length;
      toast.error(`${errorCount}개의 필수 입력 항목을 확인해주세요.`);
      
      // 첫 번째 에러 필드로 스크롤
      setTimeout(() => {
        const firstErrorField = document.querySelector('[data-error="true"]');
        if (firstErrorField) {
          firstErrorField.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }, 100);
      return;
    }

    // 에러가 없으면 validation errors 초기화
    setValidationErrors({});

    // 조립 부품의 경우 품목명 자동 설정
    let finalItemName = formData.itemName || "";
    if (formData.partType === "ASSEMBLY") {
      if (formData.category1 === "guide_rail") finalItemName = "가이드레일";
      else if (formData.category1 === "case") finalItemName = "케이스";
      else if (formData.category1 === "bottom_finish") finalItemName = "하단마감재";
      else if (formData.category1) finalItemName = formData.category1; // 기타 경우
    }
    
    // 구매 부품의 경우 품목명 자동 설정
    if (formData.partType === "PURCHASED") {
      if (formData.category1 === "electric_opener") finalItemName = "전동개폐기";
    }
    
    // 품목코드 자동 생성
    const itemCode = formData.itemType === "FG" 
      ? (finalItemName || "제품-" + Date.now())  // 제품은 품목명과 품목코드 동일
      : generateItemCode(finalItemName, formData.specification) || ("품목-" + Date.now());

    console.log("품목 저장:", {
      itemCode,
      itemName: finalItemName,
      itemType: formData.itemType,
      partType: formData.partType,
      category1: formData.category1,
      installationType: formData.installationType,
      assemblyType: formData.assemblyType,
      assemblyLength: formData.assemblyLength
    });

    if (view === "create") {
      // 신규 등록
      const newItem: any = {
        id: Date.now().toString(),
        itemCode,
        itemName: finalItemName,
        itemType: formData.itemType,
        productCategory: formData.itemType === "FG" ? formData.productCategory : undefined,
        partType: formData.itemType === "PT" ? formData.partType : undefined,
        partUsage: formData.itemType === "PT" && formData.partType === "BENDING" ? formData.partUsage : undefined,
        category1: formData.category1 || undefined,
        category2: formData.category2 || undefined,
        category3: formData.category3 || undefined,
        unit: formData.unit,
        specification: formData.specification,
        bom: bomLines.length > 0 ? bomLines : undefined,
        isSaleable: formData.itemType === "PT" ? formData.isSaleable : undefined,
        isActive: ["FG", "PT", "RM", "SM"].includes(formData.itemType) ? formData.isActive : undefined,
        lotAbbreviation: formData.itemType === "FG" ? formData.lotAbbreviation : undefined,
        note: formData.itemType === "FG" ? formData.note : undefined,
        createdAt: new Date().toISOString().split("T")[0],
      };
      
      // 조립 부품인 경우 추가 정보 저장
      if (formData.partType === "ASSEMBLY") {
        newItem.installationType = formData.installationType || undefined;
        newItem.assemblyType = formData.assemblyType || undefined;
        newItem.sideSpecWidth = formData.sideSpecWidth || undefined;
        newItem.sideSpecHeight = formData.sideSpecHeight || undefined;
        newItem.assemblyLength = formData.assemblyLength || undefined;
        // 조립 부품 전개도 정보 저장
        newItem.bendingDiagram = bendingDiagram || undefined;
        newItem.bendingDetails = (formData as any).bendingDetails || undefined;
        newItem.material = formData.material || undefined;
        newItem.length = formData.length || undefined;
      }
      
      // 구매 부품인 경우 추가 정보 저장
      if (formData.partType === "PURCHASED" && formData.category1 === "electric_opener") {
        newItem.electricOpenerPower = formData.electricOpenerPower || undefined;
        newItem.electricOpenerVolt = formData.electricOpenerVolt || undefined;
        newItem.electricOpenerCapacity = formData.electricOpenerCapacity || undefined;
      }
      
      // 가이드레일인 경우 추가 정보 저장 (절곡/구매 부품)
      if (formData.category3 === "가이드레일") {
        newItem.guideRailModelType = formData.guideRailModelType || undefined;
        newItem.guideRailModel = formData.guideRailModel || undefined;
      }
      

      
      // 절곡 부품인 경우 전개도 정보 저장
      if (formData.itemType === "PT" && formData.partType === "BENDING") {
        newItem.bendingDiagram = bendingDiagram || undefined;
        newItem.bendingDetails = (formData as any).bendingDetails || undefined;
        newItem.material = formData.material || undefined;
        newItem.length = formData.length || undefined;
        newItem.bendingLength = formData.bendingLength || undefined;
        
        console.log("절곡 부품 저장:", {
          bendingDiagram: bendingDiagram ? "있음 (길이: " + bendingDiagram.length + ")" : "없음",
          bendingDetails: (formData as any).bendingDetails,
          material: formData.material,
          length: formData.length,
          bendingLength: formData.bendingLength
        });
      }
      
      // 인정 정보 저장
      if (formData.certificationNumber) {
        newItem.certificationNumber = formData.certificationNumber;
      }
      if (formData.certificationStartDate) {
        newItem.certificationStartDate = formData.certificationStartDate;
      }
      if (formData.certificationEndDate) {
        newItem.certificationEndDate = formData.certificationEndDate;
      }
      if (specificationFile && formData.specificationFileName) {
        newItem.specificationFile = specificationFile;
        newItem.specificationFileName = formData.specificationFileName;
      }
      if (certificationFile && formData.certificationFileName) {
        newItem.certificationFile = certificationFile;
        newItem.certificationFileName = formData.certificationFileName;
      }
      
      // 버전 관리 초기화 (신규 등록)
      newItem.currentRevision = 0;
      newItem.revisions = [];
      newItem.isFinal = false;
      
      // 신규 등록 시에는 버전 다이얼로그 없이 바로 저장
      addItemMaster(newItem);
      toast.success("품목이 성공적으로 등록되었습니다.");
      resetForm();
    } else if (view === "edit" && selectedItem) {
      // 수정
      const updates: any = {
        itemCode,
        itemName: finalItemName,
        itemType: formData.itemType,
        productCategory: formData.itemType === "FG" ? formData.productCategory : undefined,
        partType: formData.itemType === "PT" ? formData.partType : undefined,
        partUsage: formData.itemType === "PT" && formData.partType === "BENDING" ? formData.partUsage : undefined,
        category1: formData.category1 || undefined,
        category2: formData.category2 || undefined,
        category3: formData.category3 || undefined,
        unit: formData.unit,
        specification: formData.specification,
        bom: bomLines.length > 0 ? bomLines : undefined,
        isSaleable: formData.itemType === "PT" ? formData.isSaleable : undefined,
        isActive: ["FG", "PT", "RM", "SM"].includes(formData.itemType) ? formData.isActive : undefined,
        lotAbbreviation: formData.itemType === "FG" ? formData.lotAbbreviation : undefined,
        note: formData.itemType === "FG" ? formData.note : undefined,
      };
      
      // 조립 부품인 경우 추가 정보 저장
      if (formData.partType === "ASSEMBLY") {
        updates.installationType = formData.installationType || undefined;
        updates.assemblyType = formData.assemblyType || undefined;
        updates.sideSpecWidth = formData.sideSpecWidth || undefined;
        updates.sideSpecHeight = formData.sideSpecHeight || undefined;
        updates.assemblyLength = formData.assemblyLength || undefined;
        // 조립 부품 전개도 정보 저장
        updates.bendingDiagram = bendingDiagram || undefined;
        updates.bendingDetails = (formData as any).bendingDetails || undefined;
        updates.material = formData.material || undefined;
        updates.length = formData.length || undefined;
      }
      
      // 구매 부품인 경우 추가 정보 저장
      if (formData.partType === "PURCHASED" && formData.category1 === "electric_opener") {
        updates.electricOpenerPower = formData.electricOpenerPower || undefined;
        updates.electricOpenerVolt = formData.electricOpenerVolt || undefined;
        updates.electricOpenerCapacity = formData.electricOpenerCapacity || undefined;
      }
      
      // 가이드레일인 경우 추가 정보 저장 (절곡/구매 부품)
      if (formData.category3 === "가이드레일") {
        updates.guideRailModelType = formData.guideRailModelType || undefined;
        updates.guideRailModel = formData.guideRailModel || undefined;
      }
      

      
      // 절곡 부품인 경우 전개도 정보 저장
      if (formData.itemType === "PT" && formData.partType === "BENDING") {
        updates.bendingDiagram = bendingDiagram || undefined;
        updates.bendingDetails = (formData as any).bendingDetails || undefined;
        updates.material = formData.material || undefined;
        updates.length = formData.length || undefined;
        updates.bendingLength = formData.bendingLength || undefined;
        
        console.log("���곡 부품 수정:", {
          bendingDiagram: bendingDiagram ? "있음 (길이: " + bendingDiagram.length + ")" : "없음",
          bendingDetails: (formData as any).bendingDetails,
          material: formData.material,
          length: formData.length
        });
      }
      
      // 인정 정보 저장
      if (formData.certificationNumber) {
        updates.certificationNumber = formData.certificationNumber;
      }
      if (formData.certificationStartDate) {
        updates.certificationStartDate = formData.certificationStartDate;
      }
      if (formData.certificationEndDate) {
        updates.certificationEndDate = formData.certificationEndDate;
      }
      if (specificationFile && formData.specificationFileName) {
        updates.specificationFile = specificationFile;
        updates.specificationFileName = formData.specificationFileName;
      }
      if (certificationFile && formData.certificationFileName) {
        updates.certificationFile = certificationFile;
        updates.certificationFileName = formData.certificationFileName;
      }
      
      // 버전 관리 - 수정 시 수정 사유 입력 다이얼로그 표시
      setPendingUpdates(updates);
      setIsRevisionDialogOpen(true);
      return;
    }
    
    // 신규 등록의 경우에만 여기서 호출됨 (수정은 위의 return으로 차단)
  };

  // 수정 사유와 함께 품목 수정 저장
  const handleSaveWithRevision = () => {
    if (!revisionReason.trim()) {
      toast.error("���정 사유를 입력해주세요.");
      return;
    }
    
    if (!selectedItem || !pendingUpdates) return;
    
    // 버전 관리 - 수정 시 이력 저장
    const currentRevision = selectedItem.currentRevision || 0;
    const newRevisionNumber = currentRevision + 1;
    
    // 이전 데이터를 수정 이력에 저장
    const revision = {
      revisionNumber: newRevisionNumber,
      revisionDate: new Date().toISOString().split("T")[0],
      revisionBy: "관리자", // TODO: 실제 사용자 정보로 교체
      revisionReason: revisionReason,
      previousData: { ...selectedItem }
    };
    
    pendingUpdates.currentRevision = newRevisionNumber;
    pendingUpdates.revisions = [...(selectedItem.revisions || []), revision];
    
    // 버전 관리 다이얼로그 표시
    requestVersionUpdate(() => {
      updateItemMaster(selectedItem.id, pendingUpdates);
      toast.success("품목이 성공적으로 수정되었습니다.");
      setIsRevisionDialogOpen(false);
      setRevisionReason("");
      setPendingUpdates(null);
      resetForm();
    });
  };

  // 폼 초기화 및 리스트로 돌아가기
  const resetForm = () => {
    setView("list");
    setIsViewingHistory(false);
    setSelectedRevisionNumber(null);
    resetFormData();
  };

  // 수정 이력 조회 핸들러
  const handleViewRevisionHistory = (item: ItemMaster) => {
    setSelectedItemForHistory(item);
    setIsRevisionHistoryOpen(true);
  };

  // 품목 삭제 확인
  const confirmDelete = () => {
    if (itemToDelete) {
      deleteItemMaster(itemToDelete.id);
      toast.success("품목이 삭제되었습니다.");
      setIsDeleteDialogOpen(false);
      setItemToDelete(null);
    }
  };

  // 선택된 품목 토글
  const toggleItemSelection = (itemId: string) => {
    setSelectedItems(prev => {
      const newSet = new Set(prev);
      if (newSet.has(itemId)) {
        newSet.delete(itemId);
      } else {
        newSet.add(itemId);
      }
      return newSet;
    });
  };

  // 전체 선택/해제
  const toggleSelectAll = () => {
    if (selectedItems.size === filteredItems.length) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(filteredItems.map(item => item.id)));
    }
  };

  // 선택된 품목 일괄 삭제
  const confirmBulkDelete = () => {
    selectedItems.forEach(itemId => {
      deleteItemMaster(itemId);
    });
    toast.success(`${selectedItems.size}개 품목이 삭제되었습니다.`);
    setSelectedItems(new Set());
    setIsBulkDeleteDialogOpen(false);
  };

  // 전체 품목 삭제 (연관 데이터 포함)
  const confirmDeleteAll = () => {
    // 품목 마스터의 모든 품목코드 수집
    const allItemCodes = itemMasters.map(item => item.itemCode);
    
    // 1. 품목 마스터에서 모든 품목 삭제
    itemMasters.forEach(item => {
      deleteItemMaster(item.id);
    });
    
    // 2. 연관된 단가 데이터 삭제 (판매관리/회계관리 단가관리)
    const pricingToDelete = pricing.filter(p => allItemCodes.includes(p.itemCode));
    pricingToDelete.forEach(p => {
      deletePricing(p.id);
    });
    
    toast.success(`모든 품목 ${itemMasters.length}개와 연관된 단가 데이터 ${pricingToDelete.length}개가 삭제되었습니다.`);
    setIsDeleteAllDialogOpen(false);
    setSelectedItems(new Set());
  };

  // 하위 BOM 순서 변경 핸들러
  const handleReorderSubBOM = (parentItemCode: string, subBomIndex: number, direction: 'up' | 'down') => {
    const parentItem = itemMasters.find(item => item.itemCode === parentItemCode);
    if (!parentItem || !parentItem.bom || parentItem.bom.length <= 1) return;
    
    const newIndex = direction === 'up' ? subBomIndex - 1 : subBomIndex + 1;
    
    // 범위 체크
    if (newIndex < 0 || newIndex >= parentItem.bom.length) return;
    
    // BOM 배열 복사 및 순서 변경
    const newBom = [...parentItem.bom];
    [newBom[subBomIndex], newBom[newIndex]] = [newBom[newIndex], newBom[subBomIndex]];
    
    // 부모 품목 업데이트
    updateItemMaster(parentItem.id, {
      ...parentItem,
      bom: newBom
    });
    
    toast.success(`순서가 변경되었습니다.`);
    
    // 뷰 모드에서 선택된 아이템도 업데이트
    if (selectedItem && selectedItem.itemCode === parentItemCode) {
      setSelectedItem({
        ...selectedItem,
        bom: newBom
      });
    }
  };

  // 품목 유형 뱃지 색상
  const getItemTypeBadge = (type?: string) => {
    switch (type) {
      case "FG":
        return <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">제품</Badge>;
      case "PT":
        return <Badge variant="outline" className="bg-orange-50 text-orange-700 border-orange-200">부품</Badge>;
      case "SM":
        return <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">부자재</Badge>;
      case "RM":
        return <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">원자재</Badge>;
      case "CS":
        return <Badge variant="outline" className="bg-gray-50 dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-gray-200 dark:border-gray-700">소모품</Badge>;
      default:
        return <Badge variant="outline">-</Badge>;
    }
  };

  // 통계 데이터
  const stats = [
    {
      label: "전체 품목",
      value: itemMasters.length,
      icon: Package,
      iconColor: "text-blue-600"
    },
    {
      label: "제품",
      value: itemMasters.filter((i) => i.itemType === "FG").length,
      icon: Package,
      iconColor: "text-purple-600"
    },
    {
      label: "부품",
      value: itemMasters.filter((i) => i.itemType === "PT").length,
      icon: Package,
      iconColor: "text-orange-600"
    },
    {
      label: "부자재",
      value: itemMasters.filter((i) => i.itemType === "SM").length,
      icon: Package,
      iconColor: "text-green-600"
    },
    {
      label: "원자재",
      value: itemMasters.filter((i) => i.itemType === "RM").length,
      icon: Package,
      iconColor: "text-cyan-600"
    },
    {
      label: "소모품",
      value: itemMasters.filter((i) => i.itemType === "CS").length,
      icon: Package,
      iconColor: "text-gray-600"
    }
  ];

  // 리스트 뷰
  if (view === "list") {
    return (
      <PageLayout
        devMetadata={{
          componentName: '품목관리',
          pagePath: '/components/ItemManagement.tsx',
          description: '제품, 부품, 부자재, 원자재, 소모품 등록 및 관리 시스템',
          
          apis: [
            {
              endpoint: '/api/v1/items',
              method: 'GET',
              description: '품목 목록 조회',
              queryParams: [
                { name: 'page', type: 'number', required: false, description: '페이지 번호' },
                { name: 'search', type: 'string', required: false, description: '검색어' },
                { name: 'itemType', type: 'string', required: false, description: '품목 유형' },
              ],
              responseBody: {
                success: true,
                data: { items: [], total: 150 }
              }
            },
            {
              endpoint: '/api/v1/items',
              method: 'POST',
              description: '품목 등록',
              requestBody: {
                itemCode: 'PRD-0001',
                itemName: '방화셔터 3000x3000',
                itemType: 'PRODUCT',
              },
              responseBody: {
                success: true,
                data: { id: 'ITEM-1234567890' }
              }
            },
          ],
          
          dataStructures: [
            {
              name: 'ItemMaster',
              type: 'interface',
              fields: [
                { name: 'id', type: 'string', required: true, description: '고유 ID' },
                { name: 'itemCode', type: 'string', required: true, description: '품목 코드' },
                { name: 'itemName', type: 'string', required: true, description: '품목명' },
                { name: 'itemType', type: 'string', required: true, description: '품목 유형' },
              ],
            },
          ],
          
          dbSchema: [
            {
              tableName: 'items',
              columns: [
                { name: 'id', type: 'VARCHAR(50)', nullable: false, key: 'PK', description: '고유 식별자' },
                { name: 'item_code', type: 'VARCHAR(50)', nullable: false, description: '품목 코드' },
                { name: 'item_name', type: 'VARCHAR(200)', nullable: false, description: '품목명' },
                { name: 'item_type', type: 'ENUM', nullable: false, description: '품목 유형' },
              ],
              indexes: ['idx_item_code', 'idx_item_type'],
            },
          ],
          
          businessLogic: [
            {
              name: '품목 등록',
              description: '새로운 품목을 시스템에 등록',
              steps: [
                '품목 유형 선택',
                '품목 정보 입력',
                '품목 코드 자동 생성',
                '유효성 검사',
                'DataContext에 저장',
              ]
            },
          ],
        }}
      >
        <PageHeader
          title="품목 목록"
          description="제품, 부품, 부자재, 원자재, 소모품 등록 및 관리"
          icon={Package}
          actions={
            <ListActions
              onAdd={() => handleViewChange("create")}
              addText="품목 등록"
              selectedCount={selectedItems.size}
              onBulkDelete={() => setIsBulkDeleteDialogOpen(true)}
            />
          }
        />

        {/* 통계 카드 */}
        <StatCards stats={stats} />

        {/* 스크린 버전 히스토리 */}
        <ScreenVersionHistory
          versionHistory={screenVersion.versionHistory}
          title="품목 관리 수정 이력"
        />

        {/* 검색 및 필터 */}
        <Card>
          <CardContent className="p-4 md:p-6">
            <SearchFilter
              searchValue={searchTerm}
              onSearchChange={setSearchTerm}
              searchPlaceholder="품목코드, 품목명, 규격 검색..."
              filterButton={false}
              extraActions={
                <Select value={filterType} onValueChange={setFilterType}>
                  <SelectTrigger className="w-[180px]">
                    <SelectValue placeholder="품목 유형" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">전체 ({itemMasters.length})</SelectItem>
                    <SelectItem value="FG">제품 ({itemMasters.filter(i => i.itemType === 'FG').length})</SelectItem>
                    <SelectItem value="PT">부품 ({itemMasters.filter(i => i.itemType === 'PT').length})</SelectItem>
                    <SelectItem value="SM">부자재 ({itemMasters.filter(i => i.itemType === 'SM').length})</SelectItem>
                    <SelectItem value="RM">원자재 ({itemMasters.filter(i => i.itemType === 'RM').length})</SelectItem>
                    <SelectItem value="CS">소모품 ({itemMasters.filter(i => i.itemType === 'CS').length})</SelectItem>
                  </SelectContent>
                </Select>
              }
            />
          </CardContent>
        </Card>

        {/* 품목 목록 - 반응형 테이블 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-sm md:text-base">
              {filterType === "all" && `전체 목록 (${filteredItems.length}개)`}
              {filterType === "FG" && `제품 목록 (${filteredItems.length}개)`}
              {filterType === "PT" && `부품 목록 (${filteredItems.length}개)`}
              {filterType === "RM" && `원자재 목록 (${filteredItems.length}개)`}
              {filterType === "SM" && `부자재 목록 (${filteredItems.length}개)`}
              {filterType === "CS" && `소모품 목록 (${filteredItems.length}개)`}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <Tabs value={filterType} onValueChange={setFilterType} className="w-full">
              {/* 데스크톱 - 기본 테이블 탭 */}
              <div className="hidden lg:block mb-6">
                <TabsList>
                  <TabsTrigger value="all">
                    전체 ({itemMasters.length})
                  </TabsTrigger>
                  <TabsTrigger value="FG">
                    제품 ({itemMasters.filter(i => i.itemType === 'FG').length})
                  </TabsTrigger>
                  <TabsTrigger value="PT">
                    부품 ({itemMasters.filter(i => i.itemType === 'PT').length})
                  </TabsTrigger>
                  <TabsTrigger value="SM">
                    부자재 ({itemMasters.filter(i => i.itemType === 'SM').length})
                  </TabsTrigger>
                  <TabsTrigger value="RM">
                    원자재 ({itemMasters.filter(i => i.itemType === 'RM').length})
                  </TabsTrigger>
                  <TabsTrigger value="CS">
                    소모품 ({itemMasters.filter(i => i.itemType === 'CS').length})
                  </TabsTrigger>
                </TabsList>
              </div>

              {/* 모바일 - 커스텀 버튼 탭 */}
              <div className="lg:hidden mb-6">
                <div className="flex flex-wrap gap-2">
                  <button
                    onClick={() => setFilterType("all")}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
                      filterType === "all" 
                        ? "border-blue-500 bg-blue-50 shadow-sm" 
                        : "border-gray-200 hover:border-gray-300 hover:bg-gray-50"
                    }`}
                  >
                    <span className={`text-sm font-medium ${filterType === "all" ? "text-blue-700" : "text-gray-700"}`}>
                      전체
                    </span>
                    <span className={`text-lg font-semibold ${filterType === "all" ? "text-blue-600" : "text-gray-900"}`}>
                      {itemMasters.length}
                    </span>
                  </button>
                  <button
                    onClick={() => setFilterType("FG")}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
                      filterType === "FG" 
                        ? "border-purple-500 bg-purple-50 shadow-sm" 
                        : "border-gray-200 hover:border-gray-300 hover:bg-gray-50"
                    }`}
                  >
                    <span className={`text-sm font-medium ${filterType === "FG" ? "text-purple-700" : "text-gray-700"}`}>
                      제품
                    </span>
                    <span className={`text-lg font-semibold ${filterType === "FG" ? "text-purple-600" : "text-gray-900"}`}>
                      {itemMasters.filter(i => i.itemType === 'FG').length}
                    </span>
                  </button>
                  <button
                    onClick={() => setFilterType("PT")}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
                      filterType === "PT" 
                        ? "border-orange-500 bg-orange-50 shadow-sm" 
                        : "border-gray-200 hover:border-gray-300 hover:bg-gray-50"
                    }`}
                  >
                    <span className={`text-sm font-medium ${filterType === "PT" ? "text-orange-700" : "text-gray-700"}`}>
                      부품
                    </span>
                    <span className={`text-lg font-semibold ${filterType === "PT" ? "text-orange-600" : "text-gray-900"}`}>
                      {itemMasters.filter(i => i.itemType === 'PT').length}
                    </span>
                  </button>
                  <button
                    onClick={() => setFilterType("SM")}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
                      filterType === "SM" 
                        ? "border-cyan-500 bg-cyan-50 shadow-sm" 
                        : "border-gray-200 hover:border-gray-300 hover:bg-gray-50"
                    }`}
                  >
                    <span className={`text-sm font-medium ${filterType === "SM" ? "text-cyan-700" : "text-gray-700"}`}>
                      부자재
                    </span>
                    <span className={`text-lg font-semibold ${filterType === "SM" ? "text-cyan-600" : "text-gray-900"}`}>
                      {itemMasters.filter(i => i.itemType === 'SM').length}
                    </span>
                  </button>
                  <button
                    onClick={() => setFilterType("RM")}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
                      filterType === "RM" 
                        ? "border-green-500 bg-green-50 shadow-sm" 
                        : "border-gray-200 hover:border-gray-300 hover:bg-gray-50"
                    }`}
                  >
                    <span className={`text-sm font-medium ${filterType === "RM" ? "text-green-700" : "text-gray-700"}`}>
                      원자재
                    </span>
                    <span className={`text-lg font-semibold ${filterType === "RM" ? "text-green-600" : "text-gray-900"}`}>
                      {itemMasters.filter(i => i.itemType === 'RM').length}
                    </span>
                  </button>
                  <button
                    onClick={() => setFilterType("CS")}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
                      filterType === "CS" 
                        ? "border-gray-500 bg-gray-50 shadow-sm" 
                        : "border-gray-200 hover:border-gray-300 hover:bg-gray-50"
                    }`}
                  >
                    <span className={`text-sm font-medium ${filterType === "CS" ? "text-gray-700" : "text-gray-700"}`}>
                      소모품
                    </span>
                    <span className={`text-lg font-semibold ${filterType === "CS" ? "text-gray-900" : "text-gray-900"}`}>
                      {itemMasters.filter(i => i.itemType === 'CS').length}
                    </span>
                  </button>
                </div>
              </div>

              {/* 전체 탭 - 최소 정보만 */}
              <TabsContent value="all" className="mt-0">
                {/* 모바일/태블릿 카드 뷰 */}
                <div className="lg:hidden space-y-3">
                  {filteredItems.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground border rounded-lg">
                      검색 결과가 없습니다.
                    </div>
                  ) : (
                    paginatedItems.map((item, index) => (
                      <div 
                        key={`${item.id}-mobile-${index}`}
                        className="border rounded-lg p-4 space-y-3 bg-white dark:bg-card hover:bg-muted/50 transition-colors shadow-sm"
                      >
                        {/* 번호와 체크박스 */}
                        <div className="flex items-start gap-3">
                          <Checkbox
                            checked={selectedItems.has(item.id)}
                            onCheckedChange={() => toggleItemSelection(item.id)}
                            onClick={(e) => e.stopPropagation()}
                            className="mt-1"
                          />
                          <div className="flex-1 min-w-0 space-y-3">
                            {/* 번호 + 품목코드 */}
                            <div className="flex items-center gap-2 flex-wrap">
                              <Badge variant="outline" className="bg-gray-100 text-gray-700 font-mono text-xs">
                                #{filteredItems.length - (startIndex + index)}
                              </Badge>
                              <code className="text-xs bg-blue-50 text-blue-700 px-2 py-1 rounded font-mono">
                                {formatItemCodeForAssembly(item) || item.itemCode}
                              </code>
                            </div>
                            
                            {/* 품목명 */}
                            <div 
                              className="font-semibold text-base cursor-pointer hover:text-blue-600 transition-colors"
                              onClick={() => handleViewChange("view", item)}
                            >
                              {item.itemName}
                            </div>

                            {/* 품목 유형 및 규격 - 항상 표시 */}
                            <div className="space-y-2">
                              {/* 품목 유형 */}
                              <div>
                                <span className="text-muted-foreground text-xs">품목유형</span>
                                <div className="mt-1 flex items-center gap-2 flex-wrap">
                                  {getItemTypeBadge(item.itemType)}
                                  {item.itemType === 'PT' && (item as any).partType && (
                                    <Badge variant="outline" className="text-xs">
                                      {(item as any).partType === 'ASSEMBLY' ? '조립' :
                                       (item as any).partType === 'BENDING' ? '절곡' :
                                       (item as any).partType === 'PURCHASED' ? '구매' : ''}
                                    </Badge>
                                  )}
                                </div>
                              </div>

                              {/* 규격 정보 */}
                              <div>
                                <span className="text-muted-foreground text-xs">규격</span>
                                <div className="font-medium mt-1">
                                  {item.specification || '-'}
                                </div>
                              </div>

                              {/* 단위 정보 */}
                              {item.unit && (
                                <div>
                                  <span className="text-muted-foreground text-xs">단위</span>
                                  <div className="mt-1">
                                    <Badge variant="secondary" className="text-xs">{item.unit}</Badge>
                                  </div>
                                </div>
                              )}

                              {/* 조립 부품 세부정보 */}
                              {item.itemType === 'PT' && (item as any).partType === 'ASSEMBLY' && (
                                <>
                                  {/* 설치 유형 */}
                                  {(item as any).installationType && (
                                    <div>
                                      <span className="text-muted-foreground text-xs">설치 유형</span>
                                      <div className="mt-1">
                                        <Badge variant="outline" className="text-xs bg-blue-50 text-blue-700">
                                          {(item as any).installationType === 'wall' ? '벽면형 (R)' :
                                           (item as any).installationType === 'side' ? '측면형 (S)' :
                                           (item as any).installationType === 'standard' ? '표준형 (C)' :
                                           (item as any).installationType === 'steel' ? '스크린 (B)' :
                                           (item as any).installationType === 'iron' ? '철재 (T)' :
                                           (item as any).installationType}
                                        </Badge>
                                      </div>
                                    </div>
                                  )}

                                  {/* 측면 규격 */}
                                  {((item as any).sideSpecWidth || (item as any).sideSpecHeight) && (
                                    <div>
                                      <span className="text-muted-foreground text-xs">측면 규격</span>
                                      <div className="font-medium mt-1 text-sm">
                                        {(item as any).sideSpecWidth || '?'} × {(item as any).sideSpecHeight || '?'} mm
                                      </div>
                                    </div>
                                  )}

                                  {/* 길이 */}
                                  {(item as any).assemblyLength && (
                                    <div>
                                      <span className="text-muted-foreground text-xs">길이</span>
                                      <div className="font-medium mt-1 text-sm">
                                        {(item as any).assemblyLength} mm
                                      </div>
                                    </div>
                                  )}

                                  {/* 마감 */}
                                  {(item as any).finishing && (
                                    <div>
                                      <span className="text-muted-foreground text-xs">마감</span>
                                      <div className="mt-1">
                                        <Badge variant="secondary" className="text-xs bg-green-50 text-green-700">
                                          {(item as any).finishing}
                                        </Badge>
                                      </div>
                                    </div>
                                  )}
                                </>
                              )}
                            </div>

                            {/* 재고 정보 - 데이터가 있을 때만 표시 */}
                            {((item.safetyStock !== undefined && item.safetyStock !== null) || 
                              (item.currentStock !== undefined && item.currentStock !== null)) && (
                              <div className="grid grid-cols-2 gap-2 text-sm">
                                {(item.safetyStock !== undefined && item.safetyStock !== null) && (
                                  <div>
                                    <span className="text-muted-foreground text-xs">안전재고</span>
                                    <div className="font-medium mt-0.5">{item.safetyStock}</div>
                                  </div>
                                )}
                                {(item.currentStock !== undefined && item.currentStock !== null) && (
                                  <div>
                                    <span className="text-muted-foreground text-xs">현재고</span>
                                    <div className="font-medium mt-0.5">{item.currentStock}</div>
                                  </div>
                                )}
                              </div>
                            )}

                            {/* 버전 및 상태 정보 */}
                            <div className="flex items-center gap-2 flex-wrap">
                              <Badge variant="outline" className="bg-purple-50 text-purple-700 text-xs">
                                V{item.currentRevision || 0}
                              </Badge>
                              {item.useYN && (
                                <Badge 
                                  variant={item.useYN === 'Y' ? 'default' : 'secondary'}
                                  className="text-xs"
                                >
                                  {item.useYN === 'Y' ? '��용' : '미사용'}
                                </Badge>
                              )}
                              {item.status && (
                                <Badge variant="outline" className="text-xs">
                                  {item.status === 'active' ? '사용중' :
                                   item.status === 'development' ? '개발중' :
                                   item.status === 'inactive' ? '미사용' : 
                                   item.status === 'discontinued' ? '폐기' : item.status}
                                </Badge>
                              )}
                            </div>

                            {/* 등록 정보 - 데이터가 있을 때만 표시 */}
                            {((item as any).createdBy || item.createdAt) && (
                              <div className="text-xs text-muted-foreground flex items-center gap-3 pt-1 border-t">
                                {(item as any).createdBy && (
                                  <span>작성: {(item as any).createdBy}</span>
                                )}
                                {item.createdAt && (
                                  <span>{new Date(item.createdAt).toLocaleDateString('ko-KR')}</span>
                                )}
                              </div>
                            )}
                          </div>
                        </div>

                        {/* 액션 버튼 */}
                        <div className="flex items-center justify-end gap-1 pt-3 border-t">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewChange("view", item)}
                            className="h-9 px-3 flex-1 max-w-[100px]"
                          >
                            <Search className="h-4 w-4 mr-1.5" />
                            <span className="text-sm">상세</span>
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewChange("edit", item)}
                            className="h-9 px-3 flex-1 max-w-[100px]"
                          >
                            <Edit className="h-4 w-4 mr-1.5" />
                            <span className="text-sm">수정</span>
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setItemToDelete(item);
                              setIsDeleteDialogOpen(true);
                            }}
                            className="h-9 px-3"
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </div>
                      </div>
                    ))
                  )}
                </div>

                {/* 데스크톱 테이블 뷰 */}
                <div className="hidden lg:block rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-[50px]">
                          <Checkbox
                            checked={selectedItems.size === filteredItems.length && filteredItems.length > 0}
                            onCheckedChange={toggleSelectAll}
                          />
                        </TableHead>
                        <TableHead className="hidden md:table-cell">번호</TableHead>
                        <TableHead className="min-w-[100px]">품목코드</TableHead>
                        <TableHead className="min-w-[80px]">품목유형</TableHead>
                        <TableHead className="min-w-[120px]">품목명</TableHead>
                        <TableHead className="hidden md:table-cell">규격</TableHead>
                        <TableHead className="hidden md:table-cell">단위</TableHead>
                        <TableHead className="hidden lg:table-cell">품목 상태</TableHead>
                        <TableHead className="text-right min-w-[100px]">작업</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredItems.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
                            검색 결과가 없습니다.
                          </TableCell>
                        </TableRow>
                      ) : (
                        paginatedItems.map((item, index) => (
                          <TableRow 
                            key={`${item.id}-${index}`}
                            className="hover:bg-muted/50"
                          >
                            <TableCell onClick={(e) => e.stopPropagation()}>
                              <Checkbox
                                checked={selectedItems.has(item.id)}
                                onCheckedChange={() => toggleItemSelection(item.id)}
                              />
                            </TableCell>
                            <TableCell 
                              className="text-muted-foreground cursor-pointer hidden md:table-cell" 
                              onClick={() => handleViewChange("view", item)}
                            >
                              {filteredItems.length - (startIndex + index)}
                            </TableCell>
                            <TableCell 
                              className="cursor-pointer" 
                              onClick={() => handleViewChange("view", item)}
                            >
                              <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                {formatItemCodeForAssembly(item) || '-'}
                              </code>
                            </TableCell>
                            <TableCell 
                              className="cursor-pointer" 
                              onClick={() => handleViewChange("view", item)}
                            >
                              {getItemTypeBadge(item.itemType)}
                              {item.itemType === 'PT' && (item as any).partType && (
                                <Badge variant="outline" className="ml-1 bg-purple-50 text-purple-700 text-xs hidden lg:inline-flex">
                                  {(item as any).partType === 'ASSEMBLY' ? '조립' :
                                   (item as any).partType === 'BENDING' ? '절곡' :
                                   (item as any).partType === 'PURCHASED' ? '구매' : ''}
                                </Badge>
                              )}
                            </TableCell>
                            <TableCell 
                              className="cursor-pointer" 
                              onClick={() => handleViewChange("view", item)}
                            >
                              <div className="flex items-center gap-2">
                                <span className="truncate max-w-[150px] md:max-w-none">{item.itemName}</span>
                                {item.itemCode.includes('샘플') && (
                                  <Badge variant="outline" className="bg-green-50 text-green-700 text-xs hidden lg:inline-flex">
                                    견적산출용
                                  </Badge>
                                )}
                              </div>
                            </TableCell>
                            <TableCell 
                              className="text-sm text-muted-foreground cursor-pointer hidden md:table-cell" 
                              onClick={() => handleViewChange("view", item)}
                            >
                              {item.specification || "-"}
                            </TableCell>
                            <TableCell 
                              className="cursor-pointer hidden md:table-cell" 
                              onClick={() => handleViewChange("view", item)}
                            >
                              <Badge variant="secondary">{item.unit || "-"}</Badge>
                            </TableCell>
                            <TableCell 
                              className="cursor-pointer hidden lg:table-cell" 
                              onClick={() => handleViewChange("view", item)}
                            >
                              {item.status === 'active' && (
                                <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                              )}
                              {item.status === 'inactive' && (
                                <Badge variant="outline" className="bg-gray-50 text-gray-700 text-xs">미사용</Badge>
                              )}
                              {item.status === 'development' && (
                                <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">개발중</Badge>
                              )}
                              {item.status === 'discontinued' && (
                                <Badge variant="outline" className="bg-red-50 text-red-700 text-xs">폐기</Badge>
                              )}
                              {!item.status && (
                                <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                              )}
                            </TableCell>
                            <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
                              <TableActionButtons
                                onView={() => handleViewChange("view", item)}
                                onEdit={() => handleViewChange("edit", item)}
                                onDelete={() => {
                                  setItemToDelete(item);
                                  setIsDeleteDialogOpen(true);
                                }}
                              />
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
                
                {/* 페이지네이션 */}
                {totalPages > 1 && (
                  <div className="flex items-center justify-between mt-4">
                    <div className="text-sm text-muted-foreground">
                      전체 {filteredItems.length}개 중 {startIndex + 1}-{Math.min(endIndex, filteredItems.length)}개 표시
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(1)}
                        disabled={currentPage === 1}
                      >
                        처음
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                        disabled={currentPage === 1}
                      >
                        <ChevronLeft className="h-4 w-4" />
                      </Button>
                      <span className="text-sm">
                        {currentPage} / {totalPages}
                      </span>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                        disabled={currentPage === totalPages}
                      >
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(totalPages)}
                        disabled={currentPage === totalPages}
                      >
                        마지막
                      </Button>
                    </div>
                  </div>
                )}
              </TabsContent>

              {/* 제품(FG) 탭 */}
              <TabsContent value="FG" className="mt-0">
                {/* 모바일/태블릿 카드 뷰 */}
                <div className="lg:hidden space-y-3">
                  {fgItems.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground border rounded-lg">
                      검색 결과가 없습니다.
                    </div>
                  ) : (
                    fgPagination.paginatedItems.map((item, index) => (
                      <div 
                        key={`${item.id}-fg-mobile-${index}`}
                        className="border rounded-lg p-4 space-y-3 bg-white dark:bg-card hover:bg-muted/50 transition-colors cursor-pointer"
                        onClick={() => handleViewChange("view", item)}
                      >
                        <div className="space-y-2">
                          <div className="flex items-center gap-2 flex-wrap">
                            <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                              {item.itemCode}
                            </code>
                            <Badge variant="outline" className="bg-purple-50 text-purple-700 text-xs">
                              V{(item as any).currentRevision || 0}
                            </Badge>
                          </div>
                          <div className="font-medium">
                            {item.itemName}
                          </div>
                          {(item as any).productName && (
                            <div className="text-sm text-muted-foreground">
                              상품명: {(item as any).productName}
                            </div>
                          )}
                          {(item as any).certificationNumber && (
                            <div className="text-sm">
                              <span className="text-muted-foreground">인정번호: </span>
                              {(item as any).certificationNumber}
                            </div>
                          )}
                          {item.createdAt && (
                            <div className="text-xs text-muted-foreground">
                              {new Date(item.createdAt).toLocaleDateString('ko-KR')}
                            </div>
                          )}
                        </div>
                        <div className="flex items-center justify-end gap-1 pt-2 border-t" onClick={(e) => e.stopPropagation()}>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewChange("edit", item)}
                            className="h-8 px-3"
                          >
                            <Edit className="h-4 w-4 mr-1" />
                            <span className="text-xs">수정</span>
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setItemToDelete(item);
                              setIsDeleteDialogOpen(true);
                            }}
                            className="h-8 px-2"
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </div>
                      </div>
                    ))
                  )}
                </div>

                {/* 데스크톱 테이블 뷰 */}
                <div className="hidden lg:block rounded-md border overflow-hidden">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-16">번호</TableHead>
                        <TableHead className="w-24">로트약자</TableHead>
                        <TableHead className="w-32">제품명</TableHead>
                        <TableHead className="w-32 hidden xl:table-cell">상품명</TableHead>
                        <TableHead className="w-28 hidden xl:table-cell">인정번호</TableHead>
                        <TableHead className="w-32 hidden 2xl:table-cell">인정기간</TableHead>
                        <TableHead className="w-20 hidden xl:table-cell">버전</TableHead>
                        <TableHead className="w-24 hidden xl:table-cell">등록일</TableHead>
                        <TableHead className="w-24 hidden xl:table-cell">품목 상태</TableHead>
                        <TableHead className="w-32 hidden 2xl:table-cell">비고</TableHead>
                        <TableHead className="text-right w-24">작업</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {fgItems.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={11} className="text-center py-8 text-muted-foreground">
                            검색 결과가 없습니다.
                          </TableCell>
                        </TableRow>
                      ) : (
                        fgPagination.paginatedItems.map((item, index) => (
                          <TableRow 
                            key={`${item.id}-${index}`}
                            className="cursor-pointer hover:bg-muted/50"
                            onClick={() => handleViewChange("view", item)}
                          >
                            <TableCell className="text-muted-foreground text-center">{fgItems.length - (fgPagination.startIndex + index)}</TableCell>
                            <TableCell>
                              <code className="text-xs bg-gray-100 px-2 py-1 rounded truncate block max-w-[100px]">
                                {item.itemCode}
                              </code>
                            </TableCell>
                            <TableCell className="font-medium">
                              <div className="truncate max-w-[120px]">{item.itemName}</div>
                            </TableCell>
                            <TableCell className="hidden xl:table-cell">
                              <div className="truncate max-w-[120px]">{(item as any).productName || '-'}</div>
                            </TableCell>
                            <TableCell className="hidden xl:table-cell">
                              <span className="text-sm truncate block max-w-[100px]">
                                {(item as any).certificationNumber || '-'}
                              </span>
                            </TableCell>
                            <TableCell className="hidden 2xl:table-cell">
                              <span className="text-xs truncate block max-w-[120px]">
                                {(item as any).certificationStartDate && (item as any).certificationEndDate 
                                  ? `${(item as any).certificationStartDate} ~ ${(item as any).certificationEndDate}`
                                  : '-'}
                              </span>
                            </TableCell>
                            <TableCell className="hidden xl:table-cell">
                              <span className="text-xs">
                                V{(item as any).currentRevision || 0}
                              </span>
                            </TableCell>
                            <TableCell className="hidden xl:table-cell">
                              <span className="text-xs">
                                {item.createdAt ? new Date(item.createdAt).toLocaleDateString('ko-KR') : '-'}
                              </span>
                            </TableCell>
                            <TableCell className="hidden xl:table-cell">
                              {item.status === 'active' && (
                                <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                              )}
                              {item.status === 'inactive' && (
                                <Badge variant="outline" className="bg-gray-50 text-gray-700 text-xs">미사용</Badge>
                              )}
                              {item.status === 'development' && (
                                <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">개발중</Badge>
                              )}
                              {item.status === 'discontinued' && (
                                <Badge variant="outline" className="bg-red-50 text-red-700 text-xs">폐기</Badge>
                              )}
                              {!item.status && (
                                <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                              )}
                            </TableCell>
                            <TableCell className="hidden 2xl:table-cell">
                              <span className="text-xs text-muted-foreground truncate block max-w-[120px]">
                                {(item as any).remarks || '-'}
                              </span>
                            </TableCell>
                            <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
                              <div className="flex items-center justify-end gap-1">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => handleViewChange("edit", item)}
                                  className="h-8 w-8 p-0"
                                >
                                  <Edit className="h-4 w-4" />
                                </Button>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => {
                                    setItemToDelete(item);
                                    setIsDeleteDialogOpen(true);
                                  }}
                                  className="h-8 w-8 p-0"
                                >
                                  <Trash2 className="h-4 w-4 text-red-600" />
                                </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
                
                {/* 페이지네이션 */}
                {totalPages > 1 && (
                  <div className="flex items-center justify-between mt-4">
                    <div className="text-sm text-muted-foreground">
                      전체 {filteredItems.length}개 중 {startIndex + 1}-{Math.min(endIndex, filteredItems.length)}개 표시
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(1)}
                        disabled={currentPage === 1}
                      >
                        처음
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                        disabled={currentPage === 1}
                      >
                        <ChevronLeft className="h-4 w-4" />
                      </Button>
                      <span className="text-sm">
                        {currentPage} / {totalPages}
                      </span>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                        disabled={currentPage === totalPages}
                      >
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(totalPages)}
                        disabled={currentPage === totalPages}
                      >
                        마지막
                      </Button>
                    </div>
                  </div>
                )}
              </TabsContent>

              {/* 부품(PT) 탭 - 부품 유형별 섹션 */}
              <TabsContent value="PT" className="mt-0 space-y-6">
                {/* 조립 부품 (ASSEMBLY) */}
                {assemblyItems.length > 0 && (
                  <div>
                    <div className="flex items-center gap-2 mb-3">
                      <Badge variant="outline" className="bg-blue-50 text-blue-700">조립 부품</Badge>
                      <span className="text-sm text-muted-foreground">
                        ({assemblyItems.length}개)
                      </span>
                    </div>
                    
                    {/* 모바일/태블릿 카드 뷰 */}
                    <div className="lg:hidden space-y-3">
                      {assemblyPagination.paginatedItems.map((item, index) => (
                        <div 
                          key={`${item.id}-assembly-mobile-${index}`}
                          className="border rounded-lg p-4 space-y-3 bg-blue-50/20 hover:bg-blue-50/50 transition-colors cursor-pointer"
                          onClick={() => handleViewChange("view", item)}
                        >
                          <div className="space-y-2">
                            <div className="flex items-center gap-2 flex-wrap">
                              <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                {formatItemCodeForAssembly(item) || '-'}
                              </code>
                              {item.status === 'active' && (
                                <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                              )}
                              {item.status === 'development' && (
                                <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">개발중</Badge>
                              )}
                            </div>
                            <div className="font-medium">
                              {item.itemName || '-'}
                            </div>
                            {(item as any).installationType && (
                              <div className="text-sm">
                                {(item as any).installationType === 'wall' ? '벽면형 (R)' :
                                 (item as any).installationType === 'side' ? '측면형 (S)' :
                                 (item as any).installationType === 'steel' ? '스틸 (B)' :
                                 (item as any).installationType === 'iron' ? '철재 (T)' : '-'}
                              </div>
                            )}
                            {(item as any).assemblyLength && (
                              <div className="text-sm text-muted-foreground">
                                길이: {(item as any).assemblyLength}mm
                              </div>
                            )}
                            {item.bom && item.bom.length > 0 && (
                              <div>
                                <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">
                                  BOM {item.bom.length}개
                                </Badge>
                              </div>
                            )}
                          </div>
                          <div className="flex items-center justify-end gap-1 pt-2 border-t" onClick={(e) => e.stopPropagation()}>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleViewChange("edit", item)}
                              className="h-8 px-3"
                            >
                              <Edit className="h-4 w-4 mr-1" />
                              <span className="text-xs">수정</span>
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                setItemToDelete(item);
                                setIsDeleteDialogOpen(true);
                              }}
                              className="h-8 px-2"
                            >
                              <Trash2 className="h-4 w-4 text-red-600" />
                            </Button>
                          </div>
                        </div>
                      ))}
                    </div>

                    {/* 데스크톱 테이블 뷰 */}
                    <div className="hidden lg:block rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow className="bg-blue-50/50">
                            <TableHead className="w-12">번호</TableHead>
                            <TableHead className="min-w-[140px]">품목코드</TableHead>
                            <TableHead className="min-w-[100px]">품목명</TableHead>
                            <TableHead className="min-w-[100px]">품목 상태</TableHead>
                            <TableHead className="min-w-[100px]">설치유형</TableHead>
                            <TableHead className="min-w-[80px]">마감</TableHead>
                            <TableHead className="min-w-[100px]">측면규격</TableHead>
                            <TableHead className="min-w-[80px]">길이</TableHead>
                            <TableHead className="min-w-[60px]">단위</TableHead>
                            <TableHead className="min-w-[60px]">BOM</TableHead>
                            <TableHead className="min-w-[80px]">전개도</TableHead>
                            <TableHead className="min-w-[80px]">작성자</TableHead>
                            <TableHead className="min-w-[100px]">등록일</TableHead>
                            <TableHead className="min-w-[80px]">버전관리</TableHead>
                            <TableHead className="text-right min-w-[100px]">작업</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {assemblyPagination.paginatedItems.map((item, index) => (
                            <TableRow 
                              key={`${item.id}-${index}`}
                              className="cursor-pointer hover:bg-muted/50"
                              onClick={() => handleViewChange("view", item)}
                            >
                              <TableCell className="text-muted-foreground text-center">{index + 1}</TableCell>
                              <TableCell>
                                <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                  {formatItemCodeForAssembly(item) || '-'}
                                </code>
                              </TableCell>
                              <TableCell className="font-medium">{item.itemName || '-'}</TableCell>
                              <TableCell>
                                {item.status === 'active' && (
                                  <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                                )}
                                {item.status === 'inactive' && (
                                  <Badge variant="outline" className="bg-gray-50 text-gray-700 text-xs">미사용</Badge>
                                )}
                                {item.status === 'development' && (
                                  <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">개발중</Badge>
                                )}
                                {item.status === 'discontinued' && (
                                  <Badge variant="outline" className="bg-red-50 text-red-700 text-xs">폐기</Badge>
                                )}
                                {!item.status && (
                                  <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                                )}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).installationType === 'wall' ? (
                                  <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">벽면형 (R)</Badge>
                                ) : (item as any).installationType === 'side' ? (
                                  <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">측면형 (S)</Badge>
                                ) : (item as any).installationType === 'steel' ? (
                                  <Badge variant="outline" className="bg-gray-50 text-gray-700 text-xs">스틸 (B)</Badge>
                                ) : (item as any).installationType === 'iron' ? (
                                  <Badge variant="outline" className="bg-gray-50 text-gray-700 text-xs">철재 (T)</Badge>
                                ) : <span className="text-xs text-muted-foreground">-</span>}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).finishing ? (
                                  <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                    {(item as any).finishing}
                                  </code>
                                ) : <span className="text-xs text-muted-foreground">-</span>}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).sideSpecWidth && (item as any).sideSpecHeight ? (
                                  <span className="text-xs">
                                    {(item as any).sideSpecWidth} × {(item as any).sideSpecHeight}
                                  </span>
                                ) : <span className="text-xs text-muted-foreground">-</span>}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).assemblyLength ? `${(item as any).assemblyLength}mm` : <span className="text-xs text-muted-foreground">-</span>}
                              </TableCell>
                              <TableCell>
                                <Badge variant="secondary" className="text-xs">{item.unit || '-'}</Badge>
                              </TableCell>
                              <TableCell>
                                {item.bom && item.bom.length > 0 ? (
                                  <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">
                                    {item.bom.length}개
                                  </Badge>
                                ) : (
                                  <span className="text-xs text-muted-foreground">-</span>
                                )}
                              </TableCell>
                              <TableCell onClick={(e) => e.stopPropagation()}>
                                {(item as any).bendingDiagram ? (
                                  <div className="flex items-center gap-2">
                                    <img 
                                      src={(item as any).bendingDiagram} 
                                      alt="전개도"
                                      className="h-10 w-10 object-cover rounded border cursor-pointer hover:scale-110 transition-transform"
                                      onClick={() => window.open((item as any).bendingDiagram, '_blank')}
                                    />
                                  </div>
                                ) : (
                                  <span className="text-xs text-muted-foreground">-</span>
                                )}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).createdBy || '관리자'}
                              </TableCell>
                              <TableCell className="text-sm text-muted-foreground">
                                {item.createdAt ? new Date(item.createdAt).toLocaleDateString('ko-KR') : '-'}
                              </TableCell>
                              <TableCell>
                                <div className="flex flex-col gap-1">
                                  <Badge variant="outline" className="bg-purple-50 text-purple-700 text-xs w-fit">
                                    V{item.currentRevision || 0}
                                  </Badge>
                                  {(item.revisions?.length || 0) > 0 && (
                                    <span className="text-xs text-muted-foreground">
                                      {item.revisions?.length}회 수정
                                    </span>
                                  )}
                                </div>
                              </TableCell>
                              <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
                                <div className="flex items-center justify-end gap-2">
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => handleViewChange("edit", item)}
                                  >
                                    <Edit className="h-4 w-4" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => {
                                      setItemToDelete(item);
                                      setIsDeleteDialogOpen(true);
                                    }}
                                  >
                                    <Trash2 className="h-4 w-4 text-red-600" />
                                  </Button>
                                </div>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  </div>
                )}

                {/* 절곡 부품 (BENDING) */}
                {bendingItems.length > 0 && (
                  <div>
                    <div className="flex items-center gap-2 mb-3">
                      <Badge variant="outline" className="bg-purple-50 text-purple-700">절곡 부품</Badge>
                      <span className="text-sm text-muted-foreground">
                        ({bendingItems.length}개)
                      </span>
                    </div>
                    
                    {/* 모바일/태블릿 카드 뷰 */}
                    <div className="lg:hidden space-y-3">
                      {filteredItems.filter(item => (item as any).partType === 'BENDING').map((item, index) => (
                        <div 
                          key={`${item.id}-bending-mobile-${index}`}
                          className="border rounded-lg p-4 space-y-3 bg-purple-50/20 hover:bg-purple-50/50 transition-colors cursor-pointer"
                          onClick={() => handleViewChange("view", item)}
                        >
                          <div className="space-y-2">
                            <div className="flex items-center gap-2 flex-wrap">
                              <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                {formatItemCodeForAssembly(item) || '-'}
                              </code>
                              {item.status === 'active' && (
                                <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                              )}
                            </div>
                            <div className="font-medium">
                              {item.itemName}
                            </div>
                            {(item as any).material && (
                              <div className="text-sm text-muted-foreground">
                                재질: {(item as any).material}
                              </div>
                            )}
                            {(item as any).length && (
                              <div className="text-sm text-muted-foreground">
                                길이: {(item as any).length}mm
                              </div>
                            )}
                            {(item as any).bendingDetails && (item as any).bendingDetails.length > 0 && (
                              <div>
                                <Badge variant="outline" className="bg-purple-50 text-purple-700 text-xs">
                                  절곡 {(item as any).bendingDetails.length}회
                                </Badge>
                              </div>
                            )}
                          </div>
                          <div className="flex items-center justify-end gap-1 pt-2 border-t" onClick={(e) => e.stopPropagation()}>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleViewChange("edit", item)}
                              className="h-8 px-3"
                            >
                              <Edit className="h-4 w-4 mr-1" />
                              <span className="text-xs">수정</span>
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                setItemToDelete(item);
                                setIsDeleteDialogOpen(true);
                              }}
                              className="h-8 px-2"
                            >
                              <Trash2 className="h-4 w-4 text-red-600" />
                            </Button>
                          </div>
                        </div>
                      ))}
                    </div>

                    {/* 데스크톱 테이블 뷰 */}
                    <div className="hidden lg:block rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow className="bg-purple-50/50">
                            <TableHead>번호</TableHead>
                            <TableHead>품목코드</TableHead>
                            <TableHead>품목명</TableHead>
                            <TableHead>품목 상태</TableHead>
                            <TableHead>재질</TableHead>
                            <TableHead>모양&길이</TableHead>
                            <TableHead>음영</TableHead>
                            <TableHead>A각</TableHead>
                            <TableHead>폭 합계</TableHead>
                            <TableHead>절곡회수</TableHead>
                            <TableHead>전개도</TableHead>
                            <TableHead>작성자</TableHead>
                            <TableHead>등록일</TableHead>
                            <TableHead>버전관리</TableHead>
                            <TableHead className="text-right">작업</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {filteredItems.filter(item => (item as any).partType === 'BENDING').map((item, index) => (
                            <TableRow 
                              key={`${item.id}-${index}`}
                              className="cursor-pointer hover:bg-muted/50"
                              onClick={() => handleViewChange("view", item)}
                            >
                              <TableCell className="text-muted-foreground">{index + 1}</TableCell>
                              <TableCell>
                                <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                  {formatItemCodeForAssembly(item) || '-'}
                                </code>
                              </TableCell>
                              <TableCell>{item.itemName}</TableCell>
                              <TableCell>
                                {item.status === 'active' && (
                                  <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                                )}
                                {item.status === 'inactive' && (
                                  <Badge variant="outline" className="bg-gray-50 text-gray-700 text-xs">미사용</Badge>
                                )}
                                {item.status === 'development' && (
                                  <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">개발중</Badge>
                                )}
                                {item.status === 'discontinued' && (
                                  <Badge variant="outline" className="bg-red-50 text-red-700 text-xs">폐기</Badge>
                                )}
                                {!item.status && (
                                  <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                                )}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).material || '-'}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).length ? `${(item as any).length}mm` : '-'}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).shade ? (
                                  <span className="text-xs">{(item as any).shade}</span>
                                ) : <span className="text-xs text-muted-foreground">-</span>}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).aAngle ? (
                                  <span className="text-xs">{(item as any).aAngle}°</span>
                                ) : <span className="text-xs text-muted-foreground">-</span>}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).widthSum ? (
                                  <span className="text-xs">{(item as any).widthSum}</span>
                                ) : <span className="text-xs text-muted-foreground">-</span>}
                              </TableCell>
                              <TableCell>
                                {(item as any).bendingDetails && (item as any).bendingDetails.length > 0 ? (
                                  <Badge variant="outline" className="bg-purple-50 text-purple-700 text-xs">
                                    {(item as any).bendingDetails.length}회
                                  </Badge>
                                ) : (
                                  <span className="text-xs text-muted-foreground">-</span>
                                )}
                              </TableCell>
                              <TableCell onClick={(e) => e.stopPropagation()}>
                                {(item as any).bendingDiagram ? (
                                  <div className="flex items-center gap-2">
                                    <img 
                                      src={(item as any).bendingDiagram} 
                                      alt="전개도"
                                      className="h-10 w-10 object-cover rounded border cursor-pointer hover:scale-110 transition-transform"
                                      onClick={() => window.open((item as any).bendingDiagram, '_blank')}
                                    />
                                  </div>
                                ) : (
                                  <span className="text-xs text-muted-foreground">-</span>
                                )}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).createdBy || '관리자'}
                              </TableCell>
                              <TableCell className="text-sm text-muted-foreground">
                                {item.createdAt ? new Date(item.createdAt).toLocaleDateString('ko-KR') : '-'}
                              </TableCell>
                              <TableCell>
                                <div className="flex flex-col gap-1">
                                  <Badge variant="outline" className="bg-purple-50 text-purple-700 text-xs w-fit">
                                    V{item.currentRevision || 0}
                                  </Badge>
                                  {(item.revisions?.length || 0) > 0 && (
                                    <span className="text-xs text-muted-foreground">
                                      {item.revisions?.length}회 수정
                                    </span>
                                  )}
                                </div>
                              </TableCell>
                              <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
                                <div className="flex items-center justify-end gap-2">
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => handleViewChange("edit", item)}
                                  >
                                    <Edit className="h-4 w-4" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => {
                                      setItemToDelete(item);
                                      setIsDeleteDialogOpen(true);
                                    }}
                                  >
                                    <Trash2 className="h-4 w-4 text-red-600" />
                                  </Button>
                                </div>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  </div>
                )}

                {/* 구매 부품 (PURCHASED) */}
                {filteredItems.filter(item => (item as any).partType === 'PURCHASED').length > 0 && (
                  <div>
                    <div className="flex items-center gap-2 mb-3">
                      <Badge variant="outline" className="bg-green-50 text-green-700">구매 부품</Badge>
                      <span className="text-sm text-muted-foreground">
                        ({filteredItems.filter(item => (item as any).partType === 'PURCHASED').length}개)
                      </span>
                    </div>
                    
                    {/* 모바일/태블릿 카드 뷰 */}
                    <div className="lg:hidden space-y-3">
                      {filteredItems.filter(item => (item as any).partType === 'PURCHASED').map((item, index) => (
                        <div 
                          key={`${item.id}-purchased-mobile-${index}`}
                          className="border rounded-lg p-4 space-y-3 bg-green-50/20 hover:bg-green-50/50 transition-colors cursor-pointer"
                          onClick={() => handleViewChange("view", item)}
                        >
                          <div className="space-y-2">
                            <div className="flex items-center gap-2 flex-wrap">
                              <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                {formatItemCodeForAssembly(item) || '-'}
                              </code>
                              {item.status === 'active' && (
                                <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                              )}
                            </div>
                            <div className="font-medium">
                              {item.itemName}
                            </div>
                            {item.specification && (
                              <div className="text-sm text-muted-foreground">
                                규격: {item.specification}
                              </div>
                            )}
                            {item.bom && item.bom.length > 0 && (
                              <div>
                                <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">
                                  BOM {item.bom.length}개
                                </Badge>
                              </div>
                            )}
                          </div>
                          <div className="flex items-center justify-end gap-1 pt-2 border-t" onClick={(e) => e.stopPropagation()}>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleViewChange("edit", item)}
                              className="h-8 px-3"
                            >
                              <Edit className="h-4 w-4 mr-1" />
                              <span className="text-xs">수정</span>
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                setItemToDelete(item);
                                setIsDeleteDialogOpen(true);
                              }}
                              className="h-8 px-2"
                            >
                              <Trash2 className="h-4 w-4 text-red-600" />
                            </Button>
                          </div>
                        </div>
                      ))}
                    </div>

                    {/* 데스크톱 테이블 뷰 */}
                    <div className="hidden lg:block rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow className="bg-green-50/50">
                            <TableHead>번호</TableHead>
                            <TableHead>품목코드</TableHead>
                            <TableHead>품목명</TableHead>
                            <TableHead>품목 상태</TableHead>
                            <TableHead>규격</TableHead>
                            <TableHead>단위</TableHead>
                            <TableHead>BOM</TableHead>
                            <TableHead>작성자</TableHead>
                            <TableHead>등록일</TableHead>
                            <TableHead>버전관리</TableHead>
                            <TableHead className="text-right">작업</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {filteredItems.filter(item => (item as any).partType === 'PURCHASED').map((item, index) => (
                            <TableRow 
                              key={`${item.id}-${index}`}
                              className="cursor-pointer hover:bg-muted/50"
                              onClick={() => handleViewChange("view", item)}
                            >
                              <TableCell className="text-muted-foreground">{index + 1}</TableCell>
                              <TableCell>
                                <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                  {formatItemCodeForAssembly(item) || '-'}
                                </code>
                              </TableCell>
                              <TableCell>{item.itemName}</TableCell>
                              <TableCell>
                                {item.status === 'active' && (
                                  <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                                )}
                                {item.status === 'inactive' && (
                                  <Badge variant="outline" className="bg-gray-50 text-gray-700 text-xs">미사용</Badge>
                                )}
                                {item.status === 'development' && (
                                  <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">개발중</Badge>
                                )}
                                {item.status === 'discontinued' && (
                                  <Badge variant="outline" className="bg-red-50 text-red-700 text-xs">폐기</Badge>
                                )}
                                {!item.status && (
                                  <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                                )}
                              </TableCell>
                              <TableCell className="text-sm text-muted-foreground">
                                {item.specification || '-'}
                              </TableCell>
                              <TableCell>
                                <Badge variant="secondary" className="text-xs">{item.unit || '-'}</Badge>
                              </TableCell>
                              <TableCell>
                                {item.bom && item.bom.length > 0 ? (
                                  <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">
                                    {item.bom.length}개
                                  </Badge>
                                ) : (
                                  <span className="text-xs text-muted-foreground">-</span>
                                )}
                              </TableCell>
                              <TableCell className="text-sm">
                                {(item as any).createdBy || '관리자'}
                              </TableCell>
                              <TableCell className="text-sm text-muted-foreground">
                                {item.createdAt ? new Date(item.createdAt).toLocaleDateString('ko-KR') : '-'}
                              </TableCell>
                              <TableCell>
                                <div className="flex flex-col gap-1">
                                  <Badge variant="outline" className="bg-purple-50 text-purple-700 text-xs w-fit">
                                    V{item.currentRevision || 0}
                                  </Badge>
                                  {(item.revisions?.length || 0) > 0 && (
                                    <span className="text-xs text-muted-foreground">
                                      {item.revisions?.length}회 수정
                                    </span>
                                  )}
                                </div>
                              </TableCell>
                              <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
                                <div className="flex items-center justify-end gap-2">
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => handleViewChange("edit", item)}
                                  >
                                    <Edit className="h-4 w-4" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => {
                                      setItemToDelete(item);
                                      setIsDeleteDialogOpen(true);
                                    }}
                                  >
                                    <Trash2 className="h-4 w-4 text-red-600" />
                                  </Button>
                                </div>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  </div>
                )}

                {/* 부품 유형이 없는 경우 */}
                {filteredItems.filter(item => !(item as any).partType).length > 0 && (
                  <div>
                    <div className="flex items-center gap-2 mb-3">
                      <Badge variant="outline" className="bg-gray-50 text-gray-700">미분류 부품</Badge>
                      <span className="text-sm text-muted-foreground">
                        ({filteredItems.filter(item => !(item as any).partType).length}개)
                      </span>
                    </div>
                    
                    {/* 모바일/태블릿 카드 뷰 */}
                    <div className="lg:hidden space-y-3">
                      {filteredItems.filter(item => !(item as any).partType).map((item, index) => (
                        <div 
                          key={`${item.id}-unclassified-mobile-${index}`}
                          className="border rounded-lg p-4 space-y-3 bg-white hover:bg-muted/50 transition-colors cursor-pointer"
                          onClick={() => handleViewChange("view", item)}
                        >
                          <div className="space-y-2">
                            <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                              {formatItemCodeForAssembly(item) || '-'}
                            </code>
                            <div className="font-medium">
                              {item.itemName}
                            </div>
                            {item.specification && (
                              <div className="text-sm text-muted-foreground">
                                규격: {item.specification}
                              </div>
                            )}
                            {item.unit && (
                              <div>
                                <Badge variant="secondary" className="text-xs">{item.unit}</Badge>
                              </div>
                            )}
                          </div>
                          <div className="flex items-center justify-end gap-1 pt-2 border-t" onClick={(e) => e.stopPropagation()}>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleViewChange("edit", item)}
                              className="h-8 px-3"
                            >
                              <Edit className="h-4 w-4 mr-1" />
                              <span className="text-xs">수정</span>
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                setItemToDelete(item);
                                setIsDeleteDialogOpen(true);
                              }}
                              className="h-8 px-2"
                            >
                              <Trash2 className="h-4 w-4 text-red-600" />
                            </Button>
                          </div>
                        </div>
                      ))}
                    </div>

                    {/* 데스크톱 테이블 뷰 */}
                    <div className="hidden lg:block rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow className="bg-gray-50/50">
                            <TableHead>번호</TableHead>
                            <TableHead>품목코드</TableHead>
                            <TableHead>품목명</TableHead>
                            <TableHead>규격</TableHead>
                            <TableHead>단위</TableHead>
                            <TableHead className="text-right">작업</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {filteredItems.filter(item => !(item as any).partType).map((item, index) => (
                            <TableRow 
                              key={`${item.id}-${index}`}
                              className="cursor-pointer hover:bg-muted/50"
                              onClick={() => handleViewChange("view", item)}
                            >
                              <TableCell className="text-muted-foreground">{index + 1}</TableCell>
                              <TableCell>
                                <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                  {formatItemCodeForAssembly(item) || '-'}
                                </code>
                              </TableCell>
                              <TableCell>{item.itemName}</TableCell>
                              <TableCell className="text-sm text-muted-foreground">
                                {item.specification || '-'}
                              </TableCell>
                              <TableCell>
                                <Badge variant="secondary" className="text-xs">{item.unit || '-'}</Badge>
                              </TableCell>
                              <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
                                <div className="flex items-center justify-end gap-2">
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => handleViewChange("edit", item)}
                                  >
                                    <Edit className="h-4 w-4" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => {
                                      setItemToDelete(item);
                                      setIsDeleteDialogOpen(true);
                                    }}
                                  >
                                    <Trash2 className="h-4 w-4 text-red-600" />
                                  </Button>
                                </div>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  </div>
                )}

                {filteredItems.length === 0 && (
                  <div className="text-center py-12 text-muted-foreground border rounded-lg">
                    검색 결과가 없습니다.
                  </div>
                )}
              </TabsContent>

              {/* 원자재(RM) 탭 */}
              <TabsContent value="RM" className="mt-0">
                {/* 모바일/태블릿 카드 뷰 */}
                <div className="lg:hidden space-y-3">
                  {filteredItems.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground border rounded-lg">
                      검색 결과가 없습니다.
                    </div>
                  ) : (
                    paginatedItems.map((item, index) => (
                      <div 
                        key={`${item.id}-rm-mobile-${index}`}
                        className="border rounded-lg p-4 space-y-3 bg-white hover:bg-muted/50 transition-colors cursor-pointer"
                        onClick={() => handleViewChange("view", item)}
                      >
                        <div className="space-y-2">
                          <div className="flex items-center gap-2 flex-wrap">
                            <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                              {item.itemCode}
                            </code>
                            <Badge variant="outline" className="bg-purple-50 text-purple-700 text-xs">
                              V{item.currentRevision || 0}
                            </Badge>
                          </div>
                          <div className="font-medium">
                            {item.itemName}
                          </div>
                          {item.category1 && (
                            <div className="text-sm text-muted-foreground">
                              분류: {item.category1}
                            </div>
                          )}
                          {item.specification && (
                            <div className="text-sm text-muted-foreground">
                              규격: {item.specification}
                            </div>
                          )}
                          {item.unit && (
                            <div>
                              <Badge variant="secondary" className="text-xs">{item.unit}</Badge>
                            </div>
                          )}
                        </div>
                        <div className="flex items-center justify-end gap-1 pt-2 border-t" onClick={(e) => e.stopPropagation()}>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewChange("edit", item)}
                            className="h-8 px-3"
                          >
                            <Edit className="h-4 w-4 mr-1" />
                            <span className="text-xs">수정</span>
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setItemToDelete(item);
                              setIsDeleteDialogOpen(true);
                            }}
                            className="h-8 px-2"
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </div>
                      </div>
                    ))
                  )}
                </div>

                {/* 데스크톱 테이블 뷰 */}
                <div className="hidden lg:block rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>번호</TableHead>
                        <TableHead>품목코드</TableHead>
                        <TableHead>품목명</TableHead>
                        <TableHead>분류</TableHead>
                        <TableHead>규격</TableHead>
                        <TableHead>단위</TableHead>
                        <TableHead>품목 상태</TableHead>
                        <TableHead>버전관리</TableHead>
                        <TableHead className="text-right">작업</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredItems.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
                            검색 결과가 없습니다.
                          </TableCell>
                        </TableRow>
                      ) : (
                        paginatedItems.map((item, index) => (
                          <TableRow 
                            key={`${item.id}-${index}`}
                            className="cursor-pointer hover:bg-muted/50"
                            onClick={() => handleViewChange("view", item)}
                          >
                            <TableCell className="text-muted-foreground">{filteredItems.length - (startIndex + index)}</TableCell>
                            <TableCell>
                              <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                {item.itemCode}
                              </code>
                            </TableCell>
                            <TableCell>{item.itemName}</TableCell>
                            <TableCell className="text-sm">
                              {item.category1 ? (
                                <span className="text-xs">{item.category1}</span>
                              ) : '-'}
                            </TableCell>
                            <TableCell className="text-sm text-muted-foreground">
                              {item.specification || '-'}
                            </TableCell>
                            <TableCell>
                              <Badge variant="secondary" className="text-xs">{item.unit || '-'}</Badge>
                            </TableCell>
                            <TableCell>
                              <div className="flex flex-col gap-1">
                                <Badge variant="outline" className="bg-purple-50 text-purple-700 text-xs w-fit">
                                  V{item.currentRevision || 0}
                                </Badge>
                                {(item.revisions?.length || 0) > 0 && (
                                  <span className="text-xs text-muted-foreground">
                                    {item.revisions?.length}회 수정
                                  </span>
                                )}
                              </div>
                            </TableCell>
                            <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
                              <div className="flex items-center justify-end gap-2">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => handleViewChange("edit", item)}
                                >
                                  <Edit className="h-4 w-4" />
                                </Button>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => {
                                    setItemToDelete(item);
                                    setIsDeleteDialogOpen(true);
                                  }}
                                >
                                  <Trash2 className="h-4 w-4 text-red-600" />
                                </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
              </TabsContent>

              {/* 부자���(SM) 탭 */}
              <TabsContent value="SM" className="mt-0">
                {/* 모바일/태블릿 카드 뷰 */}
                <div className="lg:hidden space-y-3">
                  {filteredItems.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground border rounded-lg">
                      검색 결과가 없습니다.
                    </div>
                  ) : (
                    paginatedItems.map((item, index) => (
                      <div 
                        key={`${item.id}-sm-mobile-${index}`}
                        className="border rounded-lg p-4 space-y-3 bg-white hover:bg-muted/50 transition-colors cursor-pointer"
                        onClick={() => handleViewChange("view", item)}
                      >
                        <div className="space-y-2">
                          <div className="flex items-center gap-2 flex-wrap">
                            <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                              {item.itemCode}
                            </code>
                            <Badge variant="outline" className="bg-purple-50 text-purple-700 text-xs">
                              V{item.currentRevision || 0}
                            </Badge>
                          </div>
                          <div className="font-medium">
                            {item.itemName}
                          </div>
                          {item.specification && (
                            <div className="text-sm text-muted-foreground">
                              규격: {item.specification}
                            </div>
                          )}
                          {item.unit && (
                            <div>
                              <Badge variant="secondary" className="text-xs">{item.unit}</Badge>
                            </div>
                          )}
                        </div>
                        <div className="flex items-center justify-end gap-1 pt-2 border-t" onClick={(e) => e.stopPropagation()}>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewChange("edit", item)}
                            className="h-8 px-3"
                          >
                            <Edit className="h-4 w-4 mr-1" />
                            <span className="text-xs">수정</span>
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setItemToDelete(item);
                              setIsDeleteDialogOpen(true);
                            }}
                            className="h-8 px-2"
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </div>
                      </div>
                    ))
                  )}
                </div>

                {/* 데스크톱 테이블 뷰 */}
                <div className="hidden lg:block rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>번호</TableHead>
                        <TableHead>품목코드</TableHead>
                        <TableHead>품목명</TableHead>
                        <TableHead>규격</TableHead>
                        <TableHead>단위</TableHead>
                        <TableHead>품목 상태</TableHead>
                        <TableHead>버전관리</TableHead>
                        <TableHead className="text-right">작업</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredItems.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                            검색 결과가 없습니다.
                          </TableCell>
                        </TableRow>
                      ) : (
                        paginatedItems.map((item, index) => (
                          <TableRow 
                            key={`${item.id}-${index}`}
                            className="cursor-pointer hover:bg-muted/50"
                            onClick={() => handleViewChange("view", item)}
                          >
                            <TableCell className="text-muted-foreground">{filteredItems.length - (startIndex + index)}</TableCell>
                            <TableCell>
                              <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                {item.itemCode}
                              </code>
                            </TableCell>
                            <TableCell>{item.itemName}</TableCell>
                            <TableCell className="text-sm text-muted-foreground">
                              {item.specification || '-'}
                            </TableCell>
                            <TableCell>
                              <Badge variant="secondary" className="text-xs">{item.unit || '-'}</Badge>
                            </TableCell>
                            <TableCell>
                              {item.status === 'active' && (
                                <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                              )}
                              {item.status === 'inactive' && (
                                <Badge variant="outline" className="bg-gray-50 text-gray-700 text-xs">미사용</Badge>
                              )}
                              {item.status === 'development' && (
                                <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">개발중</Badge>
                              )}
                              {item.status === 'discontinued' && (
                                <Badge variant="outline" className="bg-red-50 text-red-700 text-xs">폐기</Badge>
                              )}
                              {!item.status && (
                                <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                              )}
                            </TableCell>
                            <TableCell>
                              <div className="flex flex-col gap-1">
                                <Badge variant="outline" className="bg-purple-50 text-purple-700 text-xs w-fit">
                                  V{item.currentRevision || 0}
                                </Badge>
                                {(item.revisions?.length || 0) > 0 && (
                                  <span className="text-xs text-muted-foreground">
                                    {item.revisions?.length}회 수정
                                  </span>
                                )}
                              </div>
                            </TableCell>
                            <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
                              <div className="flex items-center justify-end gap-2">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => handleViewChange("edit", item)}
                                >
                                  <Edit className="h-4 w-4" />
                                </Button>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => {
                                    setItemToDelete(item);
                                    setIsDeleteDialogOpen(true);
                                  }}
                                >
                                  <Trash2 className="h-4 w-4 text-red-600" />
                                </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
                
                {/* 페이지네이션 */}
                {totalPages > 1 && (
                  <div className="flex items-center justify-between mt-4">
                    <div className="text-sm text-muted-foreground">
                      전체 {filteredItems.length}개 중 {startIndex + 1}-{Math.min(endIndex, filteredItems.length)}개 표시
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(1)}
                        disabled={currentPage === 1}
                      >
                        처음
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                        disabled={currentPage === 1}
                      >
                        <ChevronLeft className="h-4 w-4" />
                      </Button>
                      <span className="text-sm">
                        {currentPage} / {totalPages}
                      </span>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                        disabled={currentPage === totalPages}
                      >
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(totalPages)}
                        disabled={currentPage === totalPages}
                      >
                        마지막
                      </Button>
                    </div>
                  </div>
                )}
              </TabsContent>

              {/* 소모품(CS) 탭 */}
              <TabsContent value="CS" className="mt-0">
                {/* 모바일/태블릿 카드 뷰 */}
                <div className="lg:hidden space-y-3">
                  {filteredItems.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground border rounded-lg">
                      검색 결과가 없습니다.
                    </div>
                  ) : (
                    paginatedItems.map((item, index) => (
                      <div 
                        key={`${item.id}-cs-mobile-${index}`}
                        className="border rounded-lg p-4 space-y-3 bg-white hover:bg-muted/50 transition-colors cursor-pointer"
                        onClick={() => handleViewChange("view", item)}
                      >
                        <div className="space-y-2">
                          <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                            {item.itemCode}
                          </code>
                          <div className="font-medium">
                            {item.itemName}
                          </div>
                          {item.specification && (
                            <div className="text-sm text-muted-foreground">
                              규격: {item.specification}
                            </div>
                          )}
                          {item.unit && (
                            <div>
                              <Badge variant="secondary" className="text-xs">{item.unit}</Badge>
                            </div>
                          )}
                        </div>
                        <div className="flex items-center justify-end gap-1 pt-2 border-t" onClick={(e) => e.stopPropagation()}>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewChange("edit", item)}
                            className="h-8 px-3"
                          >
                            <Edit className="h-4 w-4 mr-1" />
                            <span className="text-xs">수정</span>
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setItemToDelete(item);
                              setIsDeleteDialogOpen(true);
                            }}
                            className="h-8 px-2"
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </div>
                      </div>
                    ))
                  )}
                </div>

                {/* 데스크톱 테이블 뷰 */}
                <div className="hidden lg:block rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>번호</TableHead>
                        <TableHead>품목코드</TableHead>
                        <TableHead>품목명</TableHead>
                        <TableHead>규격</TableHead>
                        <TableHead>단위</TableHead>
                        <TableHead>품목 상태</TableHead>
                        <TableHead className="text-right">작업</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredItems.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                            검색 결과가 없습니다.
                          </TableCell>
                        </TableRow>
                      ) : (
                        paginatedItems.map((item, index) => (
                          <TableRow 
                            key={`${item.id}-${index}`}
                            className="cursor-pointer hover:bg-muted/50"
                            onClick={() => handleViewChange("view", item)}
                          >
                            <TableCell className="text-muted-foreground">{filteredItems.length - (startIndex + index)}</TableCell>
                            <TableCell>
                              <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                {item.itemCode}
                              </code>
                            </TableCell>
                            <TableCell>{item.itemName}</TableCell>
                            <TableCell className="text-sm text-muted-foreground">
                              {item.specification || '-'}
                            </TableCell>
                            <TableCell>
                              <Badge variant="secondary" className="text-xs">{item.unit || '-'}</Badge>
                            </TableCell>
                            <TableCell>
                              {item.status === 'active' && (
                                <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                              )}
                              {item.status === 'inactive' && (
                                <Badge variant="outline" className="bg-gray-50 text-gray-700 text-xs">미사용</Badge>
                              )}
                              {item.status === 'development' && (
                                <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">개발중</Badge>
                              )}
                              {item.status === 'discontinued' && (
                                <Badge variant="outline" className="bg-red-50 text-red-700 text-xs">폐기</Badge>
                              )}
                              {!item.status && (
                                <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
                              )}
                            </TableCell>
                            <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
                              <div className="flex items-center justify-end gap-2">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => handleViewChange("edit", item)}
                                >
                                  <Edit className="h-4 w-4" />
                                </Button>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => {
                                    setItemToDelete(item);
                                    setIsDeleteDialogOpen(true);
                                  }}
                                >
                                  <Trash2 className="h-4 w-4 text-red-600" />
                                </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
                
                {/* 페이지네이션 */}
                {totalPages > 1 && (
                  <div className="flex items-center justify-between mt-4">
                    <div className="text-sm text-muted-foreground">
                      전체 {filteredItems.length}개 중 {startIndex + 1}-{Math.min(endIndex, filteredItems.length)}개 표시
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(1)}
                        disabled={currentPage === 1}
                      >
                        처음
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                        disabled={currentPage === 1}
                      >
                        <ChevronLeft className="h-4 w-4" />
                      </Button>
                      <span className="text-sm">
                        {currentPage} / {totalPages}
                      </span>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                        disabled={currentPage === totalPages}
                      >
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(totalPages)}
                        disabled={currentPage === totalPages}
                      >
                        마지막
                      </Button>
                    </div>
                  </div>
                )}
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>



        {/* 삭제 확인 다이얼로그 */}
        <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>품목 삭제</AlertDialogTitle>
              <AlertDialogDescription>
                정말로 '{itemToDelete?.itemName}' 품목을 삭제하시겠습니까?
                <br />이 작업은 되돌릴 수 없습니다.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>취소</AlertDialogCancel>
              <AlertDialogAction onClick={confirmDelete} className="bg-red-600 hover:bg-red-700">
                삭제
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </PageLayout>
    );
  }

  // 상세 조회 뷰
  if (view === "view" && selectedItem) {
    // 선택된 버전의 데이터 가져오기
    const displayData = getDisplayDataByRevision(selectedItem, selectedRevision, selectedItem.revisions);
    
    // 품목 수정 이력 표시 설정
    const itemRevisionConfig: RevisionDisplayConfig = {
      title: "품목 수정 이력",
      itemName: "품목코드",
      formatFields: (data: any) => (
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div><strong className="text-muted-foreground">품목코드:</strong> {formatItemCodeForAssembly(data)}</div>
          <div><strong className="text-muted-foreground">품목명:</strong> {data.itemName}</div>
          <div><strong className="text-muted-foreground">규격:</strong> {data.specification || '-'}</div>
          <div><strong className="text-muted-foreground">단위:</strong> {data.unit}</div>
        </div>
      ),
    };
    
    return (
      <PageLayout>
        <PageHeader
          title="품목 상세 정보"
          description="등록된 품목 정보를 확인합니다"
          icon={Package}
          actions={
            <DetailViewActions
              onBackClick={() => setView("list")}
              onEditClick={() => handleViewChange("edit", selectedItem)}
            />
          }
        />
        
        {/* 수정 이력 선택 드롭다운 */}
        <RevisionSelector
          currentRevision={selectedItem.currentRevision || 0}
          revisions={selectedItem.revisions || []}
          selectedRevision={selectedRevision}
          onRevisionChange={setSelectedRevision}
          itemType="품목"
        />
        
        {/* 버전 히스토리 */}
        {screenVersion.versionHistory.length > 0 && (
          <Card className="border-purple-200 bg-purple-50">
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-purple-700">
                <History className="h-5 w-5" />
                품목 관리 수정 이력
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="bg-white border border-purple-200 rounded-lg p-4">
                <div className="text-sm space-y-2">
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-semibold text-purple-700">최근 수정 이력</span>
                    <Badge variant="secondary">총 {screenVersion.versionHistory.length}건</Badge>
                  </div>
                  <div className="max-h-32 overflow-y-auto space-y-2">
                    {screenVersion.versionHistory.slice().reverse().slice(0, 3).map((history) => (
                      <div key={history.id} className="flex items-center gap-2 text-xs">
                        <Badge variant="outline">v{history.version}</Badge>
                        <span className="text-muted-foreground">•</span>
                        <span>{history.changeDescription}</span>
                        <span className="text-muted-foreground">•</span>
                        <span className="text-muted-foreground">{history.changedBy}</span>
                        <span className="text-muted-foreground ml-auto">{new Date(history.changedAt).toLocaleDateString('ko-KR')}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle>기본 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              <div>
                <Label className="text-muted-foreground">품목코드</Label>
                <p className="mt-1">
                  <code className="text-sm bg-gray-100 px-2 py-1 rounded">
                    {formatItemCodeForAssembly(selectedItem)}
                  </code>
                </p>
              </div>
              <div>
                <Label className="text-muted-foreground">품목명</Label>
                <p className="mt-1 font-medium">{selectedItem.itemName}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">품목유형</Label>
                <p className="mt-1">{getItemTypeBadge(selectedItem.itemType)}</p>
              </div>


              {selectedItem.itemType === "PT" && (selectedItem as any).partType && (
                <div>
                  <Label className="text-muted-foreground">부품 유형</Label>
                  <p className="mt-1">
                    <Badge variant="outline" className={
                      (selectedItem as any).partType === 'ASSEMBLY' ? 'bg-blue-50 text-blue-700' :
                      (selectedItem as any).partType === 'BENDING' ? 'bg-purple-50 text-purple-700' :
                      (selectedItem as any).partType === 'PURCHASED' ? 'bg-green-50 text-green-700' :
                      'bg-gray-50 text-gray-700'
                    }>
                      {(selectedItem as any).partType === 'ASSEMBLY' ? '조립 부품' :
                       (selectedItem as any).partType === 'BENDING' ? '절곡 부품' :
                       (selectedItem as any).partType === 'PURCHASED' ? '구매 부품' :
                       (selectedItem as any).partType}
                    </Badge>
                  </p>
                </div>
              )}
              {selectedItem.itemType === "PT" && (selectedItem as any).partType === "BENDING" && (selectedItem as any).partUsage && (
                <div>
                  <Label className="text-muted-foreground">용도</Label>
                  <p className="mt-1">
                    <Badge variant="outline" className="bg-indigo-50 text-indigo-700">
                      {(selectedItem as any).partUsage === "GUIDE_RAIL" ? "가이드레일용" :
                       (selectedItem as any).partUsage === "BOTTOM_FINISH" ? "하단마감재용" :
                       (selectedItem as any).partUsage === "CASE" ? "케이스용" :
                       (selectedItem as any).partUsage === "DOOR" ? "도어용" :
                       (selectedItem as any).partUsage === "BRACKET" ? "브라켓용" :
                       (selectedItem as any).partUsage === "GENERAL" ? "범용 (공통 부품)" :
                       (selectedItem as any).partUsage}
                    </Badge>
                  </p>
                </div>
              )}

              {selectedItem.itemType !== "FG" && !((selectedItem as any).partType === 'ASSEMBLY') && (
                <div>
                  <Label className="text-muted-foreground">규격</Label>
                  <p className="mt-1">{selectedItem.specification || "-"}</p>
                </div>
              )}
              {selectedItem.itemType !== "FG" && (
                <div>
                  <Label className="text-muted-foreground">단위</Label>
                  <p className="mt-1">
                    <Badge variant="secondary">{selectedItem.unit}</Badge>
                  </p>
                </div>
              )}
              
              {/* 마감 정보 - 조립 부품인 경우 */}
              {selectedItem.itemType === "PT" && (selectedItem as any).partType === 'ASSEMBLY' && (selectedItem as any).finishType && (
                <div>
                  <Label className="text-muted-foreground">마감</Label>
                  <p className="mt-1">
                    <Badge variant="outline" className="bg-blue-50 text-blue-700">
                      {(selectedItem as any).finishType}
                    </Badge>
                  </p>
                </div>
              )}
              
              {/* 재질 정보 - 절곡 부품인 경우 */}
              {selectedItem.itemType === "PT" && (selectedItem as any).partType === 'BENDING' && (selectedItem as any).material && (
                <div>
                  <Label className="text-muted-foreground">재질</Label>
                  <p className="mt-1">
                    <Badge variant="outline" className="bg-green-50 text-green-700">
                      {(selectedItem as any).material}
                    </Badge>
                  </p>
                </div>
              )}
              
              {selectedItem.description && (
                <div className="md:col-span-2 lg:col-span-3">
                  <Label className="text-muted-foreground">비고</Label>
                  <p className="mt-1 text-sm">{selectedItem.description}</p>
                </div>
              )}
              
              {/* 인정 정보 */}
              {((selectedItem as any).certificationNumber || (selectedItem as any).certificationStartDate || (selectedItem as any).certificationEndDate || (selectedItem as any).specificationFileName || (selectedItem as any).certificationFileName) && (
                <div className="md:col-span-2 lg:col-span-3 pt-4 border-t">
                  <h4 className="font-medium mb-3">인정 정보</h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {(selectedItem as any).certificationNumber && (
                      <div>
                        <Label className="text-muted-foreground">인정번호</Label>
                        <p className="mt-1">{(selectedItem as any).certificationNumber}</p>
                      </div>
                    )}
                    {((selectedItem as any).certificationStartDate || (selectedItem as any).certificationEndDate) && (
                      <div>
                        <Label className="text-muted-foreground">인정 유효기간</Label>
                        <p className="mt-1">
                          {(selectedItem as any).certificationStartDate || '-'} ~ {(selectedItem as any).certificationEndDate || '-'}
                        </p>
                      </div>
                    )}
                    {(selectedItem as any).specificationFileName && (
                      <div>
                        <Label className="text-muted-foreground">시방서</Label>
                        <p className="mt-1 flex items-center gap-2">
                          <Badge variant="outline" className="bg-blue-50 text-blue-700">
                            {(selectedItem as any).specificationFileName}
                          </Badge>
                        </p>
                      </div>
                    )}
                    {(selectedItem as any).certificationFileName && (
                      <div>
                        <Label className="text-muted-foreground">인정서</Label>
                        <p className="mt-1 flex items-center gap-2">
                          <Badge variant="outline" className="bg-green-50 text-green-700">
                            {(selectedItem as any).certificationFileName}
                          </Badge>
                        </p>
                      </div>
                    )}
                  </div>
                </div>
              )}
              
              {/* 버전 정보 */}
              <div className="md:col-span-2 lg:col-span-3 pt-4 border-t">
                <div className="flex items-center justify-between mb-3">
                </div>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <Label className="text-muted-foreground">현재 버전</Label>
                    <Badge variant="secondary" className="mt-1">V{selectedItem.currentRevision || 0}</Badge>
                  </div>
                  <div>
                    <Label className="text-muted-foreground">수정 횟수</Label>
                    <p className="mt-1">{(selectedItem.revisions?.length || 0)}회</p>
                  </div>
                </div>
              </div>
              
              <div>
                <Label className="text-muted-foreground">등록일</Label>
                <p className="mt-1 text-sm">{selectedItem.createdAt}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 조립 부품 세부 정보 */}
        {selectedItem.itemType === 'PT' && (selectedItem as any).partType === 'ASSEMBLY' && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Package className="h-5 w-5" />
                조립 부품 세부 정보
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                {(selectedItem as any).category1 && (
                  <div>
                    <Label className="text-muted-foreground">품목명</Label>
                    <p className="mt-1">
                      <Badge variant="outline" className="bg-indigo-50 text-indigo-700">
                        {(selectedItem as any).category1 === 'guide_rail' ? '가이드레일' :
                         (selectedItem as any).category1 === 'case' ? '케이스' :
                         (selectedItem as any).category1 === 'bottom_finish' ? '하단마감재' :
                         (selectedItem as any).category1}
                      </Badge>
                    </p>
                  </div>
                )}
                {(selectedItem as any).installationType && (
                  <div>
                    <Label className="text-muted-foreground">설치 유형</Label>
                    <p className="mt-1">
                      <Badge variant="outline" className="bg-green-50 text-green-700">
                        {(selectedItem as any).installationType === 'wall' ? '벽면형 (R)' :
                         (selectedItem as any).installationType === 'side' ? '측면형 (S)' :
                         (selectedItem as any).installationType === 'steel' ? '스틸 (B)' :
                         (selectedItem as any).installationType === 'iron' ? '철재 (T)' :
                         (selectedItem as any).installationType}
                      </Badge>
                    </p>
                  </div>
                )}
                <div>
                  <Label className="text-muted-foreground">마감</Label>
                  <p className="mt-1">
                    {(selectedItem as any).assemblyType ? (
                      <code className="text-sm bg-gray-100 px-2 py-1 rounded">
                        {(selectedItem as any).assemblyType}
                      </code>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </p>
                </div>
                {(selectedItem as any).material && (
                  <div>
                    <Label className="text-muted-foreground">재질</Label>
                    <p className="mt-1">
                      <Badge variant="outline" className="bg-indigo-50 text-indigo-700">
                        {(selectedItem as any).material}
                      </Badge>
                    </p>
                  </div>
                )}
                {(selectedItem as any).assemblyLength && (
                  <div>
                    <Label className="text-muted-foreground">길이</Label>
                    <p className="mt-1 font-medium">{(selectedItem as any).assemblyLength}mm</p>
                  </div>
                )}
                {(selectedItem as any).sideSpecWidth && (selectedItem as any).sideSpecHeight && (
                  <div>
                    <Label className="text-muted-foreground">측면 규격</Label>
                    <p className="mt-1">
                      {(selectedItem as any).sideSpecWidth} × {(selectedItem as any).sideSpecHeight}mm
                    </p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        )}
        
        {/* 가이드레일 세부 정보 */}
        {selectedItem.category3 === "가이드레일" && (selectedItem as any).guideRailModelType && (
          <Card>
            <CardHeader>
              <CardTitle>가이드레일 세부 정보</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                {(selectedItem as any).guideRailModelType && (
                  <div>
                    <Label className="text-muted-foreground">모델유형</Label>
                    <p className="mt-1">
                      <Badge variant="outline" className="bg-orange-50 text-orange-700">
                        {(selectedItem as any).guideRailModelType}
                      </Badge>
                    </p>
                  </div>
                )}
                {(selectedItem as any).guideRailModel && (
                  <div>
                    <Label className="text-muted-foreground">모델선택</Label>
                    <p className="mt-1">
                      <Badge variant="outline" className="bg-orange-50 text-orange-700">
                        {(selectedItem as any).guideRailModel}
                      </Badge>
                    </p>
                  </div>
                )}

              </div>
            </CardContent>
          </Card>
        )}



        {/* 절곡품 전개도 정보 - 절곡 부품만 표시 */}
        {selectedItem.itemType === 'PT' && ((selectedItem as any).partType === 'BENDING' || (selectedItem as any).partType === 'ASSEMBLY') && ((selectedItem as any).bendingDiagram || ((selectedItem as any).bendingDetails && (selectedItem as any).bendingDetails.length > 0)) && (
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-base md:text-lg">
                <FileImage className="h-4 w-4 md:h-5 md:w-5" />
                {(selectedItem as any).partType === 'ASSEMBLY' ? '조립품 전개도 (바라시)' : '절곡품 전개도 (바라시)'}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4 md:space-y-6 pt-0">
              {/* 전개도 이미지 */}
              {(selectedItem as any).bendingDiagram ? (
                <div>
                  <Label className="text-muted-foreground text-xs md:text-sm">전개도 이미지</Label>
                  <div className="mt-2 p-2 md:p-4 border rounded-lg bg-gray-50">
                    <img 
                      src={(selectedItem as any).bendingDiagram} 
                      alt="전개도" 
                      className="max-w-full h-auto max-h-64 md:max-h-96 mx-auto border rounded"
                    />
                  </div>
                </div>
              ) : (
                <div className="text-center py-6 md:py-8 text-xs md:text-sm text-muted-foreground border rounded-lg bg-gray-50">
                  등록된 전개도 이미지가 없습니다.
                </div>
              )}

              {/* 전개도 상세 데이터 */}
              {(selectedItem as any).bendingDetails && (selectedItem as any).bendingDetails.length > 0 && (
                <div>
                  <Label className="text-muted-foreground text-xs md:text-sm">전개도 상세 데이터</Label>
                  <div className="mt-2 overflow-x-auto bg-white rounded border -mx-2 md:mx-0">
                    <table className="w-full text-xs md:text-sm min-w-[500px]">
                      <thead className="bg-gray-100">
                        <tr>
                          <th className="border px-1 md:px-2 py-1 md:py-2">번호</th>
                          <th className="border px-1 md:px-2 py-1 md:py-2">입력</th>
                          <th className="border px-1 md:px-2 py-1 md:py-2">연신율</th>
                          <th className="border px-1 md:px-2 py-1 md:py-2">연신율계산후</th>
                          <th className="border px-1 md:px-2 py-1 md:py-2">합계</th>
                          <th className="border px-1 md:px-2 py-1 md:py-2">음영</th>
                          <th className="border px-1 md:px-2 py-1 md:py-2">A각</th>
                        </tr>
                      </thead>
                      <tbody>
                        {(selectedItem as any).bendingDetails.map((detail: any, detailIndex: number) => {
                          const calculated = detail.input + detail.elongation;
                          let sum = 0;
                          for (let i = 0; i <= detailIndex; i++) {
                            const d = (selectedItem as any).bendingDetails![i];
                            sum += d.input + d.elongation;
                          }
                          
                          return (
                            <tr key={detail.id} className={detail.shaded ? "bg-gray-200" : ""}>
                              <td className="border px-1 md:px-2 py-1 text-center">{detail.no}</td>
                              <td className="border px-1 md:px-2 py-1 text-center">{detail.input}</td>
                              <td className="border px-1 md:px-2 py-1 text-center">{detail.elongation}</td>
                              <td className="border px-1 md:px-2 py-1 text-center bg-blue-50">{calculated}</td>
                              <td className="border px-1 md:px-2 py-1 text-center bg-green-50 font-medium">{sum}</td>
                              <td className="border px-1 md:px-2 py-1 text-center">
                                {detail.shaded ? <Check className="h-3 w-3 md:h-4 md:w-4 inline" /> : "-"}
                              </td>
                              <td className="border px-1 md:px-2 py-1 text-center">{detail.aAngle || "-"}</td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                  <div className="mt-2 p-2 md:p-3 bg-blue-50 rounded-lg border border-blue-200">
                    <p className="text-xs md:text-sm">
                      <span className="font-medium">최종 전개 길이:</span>{" "}
                      <span className="text-base md:text-lg font-bold text-blue-700">
                        {(selectedItem as any).bendingDetails.reduce((sum: number, d: any) => sum + d.input + d.elongation, 0)} mm
                      </span>
                    </p>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        )}

        {/* BOM 정보 - 절곡 부품은 제외 */}
        {(selectedItem.itemType === 'FG' || (selectedItem.itemType === 'PT' && (selectedItem as any).partType !== 'BENDING')) && (selectedItem as any).needsBOM !== false && (
          <Card className="w-full">
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center gap-2">
                  <Package className="h-5 w-5" />
                  부품 구성 (BOM)
                </CardTitle>
                {selectedItem.bom && selectedItem.bom.length > 0 && (
                  <Badge variant="outline" className="bg-blue-50 text-blue-700">
                    총 {selectedItem.bom.length}개 품목
                  </Badge>
                )}
              </div>
            </CardHeader>
            <CardContent className="p-0 sm:p-6">
              {selectedItem.bom && selectedItem.bom.length > 0 ? (
                <div className="space-y-4 w-full">
                  <div className="overflow-x-auto w-full">
                    <Table className="w-full table-fixed">
                      <TableHeader>
                        <TableRow>
                          <TableHead className="whitespace-nowrap w-16">번호</TableHead>
                          <TableHead className="whitespace-nowrap w-32">품목코드</TableHead>
                          <TableHead className="whitespace-nowrap">품목명</TableHead>
                          <TableHead className="whitespace-nowrap w-32">재질/마감</TableHead>
                          <TableHead className="whitespace-nowrap text-right w-20">수량</TableHead>
                          <TableHead className="whitespace-nowrap w-20">단위</TableHead>
                          <TableHead className="whitespace-nowrap w-24">작업</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                      {selectedItem.bom.map((line, index) => {
                        // 해당 부품의 하위 BOM 찾기
                        const childItem = itemMasters.find(item => item.itemCode === line.childItemCode);
                        const isBendingPart = childItem && (childItem as any).partType === 'BENDING';
                        const isAssemblyPart = childItem && (childItem as any).partType === 'ASSEMBLY';
                        const hasChildBOM = childItem && childItem.bom && childItem.bom.length > 0;
                        
                        // 조립 부품인 경우 한글 품목코드 포맷 사용
                        const displayItemCode = childItem && isAssemblyPart 
                          ? formatItemCodeForAssembly(childItem)
                          : line.childItemCode;
                        
                        return (
                          <Fragment key={line.id}>
                            <TableRow>
                              <TableCell>{index + 1}</TableCell>
                              <TableCell>
                                <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                  {displayItemCode}
                                </code>
                              </TableCell>
                              <TableCell>
                                <div className="flex items-center gap-2">
                                  {line.childItemName}
                                  {isBendingPart && (
                                    <Badge variant="outline" className="text-xs bg-purple-50 text-purple-700">
                                      절곡품
                                    </Badge>
                                  )}
                                  {hasChildBOM && (
                                    <Badge variant="outline" className="text-xs bg-blue-50 text-blue-700">
                                      BOM {childItem.bom.length}개
                                    </Badge>
                                  )}
                                </div>
                              </TableCell>
                              <TableCell>
                                {isBendingPart ? (
                                  // 절곡 부품인 경우 재질 표시
                                  childItem && (childItem as any).material ? (
                                    <Badge variant="outline" className="bg-green-50 text-green-700">
                                      {(childItem as any).material}
                                    </Badge>
                                  ) : (
                                    <span className="text-muted-foreground">-</span>
                                  )
                                ) : isAssemblyPart ? (
                                  // 조립 부품인 경우 마감 표시
                                  childItem && (childItem as any).finishType ? (
                                    <Badge variant="outline" className="bg-blue-50 text-blue-700">
                                      {(childItem as any).finishType}
                                    </Badge>
                                  ) : (
                                    <span className="text-muted-foreground">-</span>
                                  )
                                ) : (
                                  // 기타 부품은 재질 표시
                                  childItem && (childItem as any).material ? (
                                    <Badge variant="outline" className="bg-green-50 text-green-700">
                                      {(childItem as any).material}
                                    </Badge>
                                  ) : (
                                    <span className="text-muted-foreground">-</span>
                                  )
                                )}
                              </TableCell>
                              <TableCell className="text-right">{line.quantity}</TableCell>
                              <TableCell>{line.unit}</TableCell>
                              <TableCell>
                                {(isBendingPart || (childItem && (childItem as any).partType === 'ASSEMBLY')) && (
                                  <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => {
                                      setEditBendingDialog({
                                        isOpen: true,
                                        bomLine: line,
                                        parentItemCode: selectedItem.itemCode || "",
                                      });
                                      setTempBendingData({
                                        bendingDiagram: line.bendingDiagram,
                                        bendingDetails: line.bendingDetails || []
                                      });
                                    }}
                                  >
                                    <Pencil className="h-3 w-3 mr-1" />
                                    전개도
                                  </Button>
                                )}
                              </TableCell>
                            </TableRow>
{(() => {
                              // BOM Line 또는 품목마스터에서 전개도 정보 가져오기
                              const displayDiagram = line.bendingDiagram || (childItem && (childItem as any).bendingDiagram);
                              const displayDetails = (line.bendingDetails && line.bendingDetails.length > 0) 
                                ? line.bendingDetails 
                                : (childItem && (childItem as any).bendingDetails && (childItem as any).bendingDetails.length > 0)
                                  ? (childItem as any).bendingDetails
                                  : null;
                              
                              if (!displayDiagram && !displayDetails) return null;
                              
                              return (
                                <TableRow>
                                  <TableCell colSpan={7} className="bg-purple-50/30">
                                    <div className="p-4 space-y-3">
                                      <div className="flex items-center gap-2 mb-2">
                                        <Badge variant="outline" className="bg-purple-100 text-purple-700">
                                          {isBendingPart ? '절곡 전개도 정보' : '부품 전개도 정보'}
                                        </Badge>
                                      </div>
                                      {displayDiagram && (
                                        <div className="flex flex-col items-center">
                                          <Label className="text-sm text-muted-foreground mb-2 block">전개도 이미지</Label>
                                          <img 
                                            src={displayDiagram} 
                                            alt="전개도" 
                                            className="max-w-md border rounded"
                                          />
                                        </div>
                                      )}
                                      {displayDetails && (
                                        <div>
                                          <Label className="text-sm text-muted-foreground mb-2 block">연신률 상세</Label>
                                          <Table className="border">
                                            <TableHeader>
                                              <TableRow className="bg-purple-100/50">
                                                <TableHead className="text-xs">No</TableHead>
                                                <TableHead className="text-xs">입력</TableHead>
                                                <TableHead className="text-xs">연신율</TableHead>
                                                <TableHead className="text-xs">계산 후</TableHead>
                                                <TableHead className="text-xs">합계</TableHead>
                                                <TableHead className="text-xs">A각</TableHead>
                                              </TableRow>
                                            </TableHeader>
                                            <TableBody>
                                              {displayDetails.map((detail: any, detailIdx: number) => (
                                                <TableRow key={`bending-detail-${detailIdx}`} className={detail.shaded ? 'bg-gray-100' : 'bg-white'}>
                                                  <TableCell className="text-xs">{detail.no}</TableCell>
                                                  <TableCell className="text-xs text-right">{detail.input}</TableCell>
                                                  <TableCell className="text-xs text-right">{detail.elongation}</TableCell>
                                                  <TableCell className="text-xs text-right">{detail.calculated || (detail.input + detail.elongation)}</TableCell>
                                                  <TableCell className="text-xs text-right font-medium">{detail.sum}</TableCell>
                                                  <TableCell className="text-xs text-right">{detail.aAngle || '-'}</TableCell>
                                                </TableRow>
                                              ))}
                                            </TableBody>
                                          </Table>
                                        </div>
                                      )}
                                    </div>
                                  </TableCell>
                                </TableRow>
                              );
                            })()}
                            
                            {/* 하위 BOM 표시 - 항상 표시 */}
                            {hasChildBOM && (
                              <TableRow>
                                <TableCell colSpan={7} className="bg-blue-50/30 p-0">
                                  <div className="p-2 sm:p-4 space-y-3 w-full">
                                    <div className="flex items-center gap-2 mb-2">
                                      <Badge variant="outline" className="bg-blue-100 text-blue-700">
                                        하위 BOM 구성
                                      </Badge>
                                    </div>
                                    <div className="overflow-x-auto w-full">
                                      <Table className="border w-full">
                                        <TableHeader>
                                          <TableRow className="bg-blue-100/50">
                                            <TableHead className="text-xs whitespace-nowrap">No</TableHead>
                                            <TableHead className="text-xs whitespace-nowrap">품목코드</TableHead>
                                            <TableHead className="text-xs whitespace-nowrap min-w-[150px]">품목명</TableHead>
                                            <TableHead className="text-xs whitespace-nowrap">마감</TableHead>
                                            <TableHead className="text-xs whitespace-nowrap text-right">수량</TableHead>
                                            <TableHead className="text-xs whitespace-nowrap">단위</TableHead>
                                            <TableHead className="text-xs whitespace-nowrap">순서</TableHead>
                                          </TableRow>
                                        </TableHeader>
                                        <TableBody>
                                        {childItem!.bom!.map((subLine, subIndex) => {
                                          const subChildItem = itemMasters.find(item => item.itemCode === subLine.childItemCode);
                                          const isSubBendingPart = subChildItem && (subChildItem as any).partType === 'BENDING';
                                          const isSubAssemblyPart = subChildItem && (subChildItem as any).partType === 'ASSEMBLY';
                                          
                                          return (
                                            <Fragment key={subLine.id}>
                                              <TableRow className="bg-white">
                                                <TableCell className="text-xs">{subIndex + 1}</TableCell>
                                                <TableCell className="text-xs">
                                                  <code className="text-xs bg-gray-100 px-1.5 py-0.5 rounded">
                                                    {subLine.childItemCode}
                                                  </code>
                                                </TableCell>
                                                <TableCell className="text-xs">
                                                  <div className="flex items-center gap-1.5">
                                                    {subLine.childItemName}
                                                    {isSubBendingPart && (
                                                      <Badge variant="outline" className="text-xs bg-purple-50 text-purple-700">
                                                        절곡품
                                                      </Badge>
                                                    )}
                                                  </div>
                                                </TableCell>
                                                <TableCell className="text-xs">
                                                  {isSubAssemblyPart ? (
                                                    <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">
                                                      {(subChildItem as any).assemblyType || '-'}
                                                    </Badge>
                                                  ) : (
                                                    <span className="text-muted-foreground">-</span>
                                                  )}
                                                </TableCell>
                                                <TableCell className="text-xs text-right">{subLine.quantity}</TableCell>
                                                <TableCell className="text-xs">{subLine.unit}</TableCell>
                                                <TableCell className="text-xs">
                                                  {isSubBendingPart && (
                                                    <div className="flex gap-1">
                                                      <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        className="h-6 w-6 p-0"
                                                        onClick={() => handleReorderSubBOM(line.childItemCode, subIndex, 'up')}
                                                        disabled={subIndex === 0}
                                                      >
                                                        <ArrowUp className="h-3 w-3" />
                                                      </Button>
                                                      <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        className="h-6 w-6 p-0"
                                                        onClick={() => handleReorderSubBOM(line.childItemCode, subIndex, 'down')}
                                                        disabled={subIndex === childItem!.bom!.length - 1}
                                                      >
                                                        <ArrowDown className="h-3 w-3" />
                                                      </Button>
                                                    </div>
                                                  )}
                                                </TableCell>
                                              </TableRow>
                                              
                                              {/* 하위 BOM의 전개도 - 절곡품과 조립품 모두 표시 */}
                                              {(() => {
                                                // 하위 BOM의 전개도 정보 가져오기
                                                const subDisplayDiagram = subLine.bendingDiagram || (subChildItem && (subChildItem as any).bendingDiagram);
                                                const subDisplayDetails = (subLine.bendingDetails && subLine.bendingDetails.length > 0) 
                                                  ? subLine.bendingDetails 
                                                  : (subChildItem && (subChildItem as any).bendingDetails && (subChildItem as any).bendingDetails.length > 0)
                                                    ? (subChildItem as any).bendingDetails
                                                    : null;
                                                
                                                if (!subDisplayDiagram && !subDisplayDetails) return null;
                                                
                                                return (
                                                  <TableRow>
                                                    <TableCell colSpan={6} className="bg-purple-50/30 p-3">
                                                      <div className="space-y-2">
                                                        <Badge variant="outline" className="bg-purple-100 text-purple-700 text-xs">
                                                          {isSubBendingPart ? '절곡 전개도' : '부품 전개도'}
                                                        </Badge>
                                                        {subDisplayDiagram && (
                                                          <div className="flex justify-center">
                                                            <img 
                                                              src={subDisplayDiagram} 
                                                              alt="전개도" 
                                                              className="max-w-sm border rounded"
                                                            />
                                                          </div>
                                                        )}
                                                        {subDisplayDetails && (
                                                          <div>
                                                            <Table className="border text-xs">
                                                              <TableHeader>
                                                                <TableRow className="bg-purple-100/50">
                                                                  <TableHead className="text-xs">No</TableHead>
                                                                  <TableHead className="text-xs">입력</TableHead>
                                                                  <TableHead className="text-xs">연신율</TableHead>
                                                                  <TableHead className="text-xs">계산 후</TableHead>
                                                                  <TableHead className="text-xs">합계</TableHead>
                                                                  <TableHead className="text-xs">A각</TableHead>
                                                                </TableRow>
                                                              </TableHeader>
                                                              <TableBody>
                                                                {subDisplayDetails.map((detail: any, detailIdx: number) => (
                                                                  <TableRow key={`sub-bending-detail-${detailIdx}`} className={detail.shaded ? 'bg-gray-100' : 'bg-white'}>
                                                                    <TableCell className="text-xs">{detail.no}</TableCell>
                                                                    <TableCell className="text-xs text-right">{detail.input}</TableCell>
                                                                    <TableCell className="text-xs text-right">{detail.elongation}</TableCell>
                                                                    <TableCell className="text-xs text-right">{detail.calculated || (detail.input + detail.elongation)}</TableCell>
                                                                    <TableCell className="text-xs text-right font-medium">{detail.sum}</TableCell>
                                                                    <TableCell className="text-xs text-right">{detail.aAngle || '-'}</TableCell>
                                                                  </TableRow>
                                                                ))}
                                                              </TableBody>
                                                            </Table>
                                                          </div>
                                                        )}
                                                      </div>
                                                    </TableCell>
                                                  </TableRow>
                                                );
                                              })()}
                                            </Fragment>
                                          );
                                        })}
                                      </TableBody>
                                    </Table>
                                    </div>
                                  </div>
                                </TableCell>
                              </TableRow>
                            )}
                          </Fragment>
                        );
                      })}
                    </TableBody>
                  </Table>
                  </div>
                  
                  {/* 절곡 부품 재질별 폭 합계 */}
                  {(() => {
                    // BOM에서 절곡 부품만 필터링 (메인 BOM + 하위 BOM 모두 포함)
                    const bendingParts: any[] = [];
                    
                    selectedItem.bom.forEach(line => {
                      const childItem = itemMasters.find(item => item.itemCode === line.childItemCode);
                      
                      // 메인 BOM의 절곡 부품
                      if (childItem && (childItem as any).partType === 'BENDING') {
                        bendingParts.push({
                          itemCode: line.childItemCode,
                          itemName: line.childItemName,
                          material: (childItem as any).material || '',
                          width: line.bendingDetails && line.bendingDetails.length > 0
                            ? line.bendingDetails.reduce((sum, d) => sum + d.input + d.elongation, 0)
                            : ((childItem as any).bendingDetails && (childItem as any).bendingDetails.length > 0
                              ? (childItem as any).bendingDetails.reduce((sum: number, d: any) => sum + d.input + d.elongation, 0)
                              : 0),
                          quantity: line.quantity,
                          level: 1
                        });
                      }
                      
                      // 하위 BOM의 절곡 부품
                      if (childItem && childItem.bom && childItem.bom.length > 0) {
                        childItem.bom.forEach((subLine: any) => {
                          const subChildItem = itemMasters.find(item => item.itemCode === subLine.childItemCode);
                          if (subChildItem && (subChildItem as any).partType === 'BENDING') {
                            bendingParts.push({
                              itemCode: subLine.childItemCode,
                              itemName: `${line.childItemName} > ${subLine.childItemName}`,
                              material: (subChildItem as any).material || '',
                              width: subLine.bendingDetails && subLine.bendingDetails.length > 0
                                ? subLine.bendingDetails.reduce((sum: number, d: any) => sum + d.input + d.elongation, 0)
                                : ((subChildItem as any).bendingDetails && (subChildItem as any).bendingDetails.length > 0
                                  ? (subChildItem as any).bendingDetails.reduce((sum: number, d: any) => sum + d.input + d.elongation, 0)
                                  : 0),
                              quantity: line.quantity * subLine.quantity,
                              level: 2
                            });
                          }
                        });
                      }
                    });

                    if (bendingParts.length === 0) return null;

                    // 재질별 폭 합계 계산
                    const materialSummary = bendingParts.reduce((acc: any, part: any) => {
                      const material = part.material || '재질 미지정';
                      if (!acc[material]) {
                        acc[material] = { totalWidth: 0, items: [] };
                      }
                      const totalWidth = part.width * part.quantity;
                      acc[material].totalWidth += totalWidth;
                      acc[material].items.push({
                        itemCode: part.itemCode,
                        itemName: part.itemName,
                        width: part.width,
                        quantity: part.quantity,
                        totalWidth: totalWidth,
                        level: part.level
                      });
                      return acc;
                    }, {});

                    return (
                      <div className="mt-6 p-4 bg-purple-50 rounded-lg border border-purple-200">
                        <h4 className="font-medium mb-3 text-purple-900 flex items-center gap-2">
                          <GitBranch className="h-5 w-5" />
                          절곡 부품 재질별 폭 합계
                        </h4>
                        <div className="space-y-4">
                          {Object.entries(materialSummary).map(([material, data]: [string, any]) => (
                            <div key={material} className="bg-white rounded border border-purple-200 overflow-hidden">
                              <div className="bg-purple-100 px-3 py-2 flex justify-between items-center">
                                <span className="font-medium text-purple-900">{material}</span>
                                <Badge variant="outline" className="bg-purple-200 text-purple-900 px-3 py-1.5">
                                  <span className="text-base">합계: {data.totalWidth.toLocaleString()} mm</span>
                                </Badge>
                              </div>
                              <Table>
                                <TableHeader>
                                  <TableRow className="bg-purple-50/50">
                                    <TableHead className="text-xs">품목코드</TableHead>
                                    <TableHead className="text-xs">품목명</TableHead>
                                    <TableHead className="text-xs text-right">전개 폭</TableHead>
                                    <TableHead className="text-xs text-right">수량</TableHead>
                                    <TableHead className="text-xs text-right">소계</TableHead>
                                  </TableRow>
                                </TableHeader>
                                <TableBody>
                                  {data.items.map((item: any, idx: number) => (
                                    <TableRow key={idx} className={item.level === 2 ? 'bg-blue-50/30' : ''}>
                                      <TableCell className="text-xs">
                                        <code className="bg-gray-100 px-2 py-1 rounded">{item.itemCode}</code>
                                      </TableCell>
                                      <TableCell className="text-xs">
                                        {item.level === 2 && <span className="text-blue-600 mr-1">└</span>}
                                        {item.itemName}
                                      </TableCell>
                                      <TableCell className="text-xs text-right">{item.width.toLocaleString()} mm</TableCell>
                                      <TableCell className="text-xs text-right">{item.quantity}</TableCell>
                                      <TableCell className="text-xs text-right font-medium">
                                        {item.totalWidth.toLocaleString()} mm
                                      </TableCell>
                                    </TableRow>
                                  ))}
                                </TableBody>
                              </Table>
                            </div>
                          ))}
                        </div>
                      </div>
                    );
                  })()}
                </div>
              ) : (
                <div className="text-center py-8 text-muted-foreground border-2 border-dashed rounded-lg">
                  <Package className="h-12 w-12 mx-auto mb-2 opacity-20" />
                  <p>등록된 BOM 품목이 없습니다</p>
                  <p className="text-xs mt-1">품목 수정에서 BOM을 추가할 수 있습니다</p>
                </div>
              )}
            </CardContent>
          </Card>
        )}


        {/* 절곡 정보 - ItemMaster에는 bendingData와 drawingImage 필드가 없어서 주석 처리 */}
        {/* {selectedItem.isBending && (
          <Card>
            <CardHeader>
              <CardTitle>절곡 정보 (바라시)</CardTitle>
            </CardHeader>
            <CardContent>
              <Tabs defaultValue="data" className="w-full">
                <TabsList className="grid w-full grid-cols-2">
                  <TabsTrigger value="data">절곡 데이터</TabsTrigger>
                  <TabsTrigger value="drawing">절곡 형태보기</TabsTrigger>
                </TabsList>

                <TabsContent value="data" className="space-y-4">
                  {selectedItem.bendingData && selectedItem.bendingData.length > 0 ? (
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>순서</TableHead>
                          <TableHead>각도(°)</TableHead>
                          <TableHead>길이(mm)</TableHead>
                          <TableHead>방향</TableHead>
                          <TableHead>공구</TableHead>
                          <TableHead>비고</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {selectedItem.bendingData.map((step, index) => (
                          <TableRow key={step.id}>
                            <TableCell>{index + 1}</TableCell>
                            <TableCell>{step.angle}°</TableCell>
                            <TableCell>{step.length}mm</TableCell>
                            <TableCell>
                              <Badge variant="outline">
                                {step.direction === "up" ? "↑ 위" : "↓ 아래"}
                              </Badge>
                            </TableCell>
                            <TableCell>{step.tool || "-"}</TableCell>
                            <TableCell className="text-sm text-muted-foreground">
                              {step.note || "-"}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  ) : (
                    <div className="text-center py-8 text-muted-foreground">
                      등록된 절곡 데이터가 없습니다
                    </div>
                  )}
                </TabsContent>

                <TabsContent value="drawing" className="space-y-4">
                  {selectedItem.drawingImage ? (
                    <div className="border rounded-lg p-4 bg-white">
                      <img
                        src={selectedItem.drawingImage}
                        alt="절곡 도면"
                        className="max-w-full h-auto mx-auto"
                      />
                    </div>
                  ) : (
                    <div className="border-2 border-dashed rounded-lg p-12 text-center text-muted-foreground">
                      <ImageIcon className="h-12 w-12 mx-auto mb-4 opacity-50" />
                      <p>등록된 도면이 없습니다</p>
                    </div>
                  )}
                </TabsContent>
              </Tabs>
            </CardContent>
          </Card>
        )} */}

        {/* 단가 이력 - ItemMaster에 priceHistory 필드 없음 */}
        {/* {selectedItem.priceHistory && selectedItem.priceHistory.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>단가 이력</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>적용일</TableHead>
                    <TableHead className="text-right">매입단가</TableHead>
                    <TableHead className="text-right">매출단가</TableHead>
                    <TableHead className="text-right">마진율</TableHead>
                    <TableHead>비고</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {selectedItem.priceHistory.map((history) => (
                    <TableRow key={history.id}>
                      <TableCell>{history.effectiveDate}</TableCell>
                      <TableCell className="text-right">
                        {history.purchasePrice
                          ? `${history.purchasePrice.toLocaleString()}원`
                          : "-"}
                      </TableCell>
                      <TableCell className="text-right">
                        {history.salesPrice
                          ? `${history.salesPrice.toLocaleString()}원`
                          : "-"}
                      </TableCell>
                      <TableCell className="text-right">
                        {history.marginRate ? `${history.marginRate}%` : "-"}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {history.note || "-"}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        )} */}

        {/* 첨부파일 - ItemMaster에 attachments 필드 없음 */}
        {/* {selectedItem.attachments && selectedItem.attachments.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>첨부파일</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {selectedItem.attachments.map((file) => (
                  <div
                    key={file.id}
                    className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border"
                  >
                    <div className="flex items-center gap-3">
                      <Package className="h-5 w-5 text-blue-600" />
                      <div>
                        <p className="text-sm font-medium">{file.name}</p>
                        <p className="text-xs text-muted-foreground">
                          {(file.size / 1024).toFixed(1)} KB • {file.uploadedAt}
                        </p>
                      </div>
                    </div>
                    <Button size="sm" variant="ghost">
                      다운로드
                    </Button>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )} */}

        {/* 하단 액션 버튼 */}
        <div className="flex justify-end gap-2 mt-6">
          <Button
            variant="outline"
            size="sm"
            onClick={() => setView("list")}
          >
            목록으로
          </Button>
          <Button
            size="sm"
            onClick={() => handleViewChange("edit", selectedItem)}
          >
            <Edit className="h-4 w-4 mr-2" />
            수정
          </Button>
        </div>
      </PageLayout>
    );
  }

  // 신규 등록 또는 수정 뷰
  return (
    <PageLayout>
      <PageHeader
        title="품목 등록"
        description="품목 정보를 입력하세요"
        icon={Package}
        isEditMode={view === "edit"}
      />
      
      {/* 수정 모드일 때 버전 히스토리 표시 */}
      {view === "edit" && screenVersion.versionHistory.length > 0 && (
        <Card className="border-purple-200 bg-purple-50">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-purple-700">
              <History className="h-5 w-5" />
              품목 수정 이력
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="bg-white border border-purple-200 rounded-lg p-4">
              <div className="text-sm space-y-2">
                <div className="flex items-center justify-between mb-2">
                  <span className="font-semibold text-purple-700">최근 수정 이력</span>
                  <Badge variant="secondary">총 {screenVersion.versionHistory.length}건</Badge>
                </div>
                <div className="max-h-32 overflow-y-auto space-y-2">
                  {screenVersion.versionHistory.slice().reverse().slice(0, 3).map((history) => (
                    <div key={history.id} className="flex items-center gap-2 text-xs">
                      <Badge variant="outline">v{history.version}</Badge>
                      <span className="text-muted-foreground">•</span>
                      <span>{history.changeDescription}</span>
                      <span className="text-muted-foreground">•</span>
                      <span className="text-muted-foreground">{history.changedBy}</span>
                      <span className="text-muted-foreground ml-auto">{new Date(history.changedAt).toLocaleDateString('ko-KR')}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
      
      {/* Validation 에러 요약 */}
      {Object.keys(validationErrors).length > 0 && (
        <Alert className="bg-red-50 border-red-200">
          <AlertDescription className="text-red-900">
            <div className="flex items-start gap-2">
              <span className="text-lg">⚠️</span>
              <div className="flex-1">
                <strong className="block mb-2">입력 내용을 확인해주세요 ({Object.keys(validationErrors).length}개 오류)</strong>
                <ul className="space-y-1 text-sm">
                  {Object.entries(validationErrors).map(([field, message]) => {
                    // 필드명을 한글로 매핑
                    const fieldNameMap: Record<string, string> = {
                      'itemCode': '품목코드',
                      'itemName': '품목명',
                      'itemType': '품목유형',
                      'category': '카테고리',
                      'specification': '규격',
                      'unit': '단위',
                      'unitPrice': '단가',
                      'safetyStock': '안전재고',
                      'leadTime': '리드타임',
                      'supplier': '공급업체',
                    };
                    
                    const fieldLabel = fieldNameMap[field] || field;
                    
                    return (
                      <li key={field} className="flex items-start gap-2">
                        <span className="text-red-600 mt-0.5">•</span>
                        <button
                          type="button"
                          onClick={() => {
                            // 해당 필드의 input/select 요소를 찾아서 스크롤
                            const errorField = document.querySelector(`[name="${field}"]`) as HTMLElement;
                            if (errorField) {
                              errorField.scrollIntoView({ behavior: 'smooth', block: 'center' });
                              errorField.focus();
                            }
                          }}
                          className="text-left hover:underline focus:outline-none focus:underline"
                        >
                          <span className="font-medium">{fieldLabel}:</span> {message}
                        </button>
                      </li>
                    );
                  })}
                </ul>
              </div>
            </div>
          </AlertDescription>
        </Alert>
      )}

      {/* 기본 정보 카드 */}
      <Card className={Object.keys(validationErrors).length > 0 ? "border-red-300" : ""}>
        <CardHeader>
          <CardTitle>기본 정보</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 gap-4">
            {/* 1단계: 품목 유형 먼저 선택 */}
            <div>
              <Label className="flex items-center gap-1">
                품목유형 <span className="text-red-500">*</span> (먼저 선택하세요)
              </Label>
              <Select 
                value={formData.itemType || undefined}
                onValueChange={(value) => {
                  setFormData({ ...formData, itemType: value as "FG" | "PT" | "SM" | "RM" | "CS" });
                  clearFieldError('itemType');
                }}
              >
                <SelectTrigger className={validationErrors.itemType ? "border-2 border-red-500" : "border-2 border-blue-500"} data-error={!!validationErrors.itemType}>
                  <SelectValue placeholder="품목 유형을 선택하세요" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="FG">제품 (Finished Goods)</SelectItem>
                  <SelectItem value="PT">부품 (Part)</SelectItem>
                  <SelectItem value="SM">부자재 (Sub Material)</SelectItem>
                  <SelectItem value="RM">원자재 (Raw Material)</SelectItem>
                  <SelectItem value="CS">소모품 (Consumables)</SelectItem>
                </SelectContent>
              </Select>
              {validationErrors.itemType && (
                <p className="text-sm text-red-500 mt-1">{validationErrors.itemType}</p>
              )}
              <p className="text-xs text-muted-foreground mt-1">
                * 품목 유형에 따라 입력 항목이 다릅니다
              </p>
            </div>

            {/* 2단계: 품목 유형이 선택된 경우에만 표시 */}
            {formData.itemType && (
              <>
                {/* 제품(FG)인 경우 */}
                {formData.itemType === "FG" && (
                  <>
                    <div>
                      <Label className="flex items-center gap-1">
                        상품명 <span className="text-red-500">*</span>
                      </Label>
                      <Input 
                        value={formData.productName}
                        onChange={(e) => {
                          setFormData({ ...formData, productName: e.target.value });
                          clearFieldError('productName');
                        }}
                        placeholder="상품명을 입력하세요 (예: 프리미엄 스크린)"
                        className={validationErrors.productName ? "border-red-500" : ""}
                        data-error={!!validationErrors.productName}
                      />
                      {validationErrors.productName && (
                        <p className="text-sm text-red-500 mt-1">{validationErrors.productName}</p>
                      )}
                      <p className="text-xs text-muted-foreground mt-1">
                        * 고객에게 표시되는 상품명
                      </p>
                    </div>
                    <div>
                      <Label className="flex items-center gap-1">
                        품목명 <span className="text-red-500">*</span>
                      </Label>
                      <Input 
                        value={formData.itemName}
                        onChange={(e) => {
                          const newName = e.target.value;
                          setFormData({ ...formData, itemName: newName });
                          clearFieldError('itemName');
                        }}
                        placeholder="품목명을 입력하세요"
                        className={validationErrors.itemName ? "border-red-500" : ""}
                        data-error={!!validationErrors.itemName}
                      />
                      {validationErrors.itemName && (
                        <p className="text-sm text-red-500 mt-1">{validationErrors.itemName}</p>
                      )}
                    </div>
                    <div>
                      <Label>품목코드 (자동생성)</Label>
                      <Input 
                        value={formData.itemName || ""}
                        disabled
                        className="bg-muted text-muted-foreground"
                        placeholder="품목명이 입력되면 자동으로 동일하게 생성됩니다"
                      />
                      <p className="text-xs text-muted-foreground mt-1">
                        * 품목명과 품목코드가 동일하게 설정됩니다
                      </p>
                    </div>
                    <div>
                      <Label>로트 약자</Label>
                      <Input 
                        value={formData.lotAbbreviation}
                        onChange={(e) => setFormData({ ...formData, lotAbbreviation: e.target.value })}
                        placeholder="로트 약자를 입력하세요"
                        maxLength={10}
                      />
                      <p className="text-xs text-muted-foreground mt-1">
                        * 로트 번호 생성 시 사용되는 약자 (선택사항)
                      </p>
                    </div>
                    <div>
                      <Label>품목 상태</Label>
                      <Select 
                        value={formData.isActive ? "active" : "inactive"}
                        onValueChange={(value) => setFormData({ ...formData, isActive: value === "active" })}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="active">활성</SelectItem>
                          <SelectItem value="inactive">비활성</SelectItem>
                        </SelectContent>
                      </Select>
                      <p className="text-xs text-muted-foreground mt-1">
                        * 비활성 시 품목 사용이 제한됩니다
                      </p>
                    </div>
                  </>
                )}

                {/* 부품(PT)인 경우 */}
                {formData.itemType === "PT" && (
                  <>
                    {/* 부품 유형 - 항상 표시 */}
                    <div>
                      <Label className="flex items-center gap-1">
                        부품 유형 <span className="text-red-500">*</span>
                      </Label>
                      <Select 
                        value={formData.partType || undefined}
                        onValueChange={(value) => {
                          setFormData({ 
                            ...formData, 
                            partType: value as any, 
                            category1: "",
                            // 절곡 부품은 BOM이 없으므로 needsBOM을 false로 설정
                            // 조립 부품은 기본값으로 needsBOM을 true로 설정
                            needsBOM: value === "BENDING" ? false : value === "ASSEMBLY" ? true : formData.needsBOM
                          });
                          clearFieldError('partType');
                        }}
                      >
                        <SelectTrigger className={validationErrors.partType ? "border-red-500" : ""} data-error={!!validationErrors.partType}>
                          <SelectValue placeholder="부품 유형을 선택하세요" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="ASSEMBLY">조립 부품 (Assembly Part)</SelectItem>
                          <SelectItem value="BENDING">절곡 부품 (Bending Part) - 전개도만 사용</SelectItem>
                          <SelectItem value="PURCHASED">구매 부품 (Purchased Part)</SelectItem>
                        </SelectContent>
                      </Select>
                      {validationErrors.partType && (
                        <p className="text-sm text-red-500 mt-1">{validationErrors.partType}</p>
                      )}
                      {formData.partType === "BENDING" && (
                        <p className="text-xs text-muted-foreground mt-1">
                          * 절곡 부품은 전개도(바라시)만 있으며, 부품 구성(BOM)은 사용하지 않습니다.
                        </p>
                      )}
                    </div>

                    {/* 조립 부품인 경우 품목명 직접 선택 */}
                    {formData.partType === "ASSEMBLY" && (
                      <>
                        <div>
                          <Label className="flex items-center gap-1">
                            품목명 <span className="text-red-500">*</span>
                          </Label>
                          <Select 
                            value={formData.category1 || undefined}
                            onValueChange={(value) => {
                              // 선택된 값에 따라 품목명 자동 설정
                              let autoItemName = "";
                              if (value === "guide_rail") autoItemName = "가이드레일";
                              else if (value === "case") autoItemName = "케이스";
                              else if (value === "bottom_finish") autoItemName = "하단마감재";
                              
                              setFormData({ ...formData, category1: value, itemName: autoItemName });
                              clearFieldError('category1');
                            }}
                          >
                            <SelectTrigger className={validationErrors.category1 ? "border-red-500" : ""} data-error={!!validationErrors.category1}>
                              <SelectValue placeholder="품목명을 선택하세요" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="guide_rail">가이드레일</SelectItem>
                              <SelectItem value="case">케이스</SelectItem>
                              <SelectItem value="bottom_finish">하단마감재</SelectItem>
                            </SelectContent>
                          </Select>
                          {validationErrors.category1 && (
                            <p className="text-sm text-red-500 mt-1">{validationErrors.category1}</p>
                          )}
                        </div>

                        {/* 가이드레일 선택 시에만 표시되는 필드 */}
                        {formData.category1 === "guide_rail" && (
                          <>
                            {/* 설치 유형 */}
                            <div>
                              <Label className="flex items-center gap-1">
                                설치 유형 <span className="text-red-500">*</span>
                              </Label>
                              <Select 
                                value={formData.installationType || undefined}
                                onValueChange={(value) => {
                                  // category2 자동 설정: R(벽면형) 또는 S(측면형)
                                  const category2 = value === "wall" ? "R" : "S";
                                  setFormData({ ...formData, installationType: value, category2 });
                                  clearFieldError('installationType');
                                }}
                              >
                                <SelectTrigger className={validationErrors.installationType ? "border-red-500" : ""} data-error={!!validationErrors.installationType}>
                                  <SelectValue placeholder="설치 유형을 선택하세요" />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="wall">벽면형 (R)</SelectItem>
                                  <SelectItem value="side">측면형 (S)</SelectItem>
                                </SelectContent>
                              </Select>
                              {validationErrors.installationType && (
                                <p className="text-sm text-red-500 mt-1">{validationErrors.installationType}</p>
                              )}
                            </div>
                          </>
                        )}

                        {/* 케이스 선택 시에만 표시되는 필드 */}
                        {formData.category1 === "case" && (
                          <>
                            {/* 설치 유형 */}
                            <DynamicSelectField
                              label="설치유형"
                              fieldKey="installationType"
                              value={formData.installationType}
                              onChange={(value) => {
                                // category2를 C로 고정
                                setFormData({ ...formData, installationType: value, category2: "C" });
                                clearFieldError('installationType');
                              }}
                              itemMasterFields={itemMasterFields}
                              placeholder="설치 유형을 선택하세요"
                              error={validationErrors.installationType}
                              clearError={() => clearFieldError('installationType')}
                              required={true}
                              fallbackOptions={['표준형 (C)']}
                            />
                          </>
                        )}

                        {/* 하단마감재 선택 시에만 표시되는 필드 */}
                        {formData.category1 === "bottom_finish" && (
                          <>
                            {/* 설치 유형 선택 */}
                            <div>
                              <Label className="flex items-center gap-1">
                                설치 유형 <span className="text-red-500">*</span>
                              </Label>
                              <Select 
                                value={formData.installationType || undefined}
                                onValueChange={(value) => {
                                  // category2 자동 설정: B(스크린) 또는 T(철재)
                                  const category2 = value === "steel" ? "B" : "T";
                                  setFormData({ ...formData, installationType: value, category2 });
                                  clearFieldError('installationType');
                                }}
                              >
                                <SelectTrigger className={validationErrors.installationType ? "border-red-500" : ""} data-error={!!validationErrors.installationType}>
                                  <SelectValue placeholder="설치 유형을 선택하세요" />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="steel">스크린 (B)</SelectItem>
                                  <SelectItem value="iron">철재 (T)</SelectItem>
                                </SelectContent>
                              </Select>
                              {validationErrors.installationType && (
                                <p className="text-sm text-red-500 mt-1">{validationErrors.installationType}</p>
                              )}
                            </div>
                          </>
                        )}

                        {/* 단위 */}
                        <DynamicSelectField
                          label="단위"
                          fieldKey="unit"
                          value={formData.unit}
                          onChange={(value) => {
                            setFormData({ ...formData, unit: value });
                            clearFieldError('unit');
                          }}
                          itemMasterFields={itemMasterFields}
                          placeholder="단위를 선택하세요"
                          error={validationErrors.unit}
                          clearError={() => clearFieldError('unit')}
                          required={true}
                          fallbackOptions={['M', 'mm', 'EA', 'SET', 'KG', 'T', 'BOX', 'L', 'M2', 'M3', 'ROLL', 'SHEET', 'PACK']}
                        />

                        {/* 마감 */}
                        <DynamicSelectField
                          label="마감"
                          fieldKey="finishing"
                          value={formData.finishing}
                          onChange={(value) => {
                            setFormData({ ...formData, finishing: value });
                            clearFieldError('finishing');
                          }}
                          itemMasterFields={itemMasterFields}
                          placeholder="마감을 선택하세요"
                          error={validationErrors.finishing}
                          clearError={() => clearFieldError('finishing')}
                          required={true}
                          fallbackOptions={['SUS마감', 'EGI마감']}
                        />

                        {/* 비고 */}
                        <div>
                          <Label>비고</Label>
                          <Input 
                            value={formData.description}
                            onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                            placeholder="비고 사항을 입력하세요"
                          />
                        </div>

                        {/* 조립 부품 공통 입력: 측면 규격 및 길이 */}
                        <div className="border-t pt-4">
                          <h4 className="text-sm font-semibold mb-3">측면 규격 및 길이</h4>
                          <div className="grid grid-cols-1 gap-3">
                            <div>
                              <Label className="flex items-center gap-1">
                                측면 규격 (가로) <span className="text-red-500">*</span>
                              </Label>
                              <Input 
                                type="number"
                                value={formData.sideSpecWidth || ""} 
                                onChange={(e) => {
                                  setFormData({ ...formData, sideSpecWidth: e.target.value });
                                  clearFieldError('sideSpecWidth');
                                }}
                                placeholder="예: 50"
                                className={validationErrors.sideSpecWidth ? "border-red-500" : ""}
                              />
                              {validationErrors.sideSpecWidth && (
                                <p className="text-sm text-red-500 mt-1">{validationErrors.sideSpecWidth}</p>
                              )}
                            </div>
                            <div>
                              <Label className="flex items-center gap-1">
                                측면 규격 (세로) <span className="text-red-500">*</span>
                              </Label>
                              <Input 
                                type="number"
                                value={formData.sideSpecHeight || ""} 
                                onChange={(e) => {
                                  setFormData({ ...formData, sideSpecHeight: e.target.value });
                                  clearFieldError('sideSpecHeight');
                                }}
                                placeholder="예: 100"
                                className={validationErrors.sideSpecHeight ? "border-red-500" : ""}
                              />
                              {validationErrors.sideSpecHeight && (
                                <p className="text-sm text-red-500 mt-1">{validationErrors.sideSpecHeight}</p>
                              )}
                            </div>
                            <DynamicSelectField
                              label="길이"
                              fieldKey="assemblyLength"
                              value={formData.assemblyLength}
                              onChange={(value) => {
                                setFormData({ ...formData, assemblyLength: value });
                                clearFieldError('assemblyLength');
                              }}
                              itemMasterFields={itemMasterFields}
                              placeholder="길이 선택"
                              error={validationErrors.assemblyLength}
                              clearError={() => clearFieldError('assemblyLength')}
                              required={true}
                              fallbackOptions={['1219', '2438', '3000', '3500', '4000', '4150', '4200', '4300']}
                            />
                          </div>
                          <p className="text-xs text-muted-foreground mt-2">
                            * 품목코드: {(() => {
                              const installationTypeMap: Record<string, string> = {
                                "standard": "표준형",
                                "wall": "벽면형",
                                "side": "측면형",
                                "mixed": "혼합형"
                              };
                              const installationTypeKorean = installationTypeMap[formData.installationType] || formData.installationType;
                              
                              if (formData.itemName && formData.installationType && formData.sideSpecWidth && formData.sideSpecHeight && formData.assemblyLength) {
                                const lengthNum = parseInt(formData.assemblyLength);
                                let lengthCode = "";
                                if (lengthNum === 1219) lengthCode = "12";
                                else if (lengthNum === 2438) lengthCode = "24";
                                else if (lengthNum === 3000) lengthCode = "30";
                                else if (lengthNum === 3500) lengthCode = "35";
                                else if (lengthNum === 4000) lengthCode = "40";
                                else if (lengthNum === 4150) lengthCode = "41";
                                else if (lengthNum === 4200) lengthCode = "42";
                                else if (lengthNum === 4300) lengthCode = "43";
                                else lengthCode = Math.floor(lengthNum / 100).toString().padStart(2, '0');
                                
                                return `${formData.itemName} ${installationTypeKorean}-${formData.sideSpecWidth}*${formData.sideSpecHeight}*${lengthCode}`;
                              }
                              return "품목명 설치유형-?*?*?";
                            })()}
                          </p>
                        </div>
                      </>
                    )}

                    {/* 절곡 부품 및 구매 부품인 경우 품목명 */}
                    {(formData.partType === "BENDING" || formData.partType === "PURCHASED") && (
                      <div>
                        <Label className="flex items-center gap-1">
                          품목명 <span className="text-red-500">*</span>
                        </Label>
                        <Select 
                          value={formData.category1 || undefined}
                          onValueChange={(value) => {
                            // 선택된 카테고리의 코드 찾기
                            const selectedCategory = PART_TYPE_CATEGORIES[formData.partType as keyof typeof PART_TYPE_CATEGORIES]?.categories.find(cat => cat.value === value);
                            const categoryCode = selectedCategory?.code || "";
                            
                            setFormData({ 
                              ...formData, 
                              category1: value, 
                              category2: categoryCode, // category2에 품목명 코드 저장
                              category3: "" // 종류 코드는 초기화
                            });
                            clearFieldError('category1');
                          }}
                        >
                          <SelectTrigger className={validationErrors.category1 ? "border-red-500" : ""} data-error={!!validationErrors.category1}>
                            <SelectValue placeholder="품목명을 선택하세요" />
                          </SelectTrigger>
                          <SelectContent>
                            {PART_TYPE_CATEGORIES[formData.partType as keyof typeof PART_TYPE_CATEGORIES].categories.map((cat) => (
                              <SelectItem key={cat.value} value={cat.value}>
                                {cat.label} ({cat.code})
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        {validationErrors.category1 && (
                          <p className="text-sm text-red-500 mt-1">{validationErrors.category1}</p>
                        )}
                      </div>
                    )}

                    {/* 종류 선택 - 절곡 부품의 케이스/하단마감재/가이드레일 */}
                    {formData.partType === "BENDING" && formData.category1 && PART_ITEM_NAMES[formData.category1 as keyof typeof PART_ITEM_NAMES] && (
                      <div>
                        <Label className="flex items-center gap-1">
                          종류 <span className="text-red-500">*</span>
                        </Label>
                        <Select 
                          value={formData.itemName || undefined}
                          onValueChange={(value) => {
                            // label 값을 찾아서 저장하고 코드도 함께 저장
                            const selectedItem = PART_ITEM_NAMES[formData.category1 as keyof typeof PART_ITEM_NAMES].find(item => item.label === value);
                            const itemCode = selectedItem?.code || "";
                            
                            setFormData({ 
                              ...formData, 
                              itemName: selectedItem ? selectedItem.label : value,
                              category3: itemCode // category3에 종류 코드 저장
                            });
                            clearFieldError('itemName');
                          }}
                        >
                          <SelectTrigger className={validationErrors.itemName ? "border-red-500" : ""} data-error={!!validationErrors.itemName}>
                            <SelectValue placeholder="종류를 선택하세요" />
                          </SelectTrigger>
                          <SelectContent>
                            {PART_ITEM_NAMES[formData.category1 as keyof typeof PART_ITEM_NAMES].map((item) => (
                              <SelectItem key={item.value} value={item.label}>
                                {item.label} ({item.code})
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        {validationErrors.itemName && (
                          <p className="text-sm text-red-500 mt-1">{validationErrors.itemName}</p>
                        )}
                      </div>
                    )}

                    {/* 전동개폐기 선택 시 동적 필드 */}
                    {formData.category1 === "electric_opener" && (
                      <>
                        <div>
                          <Label className="flex items-center gap-1">
                            전원 <span className="text-red-500">*</span>
                          </Label>
                          <Select 
                            value={formData.electricOpenerPower || undefined}
                            onValueChange={(value) => {
                              setFormData({ ...formData, electricOpenerPower: value });
                              clearFieldError('electricOpenerPower');
                            }}
                          >
                            <SelectTrigger className={validationErrors.electricOpenerPower ? "border-red-500" : ""} data-error={!!validationErrors.electricOpenerPower}>
                              <SelectValue placeholder="전원을 선택하세요" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="220V">220V</SelectItem>
                              <SelectItem value="380V">380V</SelectItem>
                            </SelectContent>
                          </Select>
                          {validationErrors.electricOpenerPower && (
                            <p className="text-sm text-red-500 mt-1">{validationErrors.electricOpenerPower}</p>
                          )}
                        </div>

                        <div>
                          <Label className="flex items-center gap-1">
                            용량 <span className="text-red-500">*</span>
                          </Label>
                          <Select 
                            value={formData.electricOpenerCapacity || undefined}
                            onValueChange={(value) => {
                              setFormData({ ...formData, electricOpenerCapacity: value });
                              clearFieldError('electricOpenerCapacity');
                            }}
                          >
                            <SelectTrigger className={validationErrors.electricOpenerCapacity ? "border-red-500" : ""} data-error={!!validationErrors.electricOpenerCapacity}>
                              <SelectValue placeholder="용량을 선택하세요" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="150">150 KG</SelectItem>
                              <SelectItem value="300">300 KG</SelectItem>
                              <SelectItem value="400">400 KG</SelectItem>
                              <SelectItem value="500">500 KG</SelectItem>
                              <SelectItem value="600">600 KG</SelectItem>
                              <SelectItem value="800">800 KG</SelectItem>
                              <SelectItem value="1000">1000 KG</SelectItem>
                            </SelectContent>
                          </Select>
                          {validationErrors.electricOpenerCapacity && (
                            <p className="text-sm text-red-500 mt-1">{validationErrors.electricOpenerCapacity}</p>
                          )}
                        </div>
                      </>
                    )}

                    {/* 모터 선택 시 동적 필드 */}
                    {(formData.category1 === "motor" || formData.category1 === "purchased_motor") && (
                      <div className="grid grid-cols-1 gap-4 p-4 bg-green-50 rounded-lg border border-green-200">
                        <div>
                          <Label>모터 용량 (kg) *</Label>
                          <Input
                            type="number"
                            placeholder="예: 1.5"
                            step="0.1"
                          />
                        </div>
                        
                        <div>
                          <Label>전압 (V) *</Label>
                          <Select>
                            <SelectTrigger>
                              <SelectValue placeholder="전압 선택" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="220">220V</SelectItem>
                              <SelectItem value="380">380V</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                    )}

                    {/* 체인 선택 시 동적 필드 */}
                    {formData.category1 === "chain" && (
                      <div className="grid grid-cols-1 gap-4 p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                        <div>
                          <Label>체인 규격 *</Label>
                          <Select>
                            <SelectTrigger>
                              <SelectValue placeholder="규격 선택" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="40">40</SelectItem>
                              <SelectItem value="50">50</SelectItem>
                              <SelectItem value="60">60</SelectItem>
                              <SelectItem value="80">80</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        
                        <div>
                          <Label>길이 (링크 수) *</Label>
                          <Input
                            type="number"
                            placeholder="예: 100"
                          />
                        </div>
                      </div>
                    )}

                    {/* 부품 유형에 따른 필드 */}
                    {formData.partType && formData.category1 && (
                      <>
                        {/* 품목명과 규격 입력 - 절곡 부품, 조립 부품, 전동개폐기 제외 */}
                        {formData.partType !== "BENDING" && formData.partType !== "ASSEMBLY" && formData.category1 !== "electric_opener" && (
                          <>
                            <div>
                              <Label className="flex items-center gap-1">
                                품목명 <span className="text-red-500">*</span>
                              </Label>
                              <Input 
                                value={formData.itemName}
                                onChange={(e) => {
                                  setFormData({ ...formData, itemName: e.target.value });
                                  clearFieldError('itemName');
                                }}
                                placeholder="예: 가이드레일"
                                className={validationErrors.itemName ? "border-red-500" : ""}
                                data-error={!!validationErrors.itemName}
                              />
                              {validationErrors.itemName && (
                                <p className="text-sm text-red-500 mt-1">{validationErrors.itemName}</p>
                              )}
                            </div>

                            <div>
                              <Label className="flex items-center gap-1">
                                규격 <span className="text-red-500">*</span>
                              </Label>
                              <Input 
                                value={formData.specification}
                                onChange={(e) => {
                                  setFormData({ ...formData, specification: e.target.value });
                                  clearFieldError('specification');
                                }}
                                placeholder="예: 6063-T5, SUS304, EGI 1.6T"
                                className={validationErrors.specification ? "border-red-500" : ""}
                                data-error={!!validationErrors.specification}
                              />
                              {validationErrors.specification && (
                                <p className="text-sm text-red-500 mt-1">{validationErrors.specification}</p>
                              )}
                            </div>
                          </>
                        )}
                        
                        {/* 절곡품인 경우 재질, 폭 합계, 길이, 단면규격 */}
                        {formData.partType === "BENDING" && (
                          <div className="grid grid-cols-1 gap-4 p-4 bg-purple-50 rounded-lg border border-purple-200">
                            <DynamicSelectField
                              label="재질"
                              fieldKey="material"
                              value={formData.material}
                              onChange={(value) => {
                                setFormData({ ...formData, material: value });
                                clearFieldError('material');
                              }}
                              itemMasterFields={itemMasterFields}
                              placeholder="재질을 선택하세요"
                              error={validationErrors.material}
                              clearError={() => clearFieldError('material')}
                              required={true}
                              fallbackOptions={['EGI 1.15T', 'EGI 1.55T', 'SUS 1.2T', 'SUS 1.5T']}
                            />

                            <div>
                              <Label className="flex items-center gap-1">
                                폭 합계 <span className="text-red-500">*</span>
                              </Label>
                              <div className="flex items-center gap-2">
                                <Input
                                  type="number"
                                  value={formData.length}
                                  onChange={(e) => {
                                    setFormData({ ...formData, length: e.target.value });
                                    clearFieldError('length');
                                  }}
                                  placeholder="전개도 상세를 입력해주세요"
                                  readOnly={(formData as any).bendingDetails && (formData as any).bendingDetails.length > 0}
                                  className={`${(formData as any).bendingDetails && (formData as any).bendingDetails.length > 0 ? "bg-blue-50 font-medium" : ""} ${validationErrors.length ? "border-red-500" : ""}`}
                                  data-error={!!validationErrors.length}
                                />
                                <span className="text-sm text-muted-foreground">mm</span>
                              </div>
                              {validationErrors.length && !(formData as any).bendingDetails?.length && (
                                <p className="text-sm text-red-500 mt-1">{validationErrors.length}</p>
                              )}
                              {(formData as any).bendingDetails && (formData as any).bendingDetails.length > 0 && (
                                <p className="text-xs text-blue-600 mt-1">
                                  * 전개도 상세 입력의 합계가 자동 반영됩니다
                                </p>
                              )}
                            </div>

                            <DynamicSelectField
                              label="모양&길이"
                              fieldKey="bendingLength"
                              value={formData.bendingLength}
                              onChange={(value) => {
                                setFormData({ ...formData, bendingLength: value });
                                clearFieldError('bendingLength');
                              }}
                              itemMasterFields={itemMasterFields}
                              placeholder="모양&길이를 선택하세요"
                              error={validationErrors.bendingLength}
                              clearError={() => clearFieldError('bendingLength')}
                              required={true}
                              fallbackOptions={['W50x3000', 'W50x4000', 'W80x3000', 'W80x4000', '1219', '2438', '3000', '3500', '4000', '4150', '4200', '4300']}
                            />
                          </div>
                        )}

                        {/* 구매 부품 또는 절곡 부품인 경우 단위와 비고 */}
                        {(formData.partType === "PURCHASED" || formData.partType === "BENDING") && (
                          <>
                            <DynamicSelectField
                              label="단위"
                              fieldKey="unit"
                              value={formData.unit}
                              onChange={(value) => {
                                setFormData({ ...formData, unit: value });
                                clearFieldError('unit');
                              }}
                              itemMasterFields={itemMasterFields}
                              placeholder="단위 선택"
                              error={validationErrors.unit}
                              clearError={() => clearFieldError('unit')}
                              required={true}
                              fallbackOptions={['M', 'mm', 'EA', 'SET', 'KG', 'T', 'BOX', 'L', 'M2', 'M3', 'ROLL', 'SHEET', 'PACK']}
                            />

                            <div>
                              <Label>비고</Label>
                              <Input 
                                value={formData.description}
                                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                                placeholder="비고 사항을 입력하세요"
                              />
                            </div>
                          </>
                        )}

                        {/* 품목코드 자동생성 - 구매 부품 또는 절곡 부품 */}
                        {(formData.partType === "PURCHASED" || formData.partType === "BENDING") && (
                          <div>
                            <Label>품목코드 (자동생성)</Label>
                            <Input 
                              value={generateItemCode(
                                formData.category1 === "guide_rail" && formData.guideRailModelType && formData.guideRailModel 
                                  ? generateGuideRailItemName() 
                                  : formData.itemName, 
                                formData.specification
                              )}
                              disabled
                              className="bg-muted text-muted-foreground"
                              placeholder={formData.partType === "BENDING" && formData.category1 === "guide_rail"
                                ? "종류와 길이를 입력하면 자동으로 생성됩니다 (예: RD30)"
                                : formData.partType === "BENDING"
                                ? "품목명, 종류, 길이를 입력하면 자동으로 생성됩니다"
                                : formData.category1 === "guide_rail" 
                                ? "모델유형, 모델선택, 규격을 입력하면 자동으로 생성됩니다" 
                                : "품목명과 규격이 입력되면 자동으로 생성됩니다"}
                            />
                            <p className="text-xs text-muted-foreground mt-1">
                              {formData.partType === "BENDING" && formData.category1 === "guide_rail"
                                ? "* 가이드레일 품목코드는 '제품구분(R/S)+종류(M/T/C/D/S/U)+모양&길이' 형식으로 자동 생성됩니다 (예: RD30, SM53)"
                                : formData.partType === "BENDING" 
                                ? "* 절곡 부품 품목코드는 '품목명+종류+길이축약' 형식으로 자동 생성됩니다 (예: 케이스후면부30)"
                                : formData.category1 === "guide_rail" 
                                ? "* 가이드레일 품목코드는 '제품구분+종류+길이축약' 형식으로 자동 생성됩니다 (예: RC30)"
                                : "* 품목코드는 '품목명-규격' 형식으로 자동 생성됩니다"}
                            </p>
                          </div>
                        )}
                      </>
                    )}
                    
                    {/* 부품 활성/비활성 선택 */}
                    {formData.partType && (
                      <div>
                        <Label>품목 상태</Label>
                        <Select 
                          value={formData.isActive ? "active" : "inactive"}
                          onValueChange={(value) => setFormData({ ...formData, isActive: value === "active" })}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="active">활성</SelectItem>
                            <SelectItem value="inactive">비활성</SelectItem>
                          </SelectContent>
                        </Select>
                        <p className="text-xs text-muted-foreground mt-1">
                          * 비활성 시 품목 사용이 제한됩니다
                        </p>
                      </div>
                    )}
                  </>
                )}

                {/* 원자재/부자재/소모품인 경우 */}
                {(formData.itemType === "RM" || formData.itemType === "SM" || formData.itemType === "CS") && (
                  <>
                    <div>
                      <Label className="flex items-center gap-1">
                        품목명 <span className="text-red-500">*</span>
                      </Label>
                      {/* 원자재/부자재는 목록에서 선택, 소모품은 직접 입력 */}
                      {(formData.itemType === "RM" || formData.itemType === "SM") ? (
                        <>
                          <Select 
                            value={formData.itemName}
                            onValueChange={(value) => {
                              setFormData({ ...formData, itemName: value });
                              clearFieldError('itemName');
                            }}
                          >
                            <SelectTrigger 
                              className={validationErrors.itemName ? "border-red-500" : ""}
                              data-error={!!validationErrors.itemName}
                            >
                              <SelectValue placeholder="품목명을 선택하세요" />
                            </SelectTrigger>
                            <SelectContent>
                              {materialItemNames
                                .filter(item => item.itemType === formData.itemType)
                                .map((item) => (
                                  <SelectItem key={item.id} value={item.itemName}>
                                    {item.itemName}
                                  </SelectItem>
                                ))}
                            </SelectContent>
                          </Select>
                          {validationErrors.itemName && (
                            <p className="text-sm text-red-500 mt-1">{validationErrors.itemName}</p>
                          )}
                        </>
                      ) : (
                        <>
                          <Input 
                            value={formData.itemName}
                            onChange={(e) => {
                              setFormData({ ...formData, itemName: e.target.value });
                              clearFieldError('itemName');
                            }}
                            placeholder="품목명을 입력하세요"
                            className={validationErrors.itemName ? "border-red-500" : ""}
                            data-error={!!validationErrors.itemName}
                          />
                          {validationErrors.itemName && (
                            <p className="text-sm text-red-500 mt-1">{validationErrors.itemName}</p>
                          )}
                        </>
                      )}
                    </div>
                    {/* 소모품일 경우: 기존 규격 입력 */}
                    {formData.itemType === "CS" && (
                      <div>
                        <Label className="flex items-center gap-1">
                          규격(사양) <span className="text-red-500">*</span>
                        </Label>
                        <Input 
                          value={formData.specification}
                          onChange={(e) => {
                            setFormData({ ...formData, specification: e.target.value });
                            clearFieldError('specification');
                          }}
                          placeholder="예: 면-L, 고급형, A4"
                          className={validationErrors.specification ? "border-red-500" : ""}
                          data-error={!!validationErrors.specification}
                        />
                        {validationErrors.specification && (
                          <p className="text-sm text-red-500 mt-1">{validationErrors.specification}</p>
                        )}
                      </div>
                    )}

                    {/* 원자재/부자재일 경우: 규격 선택 */}
                    {(formData.itemType === "RM" || formData.itemType === "SM") && (
                      <div>
                        <Label className="flex items-center gap-1">
                          규격 <span className="text-red-500">*</span>
                        </Label>
                        <Select 
                          value={formData.specification}
                          onValueChange={(value) => {
                            setFormData({ ...formData, specification: value });
                            clearFieldError('specification');
                          }}
                        >
                          <SelectTrigger className={validationErrors.specification ? "border-red-500" : ""}>
                            <SelectValue placeholder="규격을 선택하세요" />
                          </SelectTrigger>
                          <SelectContent>
                            {specificationMasters
                              .filter(spec => 
                                spec.itemType === formData.itemType && 
                                spec.isActive &&
                                (!formData.itemName || spec.itemName === formData.itemName)
                              )
                              .map(spec => (
                                <SelectItem key={spec.id} value={spec.specificationCode}>
                                  {spec.specificationCode}
                                  {spec.description && ` (${spec.description})`}
                                </SelectItem>
                              ))}
                          </SelectContent>
                        </Select>
                        {validationErrors.specification && (
                          <p className="text-sm text-red-500 mt-1">{validationErrors.specification}</p>
                        )}
                        <p className="text-xs text-muted-foreground mt-1">
                          * 규격은 품목명 선택 시 자동으로 필터링됩니다
                        </p>
                      </div>
                    )}
                    <div>
                      <Label>품목코드 (자동생성)</Label>
                      <Input 
                        value={generateItemCode(formData.itemName, formData.specification)}
                        disabled
                        className="bg-muted text-muted-foreground"
                        placeholder="품목명과 규격이 입력되면 자동으로 생성됩니다"
                      />
                      <p className="text-xs text-muted-foreground mt-1">
                        * 품목코드는 '품목명-규격' 형식으로 자동 생성됩니다
                      </p>
                    </div>
                    
                    {/* 원자재/부자재 활성/비활성 선택 */}
                    {(formData.itemType === "RM" || formData.itemType === "SM") && (
                      <div>
                        <Label>품목 상태</Label>
                        <Select 
                          value={formData.isActive ? "active" : "inactive"}
                          onValueChange={(value) => setFormData({ ...formData, isActive: value === "active" })}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="active">활성</SelectItem>
                            <SelectItem value="inactive">비활성</SelectItem>
                          </SelectContent>
                        </Select>
                        <p className="text-xs text-muted-foreground mt-1">
                          * 비활성 시 품목 사용이 제한됩니다
                        </p>
                      </div>
                    )}
                  </>
                )}



                {/* 원자재/부자재/소모품인 경우: 단위 */}
                {formData.itemType !== "FG" && formData.itemType !== "PT" && (
                  <DynamicSelectField
                    label="단위"
                    fieldKey="unit"
                    value={formData.unit}
                    onChange={(value) => {
                      setFormData({ ...formData, unit: value });
                      clearFieldError('unit');
                    }}
                    itemMasterFields={itemMasterFields}
                    placeholder="단위를 선택하세요"
                    error={validationErrors.unit}
                    clearError={() => clearFieldError('unit')}
                    required={true}
                    fallbackOptions={['M', 'mm', 'EA', 'SET', 'KG', 'T', 'BOX', 'L', 'M2', 'M3', 'ROLL', 'SHEET', 'PACK']}
                  />
                )}
              </>
            )}
          </div>
          
          {formData.itemType && formData.itemType !== "PT" && (
            <div>
              <Label>비고</Label>
              <Input 
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="비고 사항을 입력하세요"
              />
            </div>
          )}

          {/* 인정 정보 - 제품(FG)만 표시 */}
          {formData.itemType === "FG" && (
            <>
              <div className="pt-4 border-t">
                <div className="grid grid-cols-1 gap-4">
                  <div>
                    <Label>인정번호</Label>
                    <Input 
                      value={formData.certificationNumber}
                      onChange={(e) => setFormData({ ...formData, certificationNumber: e.target.value })}
                      placeholder="인정번호를 입력하세요"
                    />
                  </div>
                  <div>
                    <Label>인정 유효기간 시작일</Label>
                    <Input 
                      type="date"
                      value={formData.certificationStartDate}
                      onChange={(e) => setFormData({ ...formData, certificationStartDate: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label>인정 유효기간 종료일</Label>
                    <Input 
                      type="date"
                      value={formData.certificationEndDate}
                      onChange={(e) => setFormData({ ...formData, certificationEndDate: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label>시방서 (PDF)</Label>
                    <div className="flex gap-2">
                      <Input 
                        type="file"
                        accept="application/pdf"
                        onChange={(e) => handleFileUpload(e, 'specification')}
                        className="flex-1"
                      />
                      {formData.specificationFileName && (
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => handleFileRemove('specification')}
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                    {formData.specificationFileName && (
                      <p className="text-xs text-muted-foreground mt-1">
                        첨부됨: {formData.specificationFileName}
                      </p>
                    )}
                  </div>
                  <div>
                    <Label>인정서 (PDF)</Label>
                    <div className="flex gap-2">
                      <Input 
                        type="file"
                        accept="application/pdf"
                        onChange={(e) => handleFileUpload(e, 'certification')}
                        className="flex-1"
                      />
                      {formData.certificationFileName && (
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => handleFileRemove('certification')}
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                    {formData.certificationFileName && (
                      <p className="text-xs text-muted-foreground mt-1">
                        첨부됨: {formData.certificationFileName}
                      </p>
                    )}
                  </div>
                  <div>
                    <Label>비고</Label>
                    <Textarea 
                      value={formData.note}
                      onChange={(e) => setFormData({ ...formData, note: e.target.value })}
                      placeholder="비고 사항을 입력하세요"
                      rows={3}
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      * 추가 설명이나 특이사항을 기록할 수 있습니다
                    </p>
                  </div>
                </div>
              </div>
            </>
          )}


          {/* 부품/제품인 경우 BOM 필요 여부 체크박스 - 절곡 부품은 제외, 조립 부품은 품목명 선택 시 */}
          {(
            formData.itemType === "FG" || 
            (formData.itemType === "PT" && formData.partType === "ASSEMBLY" && formData.category1) ||
            (formData.itemType === "PT" && formData.partType === "PURCHASED")
          ) && (
            <div className="pt-4 border-t">
              <div className="flex items-center space-x-2">
                <Checkbox 
                  id="needsBOM"
                  checked={formData.needsBOM}
                  onCheckedChange={(checked) => setFormData({ ...formData, needsBOM: checked as boolean })}
                />
                <Label htmlFor="needsBOM" className="cursor-pointer">
                  부품구성 (BOM) 필요
                </Label>
              </div>
              <p className="text-xs text-muted-foreground mt-1 ml-6">
                * 이 {formData.itemType === "PT" ? "부품" : "제품"}이 하위 구성품을 포함하는 경우 체크하세요
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 절곡품 전개도 섹션 - 조립 부품(품목명 선택 시) 또는 절곡 부품 */}
      {formData.itemType === "PT" && (
        (formData.partType === "ASSEMBLY" && formData.category1) || 
        formData.partType === "BENDING"
      ) && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileImage className="h-5 w-5" />
              {formData.partType === "ASSEMBLY" ? "조립품 전개도 (바라시)" : "절곡품 전개도 (바라시)"}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 입력방식 선택 */}
            <div>
              <Label>입력방식 선택</Label>
              <div className="mt-2 flex gap-4">
                <div className="flex items-center space-x-2">
                  <input
                    type="radio"
                    id="input-file"
                    name="bendingInputMethod"
                    value="file"
                    checked={bendingDiagramInputMethod === "file"}
                    onChange={(e) => setBendingDiagramInputMethod(e.target.value as "file")}
                    className="h-4 w-4"
                  />
                  <Label htmlFor="input-file" className="cursor-pointer font-normal">
                    파일 선택 (이미지 파일 업로드)
                  </Label>
                </div>
                <div className="flex items-center space-x-2">
                  <input
                    type="radio"
                    id="input-drawing"
                    name="bendingInputMethod"
                    value="drawing"
                    checked={bendingDiagramInputMethod === "drawing"}
                    onChange={(e) => setBendingDiagramInputMethod(e.target.value as "drawing")}
                    className="h-4 w-4"
                  />
                  <Label htmlFor="input-drawing" className="cursor-pointer font-normal">
                    드로잉 (직접 그리기)
                  </Label>
                </div>
              </div>
              <p className="text-xs text-muted-foreground mt-1">
                * 전개도 이미지를 파일로 업로드하거나 직접 그릴 수 있습니다
              </p>
            </div>

            {/* 파일 선택 방식 */}
            {bendingDiagramInputMethod === "file" && (
              <div>
                <Label>파일 선택</Label>
                <div className="mt-2 space-y-3">
                  <div className="flex gap-2">
                    <Input
                      type="file"
                      accept="image/*,.pdf"
                      onChange={(e) => {
                        const file = e.target.files?.[0];
                        if (file) {
                          setBendingDiagramFile(file);
                          const reader = new FileReader();
                          reader.onloadend = () => {
                            setBendingDiagram(reader.result as string);
                          };
                          reader.readAsDataURL(file);
                          toast.success("파일이 업로드되었습니다.");
                        }
                      }}
                      className="flex-1"
                    />
                  </div>
                  <p className="text-xs text-muted-foreground">
                    * 절곡품 전개도 이미지를 업로드하세요 (JPG, PNG, PDF 등)
                  </p>
                </div>
              </div>
            )}

            {/* 드로잉 방식 */}
            {bendingDiagramInputMethod === "drawing" && (
              <div>
                <Label>드로잉</Label>
                <div className="mt-2 space-y-3">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setIsDrawingCanvasOpen(true)}
                    className="w-full"
                  >
                    <Pencil className="h-4 w-4 mr-2" />
                    {bendingDiagram ? "전개도 수정하기" : "전개도 그리기"}
                  </Button>
                  <p className="text-xs text-muted-foreground">
                    * "전개도 그리기" 버튼을 클릭하여 캔버스에 직접 그릴 수 있습니다
                  </p>
                </div>
              </div>
            )}

            {/* 전개도 이미지 미리보기 */}
            {bendingDiagram && (
              <div className="p-4 border rounded-lg bg-gray-50">
                <div className="flex items-center justify-between mb-2">
                  <p className="text-sm font-medium">미리보기</p>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => {
                      setBendingDiagram("");
                      setBendingDiagramFile(null);
                      toast.success("전개도가 삭제되었습니다.");
                    }}
                  >
                    <X className="h-4 w-4 mr-1" />
                    전개도 삭제
                  </Button>
                </div>
                <img 
                  src={bendingDiagram} 
                  alt="전개도 미리보기" 
                  className="max-w-full h-auto max-h-96 mx-auto border rounded bg-white"
                />
              </div>
            )}

            {/* 그리기 캔버스 */}
            <DrawingCanvas
              open={isDrawingCanvasOpen}
              onOpenChange={setIsDrawingCanvasOpen}
              onSave={(imageData) => {
                setBendingDiagram(imageData);
                toast.success("전개도가 저장되었습니다.");
              }}
              initialImage={bendingDiagram}
            />

            {/* 전개도 상세 데이터 입력 - 절곡 부품일 때만 표시 */}
            {formData.partType === "BENDING" && (
              <div className="space-y-3">
                <div className="flex justify-between items-center">
                  <Label>전개도 상세 입력 (치수 계산)</Label>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      const currentDetails = ((formData as any).bendingDetails as BendingDetail[]) || [];
                      const lastNo = currentDetails.length > 0 ? Math.max(...currentDetails.map(d => d.no)) : 0;
                      const newDetail: BendingDetail = {
                        id: `detail-${Date.now()}`,
                        no: lastNo + 1,
                        input: 0,
                        elongation: -1,
                        calculated: 0,
                        sum: 0,
                        shaded: false,
                      };
                      setFormData({
                        ...formData,
                        bendingDetails: [...currentDetails, newDetail]
                      } as any);
                    }}
                  >
                    <Plus className="h-3 w-3 mr-1" />
                    행 추가
                  </Button>
                </div>

              {/* 상세 데이터 테이블/카드 */}
              {(formData as any).bendingDetails && (formData as any).bendingDetails.length > 0 ? (
                <BendingDetailCards
                  bendingDetails={(formData as any).bendingDetails}
                  onChange={(updatedDetails) => {
                    setFormData({
                      ...formData,
                      bendingDetails: updatedDetails
                    } as any);
                  }}
                />
              ) : (
                <div className="text-center py-8 text-sm text-muted-foreground border rounded-lg bg-gray-50">
                  전개도 상세 데이터가 없습니다. "행 추가" 버튼을 클릭하여 추가하세요.
                </div>
              )}

              <p className="text-xs text-muted-foreground">
                * 전개도의 각 구간별 치수를 입력하여 정확한 전개 길이를 계산할 수 있습니다.
              </p>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* BOM 섹션 - 조립 부품(품목명 선택 시) 또는 제품에서 needsBOM이 true일 때 */}
      {(
        formData.itemType === "FG" || 
        (formData.itemType === "PT" && formData.partType === "ASSEMBLY" && formData.category1) ||
        (formData.itemType === "PT" && formData.partType === "PURCHASED")
      ) && formData.needsBOM && (
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle>부품 구성 (BOM)</CardTitle>
              <Button 
                type="button"
                variant="outline" 
                size="sm"
                onClick={() => {
                  const newLine: BOMLine = {
                    id: `bom-${Date.now()}`,
                    childItemCode: "",
                    childItemName: "",
                    specification: "",
                    quantity: 1,
                    unit: "EA",
                    unitPrice: 0,
                    quantityFormula: "",
                    note: ""
                  };
                  setBomLines([...bomLines, newLine]);
                }}
              >
                <Plus className="h-4 w-4 mr-2" />
                BOM 품목 추가
              </Button>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            {bomLines.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-12 text-center">
                <Package className="h-16 w-16 text-muted-foreground mb-4 opacity-20" />
                <p className="text-sm text-muted-foreground mb-2">
                  아직 부품 구성이 추가되지 않았습니다
                </p>
                <p className="text-xs text-muted-foreground">
                  품목의 구성 부품, 원자재, 부자재를 추가할 수 있습니다
                </p>
              </div>
            ) : (
              <div className="space-y-3">
                {/* 모바일: 카드 형식 */}
                <div className="block lg:hidden space-y-3">
                  {bomLines.map((line, index) => {
                    // 각 라인별 검색 상태 가져오기
                    const searchState = bomSearchStates[line.id] || { searchValue: "", isOpen: false };
                    const searchValue = searchState.searchValue;
                    const searchOpen = searchState.isOpen;
                    
                    // 검색어로 필터링
                    const availableItems = itemMasters.filter(item => 
                      (item.itemType === "RM" || item.itemType === "PT" || item.itemType === "SM") &&
                      (searchValue === "" || 
                       item.itemCode.toLowerCase().includes(searchValue.toLowerCase()) ||
                       item.itemName.toLowerCase().includes(searchValue.toLowerCase()))
                    );

                    return (
                      <Card key={line.id} className="border-2">
                        <CardHeader className="pb-3">
                          <div className="flex items-center justify-between">
                            <Badge variant="outline">품목 #{index + 1}</Badge>
                            <Button
                              type="button"
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                setBomLines(bomLines.filter(l => l.id !== line.id));
                              }}
                            >
                              <Trash2 className="h-4 w-4 text-red-600" />
                            </Button>
                          </div>
                        </CardHeader>
                        <CardContent className="space-y-3 text-sm">
                          <div>
                            <Label className="text-xs mb-1.5">품목 선택</Label>
                            <div className="flex gap-2">
                              <div className="flex-1">
                                <Popover 
                                  open={searchOpen} 
                                  onOpenChange={(open) => {
                                    setBomSearchStates({
                                      ...bomSearchStates,
                                      [line.id]: { ...searchState, isOpen: open }
                                    });
                                  }}
                                >
                                  <PopoverTrigger asChild>
                                    <div className="relative">
                                      <Input
                                        placeholder="품목코드 또는 품목명 입력..."
                                        value={line.childItemCode ? `[${line.childItemCode}] ${line.childItemName}` : searchValue}
                                        onChange={(e) => {
                                          if (!line.childItemCode) {
                                            setBomSearchStates({
                                              ...bomSearchStates,
                                              [line.id]: { searchValue: e.target.value, isOpen: true }
                                            });
                                          }
                                        }}
                                        onFocus={() => {
                                          setBomSearchStates({
                                            ...bomSearchStates,
                                            [line.id]: { ...searchState, isOpen: true }
                                          });
                                        }}
                                        className="w-full"
                                        readOnly={!!line.childItemCode}
                                      />
                                      {line.childItemCode && (
                                        <div className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1">
                                          <Check className="h-4 w-4 text-green-600" />
                                          <Button
                                            type="button"
                                            variant="ghost"
                                            size="sm"
                                            className="h-6 w-6 p-0"
                                            onClick={() => {
                                              // 선택 초기화
                                              setBomLines(bomLines.map(l => 
                                                l.id === line.id ? { 
                                                  ...l, 
                                                  childItemCode: "",
                                                  childItemName: "",
                                                  specification: "",
                                                  material: "",
                                                  width: 0,
                                                  unit: "EA",
                                                  unitPrice: 0,
                                                  isBending: false,
                                                  bendingDiagram: undefined,
                                                  bendingDetails: undefined,
                                                } : l
                                              ));
                                            }}
                                          >
                                            <X className="h-3 w-3" />
                                          </Button>
                                        </div>
                                      )}
                                    </div>
                                  </PopoverTrigger>
                                  <PopoverContent className="w-[calc(100vw-2rem)] max-w-[400px] p-0" align="start">
                                    <Command>
                                      <CommandInput 
                                        placeholder="품목코드 또는 품목명 검색..." 
                                        value={searchValue}
                                        onValueChange={(value) => {
                                          setBomSearchStates({
                                            ...bomSearchStates,
                                            [line.id]: { ...searchState, searchValue: value }
                                          });
                                        }}
                                      />
                                      <CommandList>
                                        <CommandEmpty>검색 결과가 없습니다.</CommandEmpty>
                                        <CommandGroup>
                                          {availableItems.map((item) => (
                                            <CommandItem
                                              key={item.id}
                                              value={`${item.itemCode} ${item.itemName}`}
                                              onSelect={() => {
                                                // 절곡품인 경우 partType이 BENDING인지 확인
                                                const isBendingPart = (item as any).partType === "BENDING";
                                                
                                                // pricing 데이터에서 해당 품목의 단가 찾기
                                                const pricingData = pricing.find(p => p.itemCode === item.itemCode);
                                                const unitPriceFromPricing = pricingData 
                                                  ? (pricingData.salesPrice || pricingData.purchasePrice || 0)
                                                  : 0;
                                                
                                                setBomLines(bomLines.map(l => 
                                                  l.id === line.id ? { 
                                                    ...l, 
                                                    childItemCode: item.itemCode || "",
                                                    childItemName: item.itemName || "",
                                                    specification: item.specification || "",
                                                    material: (item as any).material || "",
                                                    width: (item as any).widthSum || (item as any).width || 0,
                                                    unit: item.unit || "EA",
                                                    unitPrice: unitPriceFromPricing,
                                                    // 절곡품 여부 자동 감지 및 전개도 정보 복사
                                                    isBending: isBendingPart,
                                                    bendingDiagram: isBendingPart ? (item as any).bendingDiagram : undefined,
                                                    bendingDetails: isBendingPart ? (item as any).bendingDetails : undefined,
                                                  } : l
                                                ));
                                                setBomSearchStates({
                                                  ...bomSearchStates,
                                                  [line.id]: { searchValue: "", isOpen: false }
                                                });
                                              }}
                                              className="cursor-pointer"
                                            >
                                              <div className="flex flex-col w-full">
                                                <div className="flex items-center gap-2">
                                                  <code className="text-xs bg-gray-100 px-2 py-0.5 rounded">
                                                    {item.itemCode}
                                                  </code>
                                                  <span className="text-sm">{item.itemName}</span>
                                                </div>
                                                {item.specification && (
                                                  <span className="text-xs text-muted-foreground mt-0.5">
                                                    {item.specification}
                                                  </span>
                                                )}
                                                <div className="text-xs text-muted-foreground mt-1">
                                                  {item.category1} {item.category2 && `> ${item.category2}`}
                                                </div>
                                              </div>
                                            </CommandItem>
                                          ))}
                                        </CommandGroup>
                                      </CommandList>
                                    </Command>
                                  </PopoverContent>
                                </Popover>
                              </div>
                              <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                onClick={() => {
                                  // 검색 팝오버 열기 (데스크톱과 동일)
                                  setBomSearchStates({
                                    ...bomSearchStates,
                                    [line.id]: { searchValue: "", isOpen: true }
                                  });
                                }}
                              >
                                <Search className="h-4 w-4" />
                              </Button>
                            </div>
                          </div>
                          
                          {line.specification && (
                            <div>
                              <Label className="text-xs">규격</Label>
                              <p className="mt-1 text-muted-foreground">{line.specification}</p>
                            </div>
                          )}
                          
                          <div>
                            <Label className="text-xs mb-1.5">재질</Label>
                            <Input 
                              value={line.material || ""}
                              onChange={(e) => {
                                setBomLines(bomLines.map(l => 
                                  l.id === line.id ? { ...l, material: e.target.value } : l
                                ));
                              }}
                              placeholder="재질"
                            />
                          </div>
                          
                          <div className="grid grid-cols-2 gap-3">
                            <div>
                              <Label className="text-xs mb-1.5">수량</Label>
                              <Input 
                                type="number"
                                value={line.quantity}
                                onChange={(e) => {
                                  setBomLines(bomLines.map(l => 
                                    l.id === line.id ? { ...l, quantity: Number(e.target.value) } : l
                                  ));
                                }}
                                min="0"
                                step="0.01"
                              />
                            </div>
                            <div>
                              <Label className="text-xs mb-1.5">단위</Label>
                              <div className="flex items-center h-9">
                                <Badge variant="secondary">{line.unit}</Badge>
                              </div>
                            </div>
                          </div>
                          
                          {canViewPrice && (
                            <div>
                              <Label className="text-xs mb-1.5">단가</Label>
                              <Input 
                                type="number"
                                value={line.unitPrice || 0}
                                onChange={(e) => {
                                  setBomLines(bomLines.map(l => 
                                    l.id === line.id ? { ...l, unitPrice: Number(e.target.value) } : l
                                  ));
                                }}
                                min="0"
                              />
                            </div>
                          )}
                          
                          <div>
                            <Label className="text-xs mb-1.5">비고</Label>
                            <Input 
                              value={line.note || ""}
                              onChange={(e) => {
                                setBomLines(bomLines.map(l => 
                                  l.id === line.id ? { ...l, note: e.target.value } : l
                                ));
                              }}
                              placeholder="비고"
                            />
                          </div>

                          {/* 절곡품인 경우 전개도 정보 표시 */}
                          {line.isBending && (line.bendingDiagram || line.bendingDetails) && (
                            <div className="pt-3 border-t space-y-3">
                              <Badge variant="outline" className="bg-blue-100 text-blue-700">
                                절곡품 전개도 정보
                              </Badge>
                              
                              {/* 전개도 이미지 */}
                              {line.bendingDiagram && (
                                <div>
                                  <Label className="text-xs mb-2 block">전개도 이미지</Label>
                                  <div className="border rounded-lg p-2 bg-white">
                                    <img 
                                      src={line.bendingDiagram} 
                                      alt="절곡 전개도" 
                                      className="max-w-full h-auto max-h-[200px] object-contain mx-auto"
                                    />
                                  </div>
                                </div>
                              )}
                              
                              {/* 전개도 상세 데이터 */}
                              {line.bendingDetails && line.bendingDetails.length > 0 && (
                                <div>
                                  <Label className="text-xs mb-2 block">전개도 상세 데이터</Label>
                                  <div className="border rounded-lg overflow-hidden bg-white">
                                    <Table>
                                      <TableHeader>
                                        <TableRow className="bg-gray-50">
                                          <TableHead className="text-xs h-8">No</TableHead>
                                          <TableHead className="text-xs h-8">입력</TableHead>
                                          <TableHead className="text-xs h-8">연신율</TableHead>
                                          <TableHead className="text-xs h-8">합계</TableHead>
                                        </TableRow>
                                      </TableHeader>
                                      <TableBody>
                                        {line.bendingDetails.map((detail: BendingDetail, idx: number) => (
                                          <TableRow key={detail.id} className={detail.shaded ? "bg-yellow-50" : ""}>
                                            <TableCell className="text-xs py-2">{detail.no}</TableCell>
                                            <TableCell className="text-xs py-2 text-right">{detail.input}</TableCell>
                                            <TableCell className="text-xs py-2 text-right">{detail.elongation}</TableCell>
                                            <TableCell className="text-xs py-2 text-right font-medium">{detail.sum.toFixed(2)}</TableCell>
                                          </TableRow>
                                        ))}
                                      </TableBody>
                                    </Table>
                                  </div>
                                </div>
                              )}
                            </div>
                          )}
                        </CardContent>
                      </Card>
                    );
                  })}
                </div>
                
                {/* 데스크톱: 테이블 형식 */}
                <div className="hidden lg:block overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[280px]">품목코드 / 품목명 입력</TableHead>
                      <TableHead className="w-[180px]">품목명</TableHead>
                      <TableHead className="w-[150px]">규격</TableHead>
                      <TableHead className="w-[100px]">재질</TableHead>
                      <TableHead className="w-20">수량</TableHead>
                      <TableHead className="w-16">단위</TableHead>
                      {canViewPrice && <TableHead className="w-24 text-right">단가</TableHead>}
                      <TableHead className="w-[180px]">비고</TableHead>
                      <TableHead className="w-16">삭제</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {bomLines.map((line, index) => {
                      // 각 라인별 검색 상태 가져오기
                      const searchState = bomSearchStates[line.id] || { searchValue: "", isOpen: false };
                      const searchValue = searchState.searchValue;
                      const searchOpen = searchState.isOpen;
                      
                      // 검색어로 필터링
                      const availableItems = itemMasters.filter(item => 
                        (item.itemType === "RM" || item.itemType === "PT" || item.itemType === "SM") &&
                        (searchValue === "" || 
                         item.itemCode.toLowerCase().includes(searchValue.toLowerCase()) ||
                         item.itemName.toLowerCase().includes(searchValue.toLowerCase()))
                      );

                      return (
                        <Fragment key={line.id}>
                        <TableRow>
                          <TableCell>
                            <div className="flex gap-1">
                              <div className="flex-1">
                                <Popover 
                                  open={searchOpen} 
                                  onOpenChange={(open) => {
                                    setBomSearchStates({
                                      ...bomSearchStates,
                                      [line.id]: { ...searchState, isOpen: open }
                                    });
                                  }}
                                >
                              <PopoverTrigger asChild>
                                <div className="relative">
                                  <Input
                                    placeholder="품목코드 또는 품목명 입력..."
                                    value={line.childItemCode || searchValue}
                                    onChange={(e) => {
                                      setBomSearchStates({
                                        ...bomSearchStates,
                                        [line.id]: { searchValue: e.target.value, isOpen: true }
                                      });
                                    }}
                                    onFocus={() => {
                                      setBomSearchStates({
                                        ...bomSearchStates,
                                        [line.id]: { ...searchState, isOpen: true }
                                      });
                                    }}
                                    className="w-full"
                                  />
                                  {line.childItemCode && (
                                    <div className="absolute right-2 top-1/2 -translate-y-1/2">
                                      <Check className="h-4 w-4 text-green-600" />
                                    </div>
                                  )}
                                </div>
                              </PopoverTrigger>
                              <PopoverContent className="w-[400px] p-0" align="start">
                                <Command>
                                  <CommandInput 
                                    placeholder="품목코드 또는 품목명 검색..." 
                                    value={searchValue}
                                    onValueChange={(value) => {
                                      setBomSearchStates({
                                        ...bomSearchStates,
                                        [line.id]: { ...searchState, searchValue: value }
                                      });
                                    }}
                                  />
                                  <CommandList>
                                    <CommandEmpty>검색 결과가 없습니다.</CommandEmpty>
                                    <CommandGroup>
                                      {availableItems.map((item) => (
                                        <CommandItem
                                          key={item.id}
                                          value={`${item.itemCode} ${item.itemName}`}
                                          onSelect={() => {
                                            // 절곡품인 경우 partType이 BENDING인지 확인
                                            const isBendingPart = (item as any).partType === "BENDING";
                                            
                                            // pricing 데이터에서 해당 품목의 단가 찾기
                                            const pricingData = pricing.find(p => p.itemCode === item.itemCode);
                                            const unitPriceFromPricing = pricingData 
                                              ? (pricingData.salesPrice || pricingData.purchasePrice || 0)
                                              : 0;
                                            
                                            setBomLines(bomLines.map(l => 
                                              l.id === line.id ? { 
                                                ...l, 
                                                childItemCode: item.itemCode || "",
                                                childItemName: item.itemName || "",
                                                specification: item.specification || "",
                                                material: (item as any).material || "",
                                                width: (item as any).widthSum || (item as any).width || 0,
                                                unit: item.unit || "EA",
                                                unitPrice: unitPriceFromPricing,
                                                // 절곡품 여부 자동 감지 및 전개도 정보 복사
                                                isBending: isBendingPart,
                                                bendingDiagram: isBendingPart ? (item as any).bendingDiagram : undefined,
                                                bendingDetails: isBendingPart ? (item as any).bendingDetails : undefined,
                                              } : l
                                            ));
                                            setBomSearchStates({
                                              ...bomSearchStates,
                                              [line.id]: { searchValue: "", isOpen: false }
                                            });
                                          }}
                                          className="cursor-pointer"
                                        >
                                          <div className="flex items-center justify-between w-full">
                                            <div className="flex-1">
                                              <div className="flex items-center gap-2">
                                                <code className="text-xs bg-gray-100 px-2 py-0.5 rounded">
                                                  {item.itemCode}
                                                </code>
                                                <span className="text-sm">{item.itemName}</span>
                                                {item.specification && (
                                                  <span className="text-xs text-muted-foreground">({item.specification})</span>
                                                )}
                                              </div>
                                              <div className="text-xs text-muted-foreground mt-1">
                                                {item.category1} {item.category2 && `> ${item.category2}`} {item.category3 && `> ${item.category3}`}
                                              </div>
                                            </div>
                                            <Badge variant="secondary" className="ml-2">{item.unit}</Badge>
                                          </div>
                                        </CommandItem>
                                      ))}
                                    </CommandGroup>
                                  </CommandList>
                                </Command>
                              </PopoverContent>
                                </Popover>
                              </div>
                              <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                onClick={() => {
                                  // 검색 팝오버 열기
                                  setBomSearchStates({
                                    ...bomSearchStates,
                                    [line.id]: { searchValue: "", isOpen: true }
                                  });
                                }}
                              >
                                <Search className="h-4 w-4" />
                              </Button>
                            </div>
                          </TableCell>
                          <TableCell className="text-sm">
                            {line.childItemName || "-"}
                          </TableCell>
                          <TableCell className="text-sm text-muted-foreground">
                            {line.specification || "-"}
                          </TableCell>
                          <TableCell className="text-sm">
                            <Input 
                              value={line.material || ""}
                              onChange={(e) => {
                                setBomLines(bomLines.map(l => 
                                  l.id === line.id ? { ...l, material: e.target.value } : l
                                ));
                              }}
                              placeholder="재질"
                              className="w-full text-xs"
                            />
                          </TableCell>
                        <TableCell>
                          <Input 
                            type="number"
                            value={line.quantity}
                            onChange={(e) => {
                              setBomLines(bomLines.map(l => 
                                l.id === line.id ? { ...l, quantity: Number(e.target.value) } : l
                              ));
                            }}
                            min="0"
                            step="0.01"
                            className="w-full"
                          />
                        </TableCell>
                        <TableCell>
                          <Badge variant="secondary">{line.unit}</Badge>
                        </TableCell>
                        {canViewPrice && (
                          <TableCell>
                            <Input 
                              type="number"
                              value={line.unitPrice || 0}
                              onChange={(e) => {
                                setBomLines(bomLines.map(l => 
                                  l.id === line.id ? { ...l, unitPrice: Number(e.target.value) } : l
                                ));
                              }}
                              min="0"
                              className="w-full text-right"
                            />
                          </TableCell>
                        )}
                        <TableCell>
                          <Input 
                            value={line.note || ""}
                            onChange={(e) => {
                              setBomLines(bomLines.map(l => 
                                l.id === line.id ? { ...l, note: e.target.value } : l
                              ));
                            }}
                            placeholder="비고"
                            className="w-full text-xs"
                          />
                        </TableCell>
                        <TableCell>
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setBomLines(bomLines.filter(l => l.id !== line.id));
                            }}
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </TableCell>
                      </TableRow>
                      
                      {/* 절곡품인 경우 전개도 정보 표시 */}
                      {line.isBending && (line.bendingDiagram || line.bendingDetails) && (
                        <TableRow>
                          <TableCell colSpan={canViewPrice ? 9 : 8} className="bg-blue-50 p-4">
                            <div className="space-y-3">
                              <div className="flex items-center gap-2">
                                <Badge variant="outline" className="bg-blue-100 text-blue-700">
                                  절곡품 전개도 정보
                                </Badge>
                              </div>
                              
                              {/* 전개도 이미지 */}
                              {line.bendingDiagram && (
                                <div>
                                  <Label className="text-xs mb-2 block">전개도 이미지</Label>
                                  <div className="border rounded-lg p-2 bg-white">
                                    <img 
                                      src={line.bendingDiagram} 
                                      alt="절곡 전개도" 
                                      className="max-w-full h-auto max-h-[300px] object-contain mx-auto"
                                    />
                                  </div>
                                </div>
                              )}
                              
                              {/* 전개도 상세 데이터 */}
                              {line.bendingDetails && line.bendingDetails.length > 0 && (
                                <div>
                                  <Label className="text-xs mb-2 block">전개도 상세 데이터</Label>
                                  <div className="border rounded-lg overflow-hidden bg-white">
                                    <Table>
                                      <TableHeader>
                                        <TableRow className="bg-gray-50">
                                          <TableHead className="text-xs h-8">No</TableHead>
                                          <TableHead className="text-xs h-8">입력 (mm)</TableHead>
                                          <TableHead className="text-xs h-8">연신율</TableHead>
                                          <TableHead className="text-xs h-8">연신 후 (mm)</TableHead>
                                          <TableHead className="text-xs h-8">합계 (mm)</TableHead>
                                        </TableRow>
                                      </TableHeader>
                                      <TableBody>
                                        {line.bendingDetails.map((detail: BendingDetail, idx: number) => (
                                          <TableRow key={detail.id} className={detail.shaded ? "bg-yellow-50" : ""}>
                                            <TableCell className="text-xs py-2">{detail.no}</TableCell>
                                            <TableCell className="text-xs py-2 text-right">{detail.input}</TableCell>
                                            <TableCell className="text-xs py-2 text-right">{detail.elongation}</TableCell>
                                            <TableCell className="text-xs py-2 text-right">{detail.calculated.toFixed(2)}</TableCell>
                                            <TableCell className="text-xs py-2 text-right font-medium">{detail.sum.toFixed(2)}</TableCell>
                                          </TableRow>
                                        ))}
                                      </TableBody>
                                    </Table>
                                  </div>
                                </div>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      )}
                      </Fragment>
                    );
                    })}
                  </TableBody>
                </Table>
                </div>
              </div>
            )}

            {/* 재질별 폭합 세부 섹션 */}
            {bomLines.length > 0 && (() => {
              // 재질별로 그룹화하고 폭 합계 계산
              const materialWidthMap: { [key: string]: number } = {};
              
              bomLines.forEach(line => {
                if (line.material && line.width) {
                  const material = line.material;
                  const totalWidth = line.width * (line.quantity || 1);
                  
                  if (materialWidthMap[material]) {
                    materialWidthMap[material] += totalWidth;
                  } else {
                    materialWidthMap[material] = totalWidth;
                  }
                }
              });

              // 데이터가 있을 때만 표시
              if (Object.keys(materialWidthMap).length > 0) {
                return (
                  <div className="mt-6">
                    <h4 className="text-sm mb-3">재질별 폭합</h4>
                    <div className="border rounded-lg overflow-hidden">
                      <Table>
                        <TableHeader>
                          <TableRow className="bg-gray-50">
                            <TableHead className="h-10">재질</TableHead>
                            <TableHead className="h-10 text-right">폭합</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {Object.entries(materialWidthMap)
                            .sort(([a], [b]) => a.localeCompare(b))
                            .map(([material, totalWidth]) => (
                              <TableRow key={material}>
                                <TableCell className="py-2">{material}</TableCell>
                                <TableCell className="py-2 text-right">
                                  {Math.round(totalWidth)}
                                </TableCell>
                              </TableRow>
                            ))}
                        </TableBody>
                      </Table>
                    </div>
                  </div>
                );
              }
              return null;
            })()}
          </CardContent>
        </Card>
      )}

      {!formData.itemType && (
        <Alert className="bg-orange-50 border-orange-200">
          <AlertDescription className="text-orange-900">
            ⚠️ 품목 유형을 먼저 선택해주세요
          </AlertDescription>
        </Alert>
      )}

      {/* 하단 CTA 버튼 */}
      {formData.itemType && (
        <FormActions
          onSave={handleSaveItem}
          onCancel={() => resetForm()}
          saveDisabled={!formData.itemType}
        />
      )}

      {/* 그리기 캔버스 다이얼로그 */}
      {/* BOM 품목 선택 다이얼로그 */}
      <BOMItemSelectionDialog 
        open={bomDialogOpen}
        onOpenChange={setBomDialogOpen}
        onSelect={(item) => {
          if (selectedBomLineId) {
            // 절곡품인 경우 partType이 BENDING인지 확인
            const isBendingPart = (item as any).partType === "BENDING";
            
            setBomLines(bomLines.map(l => 
              l.id === selectedBomLineId ? { 
                ...l, 
                childItemCode: item.itemCode || "",
                childItemName: item.itemName || "",
                specification: item.specification || "",
                material: (item as any).material || "",
                width: (item as any).widthSum || (item as any).width || 0,
                unit: item.unit || "EA",
                unitPrice: item.purchasePrice || item.salesPrice || 0,
                // 절곡품 여부 자동 감지 및 전개도 정보 복사
                isBending: isBendingPart,
                bendingDiagram: isBendingPart ? (item as any).bendingDiagram : undefined,
                bendingDetails: isBendingPart ? (item as any).bendingDetails : undefined,
              } : l
            ));
          }
          setBomDialogOpen(false);
        }}
        itemMasters={itemMasters}
      />

      <DrawingCanvas 
        open={isDrawingCanvasOpen}
        onOpenChange={setIsDrawingCanvasOpen}
        onSave={(imageData) => {
          setDrawingImage(imageData);
          setBendingDiagram(imageData);
          setIsDrawingCanvasOpen(false);
          toast.success("도면이 저장되었습니다.");
        }}
        initialImage={drawingImage}
      />

      {/* 개별 삭제 확인 다이얼로그 */}
      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>품목 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              {itemToDelete && (
                <>
                  <span className="font-medium">{itemToDelete.itemName}</span> 품목을 삭제하시겠습니까?
                  <br />
                  <span className="text-red-600">이 작업은 되돌릴 수 없습니다.</span>
                </>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete} className="bg-red-600 hover:bg-red-700">
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 일괄 삭제 확인 다이얼로그 */}
      <AlertDialog open={isBulkDeleteDialogOpen} onOpenChange={setIsBulkDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>선택한 품목 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              선택한 {selectedItems.size}개의 품목을 삭제하시겠습니까?
              <br />
              <span className="text-red-600">이 작업은 되돌릴 수 없습니다.</span>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={confirmBulkDelete} className="bg-red-600 hover:bg-red-700">
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 전체 삭제 확인 다이얼로그 (리스트 뷰) */}
      <AlertDialog open={isDeleteAllDialogOpen} onOpenChange={setIsDeleteAllDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>전체 품목 삭제</AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div className="space-y-2">
                <p>등록된 모든 품목 ({itemMasters.length}개)과 연관된 데이터를 삭제하시겠습니까?</p>
                <div className="bg-red-50 border border-red-200 p-3 rounded-md space-y-1">
                  <p className="text-red-700 font-medium">삭제될 데이터:</p>
                  <ul className="text-red-600 text-sm list-disc list-inside">
                    <li>품목 마스터: {itemMasters.length}개</li>
                    <li>연관 단가 데이터: {pricing.filter(p => itemMasters.some(item => item.itemCode === p.itemCode)).length}개</li>
                  </ul>
                </div>
                <p className="text-red-600 font-bold">⚠️ 이 작업은 되돌릴 수 없습니다!</p>
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction 
              onClick={() => {
                confirmDeleteAll();
              }} 
              className="bg-red-600 hover:bg-red-700"
            >
              전체 삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 버전 관리 다이얼로그 */}
      <VersionControlDialog
        open={isVersionDialogOpen}
        onOpenChange={setIsVersionDialogOpen}
        screenName="품목관리"
        screenPath="/components/ItemManagement.tsx"
        onConfirm={confirmVersionUpdate}
        onCancel={cancelVersionUpdate}
      />

      {/* 품목 수정 사유 입력 다이얼로그 */}
      <Dialog open={isRevisionDialogOpen} onOpenChange={setIsRevisionDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <History className="h-5 w-5 text-orange-600" />
              품목 수정 사유
            </DialogTitle>
            <DialogDescription>
              기존 품목을 수정하는 이유를 입력해주세요. 수정 이력으로 저장됩니다.
            </DialogDescription>
          </DialogHeader>
          <div className="py-4 px-6">
            <Label>수정 사유 <span className="text-red-500">*</span></Label>
            <Textarea
              value={revisionReason}
              onChange={(e) => setRevisionReason(e.target.value)}
              placeholder="예: 단가 변경, 규격 수정, BOM 구성 변경 등"
              rows={4}
              className="mt-2"
            />
          </div>
          <div className="flex justify-end gap-2">
            <Button 
              variant="outline" 
              onClick={() => {
                setIsRevisionDialogOpen(false);
                setRevisionReason("");
                setPendingUpdates(null);
              }}
            >
              취소
            </Button>
            <Button 
              onClick={handleSaveWithRevision} 
              disabled={!revisionReason.trim()}
            >
              <Save className="h-4 w-4 mr-2" />
              수정 사유 저장
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* BOM 절곡품 전개도 수정 다이얼로그 */}
      <Dialog open={editBendingDialog.isOpen} onOpenChange={(open) => {
        if (!open) {
          setEditBendingDialog({ isOpen: false, bomLine: null, parentItemCode: "" });
          setTempBendingData({ bendingDetails: [] });
        }
      }}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileImage className="h-5 w-5 text-purple-600" />
              절곡품 전개도 및 연신률 수정
            </DialogTitle>
            <DialogDescription>
              {editBendingDialog.bomLine?.childItemName}의 전개도 이미지와 연신률 정보를 수정합니다.
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-6 py-4">
            {/* 전개도 이미지 업로드 */}
            <div className="space-y-2">
              <Label>전개도 이미지</Label>
              {tempBendingData.bendingDiagram && (
                <div className="relative inline-block">
                  <img 
                    src={tempBendingData.bendingDiagram} 
                    alt="전개도" 
                    className="max-w-full border rounded"
                  />
                  <Button
                    variant="destructive"
                    size="sm"
                    className="absolute top-2 right-2"
                    onClick={() => setTempBendingData({ ...tempBendingData, bendingDiagram: undefined })}
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              )}
              <Input
                type="file"
                accept="image/*"
                onChange={(e) => {
                  const file = e.target.files?.[0];
                  if (file) {
                    const reader = new FileReader();
                    reader.onload = () => {
                      setTempBendingData({
                        ...tempBendingData,
                        bendingDiagram: reader.result as string
                      });
                    };
                    reader.readAsDataURL(file);
                  }
                }}
              />
            </div>

            {/* 연신률 데이터 입력 */}
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <Label>연신률 상세 정보</Label>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    const newDetail: BendingDetail = {
                      id: `bending-detail-${Date.now()}`,
                      no: tempBendingData.bendingDetails.length + 1,
                      input: 0,
                      elongation: -1,
                      calculated: 0,
                      sum: 0,
                      shaded: false,
                    };
                    setTempBendingData({
                      ...tempBendingData,
                      bendingDetails: [...tempBendingData.bendingDetails, newDetail]
                    });
                  }}
                >
                  <Plus className="h-4 w-4 mr-1" />
                  행 추가
                </Button>
              </div>
              
              {tempBendingData.bendingDetails.length > 0 && (
                <div className="border rounded-lg overflow-hidden">
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-purple-100">
                        <TableHead className="w-12">No</TableHead>
                        <TableHead>입력</TableHead>
                        <TableHead>연신율</TableHead>
                        <TableHead>계산 후</TableHead>
                        <TableHead>합계</TableHead>
                        <TableHead>A각</TableHead>
                        <TableHead>음영</TableHead>
                        <TableHead className="w-20">순서</TableHead>
                        <TableHead className="w-16">삭제</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {tempBendingData.bendingDetails.map((detail, idx) => (
                        <TableRow key={detail.id} className={detail.shaded ? 'bg-gray-100' : ''}>
                          <TableCell>{detail.no}</TableCell>
                          <TableCell>
                            <Input
                              type="number"
                              value={detail.input}
                              onChange={(e) => {
                                const newDetails = [...tempBendingData.bendingDetails];
                                const inputVal = parseFloat(e.target.value) || 0;
                                newDetails[idx].input = inputVal;
                                newDetails[idx].calculated = inputVal + detail.elongation;
                                // 합계 계산 (이전 합계 + 계산 후)
                                newDetails[idx].sum = idx === 0 ? newDetails[idx].calculated : newDetails[idx - 1].sum + newDetails[idx].calculated;
                                setTempBendingData({ ...tempBendingData, bendingDetails: newDetails });
                              }}
                              className="w-24"
                            />
                          </TableCell>
                          <TableCell>
                            <Input
                              type="number"
                              value={detail.elongation}
                              onChange={(e) => {
                                const newDetails = [...tempBendingData.bendingDetails];
                                const elongationVal = parseFloat(e.target.value) || 0;
                                newDetails[idx].elongation = elongationVal;
                                newDetails[idx].calculated = detail.input + elongationVal;
                                // 합계 재계산
                                newDetails[idx].sum = idx === 0 ? newDetails[idx].calculated : newDetails[idx - 1].sum + newDetails[idx].calculated;
                                setTempBendingData({ ...tempBendingData, bendingDetails: newDetails });
                              }}
                              className="w-24"
                            />
                          </TableCell>
                          <TableCell className="font-medium">{detail.calculated.toFixed(2)}</TableCell>
                          <TableCell className="font-bold">{detail.sum.toFixed(2)}</TableCell>
                          <TableCell>
                            <Input
                              type="number"
                              value={detail.aAngle || ''}
                              onChange={(e) => {
                                const newDetails = [...tempBendingData.bendingDetails];
                                newDetails[idx].aAngle = parseFloat(e.target.value) || undefined;
                                setTempBendingData({ ...tempBendingData, bendingDetails: newDetails });
                              }}
                              placeholder="-"
                              className="w-20"
                            />
                          </TableCell>
                          <TableCell>
                            <Checkbox
                              checked={detail.shaded}
                              onCheckedChange={(checked) => {
                                const newDetails = [...tempBendingData.bendingDetails];
                                newDetails[idx].shaded = checked as boolean;
                                setTempBendingData({ ...tempBendingData, bendingDetails: newDetails });
                              }}
                            />
                          </TableCell>
                          <TableCell>
                            <div className="flex gap-1">
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-6 w-6 p-0"
                                disabled={idx === 0}
                                onClick={() => {
                                  if (idx === 0) return;
                                  const newDetails = [...tempBendingData.bendingDetails];
                                  // 현재 항목과 이전 항목을 교체
                                  [newDetails[idx - 1], newDetails[idx]] = [newDetails[idx], newDetails[idx - 1]];
                                  // No 재정렬 및 합계 재계산
                                  newDetails.forEach((d, i) => {
                                    d.no = i + 1;
                                    d.sum = i === 0 ? d.calculated : newDetails[i - 1].sum + d.calculated;
                                  });
                                  setTempBendingData({ ...tempBendingData, bendingDetails: newDetails });
                                }}
                              >
                                <ArrowUp className="h-3 w-3" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-6 w-6 p-0"
                                disabled={idx === tempBendingData.bendingDetails.length - 1}
                                onClick={() => {
                                  if (idx === tempBendingData.bendingDetails.length - 1) return;
                                  const newDetails = [...tempBendingData.bendingDetails];
                                  // 현재 항목과 다음 항목을 교체
                                  [newDetails[idx], newDetails[idx + 1]] = [newDetails[idx + 1], newDetails[idx]];
                                  // No 재정렬 및 합계 재계산
                                  newDetails.forEach((d, i) => {
                                    d.no = i + 1;
                                    d.sum = i === 0 ? d.calculated : newDetails[i - 1].sum + d.calculated;
                                  });
                                  setTempBendingData({ ...tempBendingData, bendingDetails: newDetails });
                                }}
                              >
                                <ArrowDown className="h-3 w-3" />
                              </Button>
                            </div>
                          </TableCell>
                          <TableCell>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                const newDetails = tempBendingData.bendingDetails.filter((_, i) => i !== idx);
                                // No 재정렬 및 합계 재계산
                                newDetails.forEach((d, i) => {
                                  d.no = i + 1;
                                  d.sum = i === 0 ? d.calculated : newDetails[i - 1].sum + d.calculated;
                                });
                                setTempBendingData({ ...tempBendingData, bendingDetails: newDetails });
                              }}
                            >
                              <Trash2 className="h-4 w-4 text-red-600" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </div>
          </div>

          <div className="flex justify-end gap-2">
            <Button 
              variant="outline" 
              onClick={() => {
                setEditBendingDialog({ isOpen: false, bomLine: null, parentItemCode: "" });
                setTempBendingData({ bendingDetails: [] });
              }}
            >
              취소
            </Button>
            <Button 
              onClick={() => {
                // 부모 품목 찾기
                const parentItem = itemMasters.find(item => item.itemCode === editBendingDialog.parentItemCode);
                if (!parentItem || !parentItem.bom) return;

                // BOM 라인 업데이트
                const updatedBom = parentItem.bom.map(line => 
                  line.id === editBendingDialog.bomLine?.id 
                    ? {
                        ...line,
                        bendingDiagram: tempBendingData.bendingDiagram,
                        bendingDetails: tempBendingData.bendingDetails
                      }
                    : line
                );

                // 부모 품목 업데이트
                updateItemMaster(editBendingDialog.parentItemCode, {
                  ...parentItem,
                  bom: updatedBom
                });

                toast.success("절곡품 전개도 정보가 수정되었습니다.");
                
                // 뷰 새로고침
                if (selectedItem && selectedItem.itemCode === editBendingDialog.parentItemCode) {
                  setSelectedItem({ ...parentItem, bom: updatedBom });
                }

                setEditBendingDialog({ isOpen: false, bomLine: null, parentItemCode: "" });
                setTempBendingData({ bendingDetails: [] });
              }}
            >
              <Save className="h-4 w-4 mr-2" />
              저장
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 수정 이력 다이얼로그 */}
      <Dialog open={isRevisionHistoryOpen} onOpenChange={setIsRevisionHistoryOpen}>
        <DialogContent className="max-w-5xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <History className="w-5 h-5 text-orange-600" />
              품목 수정 이력
            </DialogTitle>
            <DialogDescription>
              총 <span className="font-semibold text-orange-600">{selectedItem?.currentRevision || 0}회</span> 수정되었습니다
            </DialogDescription>
          </DialogHeader>
          
          {selectedItem && (
            <div className="space-y-4">
              {/* 현재 버전 */}
              <Card className="border-2 border-blue-500 bg-blue-50/50">
                <CardContent className="pt-6">
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <Badge variant="default" className="bg-blue-600 mb-2">
                        <Check className="w-3 h-3 mr-1" />
                        현재 버전 (V{selectedItem.currentRevision || 0})
                      </Badge>
                      <div className="text-sm text-muted-foreground">
                        📅 {selectedItem.createdAt}
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="text-2xl font-bold text-blue-600">
                        {selectedItem.itemCode}
                      </div>
                      <div className="text-sm text-muted-foreground">{selectedItem.itemName}</div>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div><strong className="text-muted-foreground">품목유형:</strong> {
                      selectedItem.itemType === "FG" ? "제품" :
                      selectedItem.itemType === "PT" ? "부품" :
                      selectedItem.itemType === "SM" ? "부자재" :
                      selectedItem.itemType === "RM" ? "원자재" :
                      selectedItem.itemType === "CS" ? "소모품" : selectedItem.itemType
                    }</div>
                    <div><strong className="text-muted-foreground">규격:</strong> {selectedItem.specification || "-"}</div>
                  </div>
                </CardContent>
              </Card>

              {/* 수정 이력 */}
              {selectedItem.revisions && selectedItem.revisions.length > 0 ? (
                <>
                  <div className="border-t pt-6">
                    <h4 className="font-semibold text-sm text-muted-foreground flex items-center gap-2 mb-4">
                      <History className="w-4 h-4" />
                      이전 버전 기록 ({selectedItem.revisions.length}건)
                    </h4>
                    <div className="space-y-4">
                      {[...selectedItem.revisions].reverse().map((revision: any) => (
                        <Card key={revision.revisionNumber} className="bg-gray-50/50">
                          <CardContent className="pt-6">
                            <div className="flex items-start justify-between mb-4">
                              <div className="flex-1">
                                <div className="flex items-center gap-2 mb-2">
                                  <Badge variant="outline" className="bg-white">
                                    V{revision.revisionNumber - 1} → V{revision.revisionNumber}
                                  </Badge>
                                  <Badge variant="secondary" className="bg-orange-100 text-orange-700">
                                    {revision.revisionNumber}차 수정
                                  </Badge>
                                </div>
                                <div className="text-sm text-muted-foreground mb-2">
                                  📅 {revision.revisionDate} | 👤 {revision.revisionBy}
                                </div>
                                {revision.revisionReason && (
                                  <div className="bg-white p-3 rounded-md border text-sm mt-2">
                                    <div className="flex items-start gap-2">
                                      <span className="font-semibold text-orange-600">💬 수정 사유:</span>
                                      <span className="flex-1">{revision.revisionReason}</span>
                                    </div>
                                  </div>
                                )}
                              </div>
                              <div className="text-right ml-4">
                                <div className="text-xl font-semibold">
                                  {revision.previousData.itemCode || "-"}
                                </div>
                                <div className="text-sm text-muted-foreground">
                                  {revision.previousData.itemName || "-"}
                                </div>
                              </div>
                            </div>
                            <div className="grid grid-cols-2 gap-4 text-sm pt-3 border-t">
                              <div><strong className="text-muted-foreground">품목유형:</strong> {
                                revision.previousData.itemType === "FG" ? "제품" :
                                revision.previousData.itemType === "PT" ? "부품" :
                                revision.previousData.itemType === "SM" ? "부자재" :
                                revision.previousData.itemType === "RM" ? "원자재" :
                                revision.previousData.itemType === "CS" ? "소모품" : revision.previousData.itemType
                              }</div>
                              <div><strong className="text-muted-foreground">규격:</strong> {revision.previousData.specification || "-"}</div>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  </div>
                </>
              ) : (
                <div className="text-center py-8 text-muted-foreground">
                  <History className="w-12 h-12 mx-auto mb-3 opacity-20" />
                  <p>수정 이력이 없습니다</p>
                  <p className="text-sm mt-1">최초 작성된 품목입니다</p>
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}

export default ItemManagement;









