import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { toast } from 'sonner@2.0.3';
import { generateCompleteSampleQuoteData } from '../../utils/sampleQuoteData_Complete';
import { addProductBoms } from '../../utils/addProductBoms';

// ===== 검색 시스템 메타데이터 =====
/**
 * 시스템 전체에서 검색 가능한 필드 정의
 * 성능 최적화를 위해 핵심 필드로 제한
 */
export const SEARCHABLE_FIELDS = {
  quote: ['quoteNumber', 'clientName', 'managerName'], // 견적번호, 발주처, 담당자
  item: ['itemName'], // 제품명
  site: ['code', 'name'], // 현장코드, 현장명
  salesOrder: ['orderNumber', 'customerName', 'projectName'], // 수주번호, 고객사, 프로젝트명
} as const;

// ===== 타입 정의 =====

// 출하 계획 (분할 출고)
export interface ShippingSchedule {
  id: string;
  scheduleNumber: number; // 1차, 2차, 3차
  scheduledDate: string; // 출하 예정일
  quantity: number; // 출하 수량
  remainingQuantity: number; // 출하 후 잔량 (자동 계산)
  shippingAddress?: string; // 배송지
  receiverName?: string; // 수령인
  receiverPhone?: string; // 수령인 연락처
  status: 'scheduled' | 'ready' | 'shipped' | 'completed'; // 예정 | 준비완료 | 출고완료 | 인도완료
  shippingOrderId?: string; // 연결된 출고지시서 ID
  actualShippingDate?: string; // 실제 출고일
  note?: string; // 특이사항
}

// 출고 지시서
export interface ShippingOrder {
  id: string;
  shippingNumber: string; // 출고 번호 (예: KD-OT-251020-01)
  salesOrderId: string; // 참조 수주 번호
  salesOrderNumber: string; // 수주 번호 (표시용)
  scheduleNumber: number; // 몇 차 출고인지 (1차, 2차, 3차)
  customerName: string; // 고객명
  projectName: string; // 프로젝트명
  shippingDate: string; // 출고일
  items: ShippingOrderItem[]; // 출고 품목 (로트 정보 포함)
  shippingAddress: string; // 배송지
  receiverName: string; // 수령인
  receiverPhone: string; // 수령인 연락처
  status: 'prepared' | 'shipped' | 'delivered'; // 준비완료 | 출고완료 | 인도완료
  createdAt: string;
  note?: string;
}

// 출고 품목
export interface ShippingOrderItem {
  id: string;
  itemCode: string;
  itemName: string;
  quantity: number;
  unit: string;
  lotNumber: string; // 로트 번호
  lotProductionDate?: string; // 로트 생산일
}

// 수주 수정 이력
export interface OrderRevision {
  revisionNumber: number;
  revisionDate: string;
  revisionBy: string;
  revisionReason?: string;
  changedFields: string[];
  previousData: any;
}

// 문서 발송 이력
export interface DocumentSendHistory {
  id: string;
  documentType: 'contract' | 'specification'; // 수주계약서 | 거래명세표
  sentDate: string;
  sentBy: string;
  sentTo: string; // 받는 사람
  sentMethod: 'email' | 'fax' | 'kakao'; // 발송 방법
  status: 'sent' | 'confirmed' | 'failed';
  note?: string;
}

// 견적서 발송 이력
export interface QuoteSendHistory {
  id: string;
  sentDate: string;
  sentBy: string;
  sentTo: string; // 받는 사람 (이름 또는 회사명)
  recipientEmail?: string; // 받는 사람 이메일
  recipientPhone?: string; // 받는 사람 연락처
  sentMethod: 'email' | 'fax' | 'kakao' | 'download' | 'print'; // 발송 방법
  status: 'sent' | 'confirmed' | 'failed';
  note?: string;
}

// 분할 로트 (출고 로트)
export interface ShippingLot {
  id: string;
  lotNumber: string; // 로트 번호 (예: KD-OT-251020-01-1)
  scheduleNumber: number; // 1차, 2차, 3차
  divisionType: 'location' | 'floor' | 'material'; // 개소별 | 층별 | 자재별
  scheduledDate: string; // 출고 예정일
  items: ShippingLotItem[]; // 분할 품목
  shippingAddress?: string;
  receiverName?: string;
  receiverPhone?: string;
  status: 'scheduled' | 'production' | 'ready' | 'shipped' | 'completed';
  productionOrderId?: string; // 연결된 생산지시 ID
  actualShippingDate?: string;
  note?: string;
}

// 분할 로트 품목
export interface ShippingLotItem {
  id: string;
  itemCode: string;
  itemName: string;
  specification?: string; // 개소명, 층수 등
  plannedQuantity: number; // 계획 수량
  remainingQuantity: number; // 잔여 수량
  unit: string;
  unitPrice: number;
  totalPrice: number;
}

// 판매 관련
export interface SalesOrder {
  id: string;
  orderNumber: string; // 수주 번호 (로트 번호)
  quoteId?: string; // 연결된 견적 ID
  quoteNumber?: string; // 견적 번호 (표시용)
  customerName: string;
  customerCode?: string;
  projectName: string;
  siteId?: string; // 연결된 현장 ID
  siteName?: string; // 현장명
  orderDate: string; // 수주 등록일
  deliveryDate: string; // 최종 납품 예정일
  
  // 금액 정보
  originalAmount: number; // 원 금액
  discountRate: number; // 할인율 (%)
  discountAmount: number; // 할인 금액
  totalAmount: number; // 최종 금액 (할인 반영)
  
  // 수량 정보
  totalQuantity: number;
  shippedQuantity: number;
  remainingQuantity: number;
  
  // 수신처 정보
  shippingAddress: string; // 배송지 주소
  shippingAddressDetail?: string; // 상세 주소
  receiverName: string; // 수령인
  receiverPhone: string; // 수령인 연락처
  shippingMethod: 'direct' | 'cargo' | 'express'; // 직송 | 화물 | 택배
  
  // 상태 관리
  status: 'registered' | 'contract_completed' | 'production_ordered' | 'shipping' | 'completed' | 'cancelled';
  // registered: 수주등록, contract_completed: 수주계약완료, production_ordered: 생산지시완료
  
  // 회계 정보
  depositStatus: 'pending' | 'partial' | 'completed'; // 입금 상태
  depositAmount: number; // 입금액
  taxInvoiceStatus: 'not_issued' | 'issued' | 'completed'; // 세금계산서 상태
  taxInvoiceNumber?: string; // 세금계산서 번호
  
  // 담당자 정보
  registeredBy: string; // 수주 등록자
  manager: string; // 담당 영업
  accountingManager?: string; // 회계 담당자
  
  // 품목 및 분할 정보
  items: SalesOrderItem[];
  shippingLots?: ShippingLot[]; // 분할 로트
  hasMultipleShipping: boolean; // 분할 출하 여부
  divisionCount: number; // 분할 차수 (0: 일괄, 1이상: 분할)
  
  // 문서 관리
  documentSendHistory?: DocumentSendHistory[]; // 문서 발송 이력
  
  // 이력 관리
  revisions?: OrderRevision[]; // 수정 이력
  currentRevision: number;
  
  // 기타
  createdAt: string;
  updatedAt: string;
  note?: string;
  memo?: string;
}

export interface SalesOrderItem {
  id: string;
  itemCode: string;
  itemName: string;
  specification?: string; // 개소, 층, 사이즈 등
  quantity: number;
  shippedQuantity: number; // 출고된 수량
  remainingQuantity: number; // 잔여 수량
  unit: string;
  unitPrice: number;
  totalPrice: number;
}

// 견적 품목 행
export interface QuoteCalculationRow {
  id: string;
  distributionType: string;
  width: string;
  thickness: string;
  result: string;
  imageUrl: string;
  quantity: number;
  notes: string;
}

// 견적 수정 이력
export interface QuoteRevision {
  revisionNumber: number; // 수정 차수 (1차, 2차, 3차...)
  revisionDate: string; // 수정일
  revisionBy: string; // 수정자
  revisionReason?: string; // 수정 사유
  previousData: Quote; // 이전 버전의 전체 데이터
}

// 견적 자동 산출 내역
export interface CalculationHistory {
  id: string;
  createdAt: string; // 생성일시
  productId: string; // 제품 ID
  productName: string; // 제품명
  productCode: string; // 제품 코드
  category: string; // 제품 카테고리
  w0: number; // 오픈사이즈 W0
  h0: number; // 오픈사이즈 H0
  guideRailInstallType: string; // 가이드레일 설치 유형
  power: string; // 모터 전원
  controller: string; // 연동제어기
  quantity: number; // 수량
  edgeWingSize?: number; // 마구리 날개치수
  inspectionFee?: number; // 검사비
  calculationResults: any; // 산출 결과 (FormulaCalculationResults의 결과)
  totalAmount: number; // 총 금액
  note?: string; // 비고
}

// BOM 계산 결과 행
export interface BOMCalculationRow {
  id: string;
  itemCode: string;
  itemName: string;
  baseQuantity: number;
  calculatedQuantity: number;
  unit: string;
  unitPrice: number;
  totalPrice: number;
  formula: string;
  note?: string;
  deliveryDate?: string;
}

export interface Quote {
  id: string;
  quoteNumber: string;
  customerName: string;
  projectName: string;
  quoteDate: string;
  validUntil: string;
  totalAmount: number;
  status: 'draft' | 'sent' | 'approved' | 'rejected' | 'converted' | 'finalized';
  
  // 수정 이력 관리
  revisions?: QuoteRevision[]; // 수정 이력
  currentRevision: number; // 현재 차수 (0 = 최초, 1 = 1차 수정...)
  isFinal: boolean; // 최종 확정 여부
  finalizedDate?: string; // 최종 확정일
  finalizedBy?: string; // 최종 확정자
  
  // 발송 이력 관리
  sendHistory?: QuoteSendHistory[]; // 견적서 발송 이력
  
  // 상세 정보 (QuoteData 호환)
  registrationDate?: string;
  receiptDate?: string;
  author?: string;
  site?: string;
  siteId?: string; // 현장 ID
  siteCode?: string; // 현장 코드
  memo?: string;
  clientContact?: string;
  contactPhone?: string;
  completionDate?: string;
  modelSelection?: string;
  floors?: string;
  code?: string;
  powderType?: string;
  installType?: string;
  installLocation?: string;
  openSizeWidth?: string;
  openSizeHeight?: string;
  selectedProducts?: string[];
  calculationRows?: QuoteCalculationRow[];
  createdAt?: string;
  type?: string;
  productCode?: string;
  quantity?: number;
  amount?: number;
  client?: string;
  manager?: string;
  contact?: string;
  remarks?: string;
  responseMethod?: string;
  commitment?: string;
  notes?: string;
  
  // 제품 선택 및 BOM 관련
  productCategory?: 'SCREEN' | 'STEEL';
  selectedProductId?: string;
  bomCalculations?: BOMCalculationRow[];
  
  // 자동 산출 설정 (수정 시 복원용)
  autoCalculationSettings?: {
    productId?: string;
    productName?: string;
    productCategory?: string;
    openSizeWidth?: number;
    openSizeHeight?: number;
    guideRailInstallType?: string;
    motorPower?: string;
    controller?: string;
    quantity?: number;
    edgeWingSize?: number;
    inspectionFee?: number;
  };
}

// 생산 관련
export interface ProductionOrder {
  id: string;
  orderNumber: string;
  productName: string;
  quantity: number;
  startDate: string;
  dueDate: string;
  status: 'scheduled' | 'in-progress' | 'completed' | 'delayed' | 'on-hold';
  completedQuantity: number;
  defectQuantity: number;
}

// 품질 관련
export interface QualityInspection {
  id: string;
  inspectionNumber: string;
  inspectionType: 'incoming' | 'process' | 'final';
  itemName: string;
  quantity: number;
  passQuantity: number;
  failQuantity: number;
  inspectionDate: string;
  inspector: string;
  result: 'pass' | 'fail' | 'pending';
}

// 재고 관련
export interface InventoryItem {
  id: string;
  itemCode: string;
  itemName: string;
  itemType: 'RM' | 'PT' | 'FG' | 'BENDING';
  currentStock: number;
  safetyStock: number;
  unit: string;
  location: string;
  lastUpdated: string;
}

// 구매 관련
export interface PurchaseOrder {
  id: string;
  orderNumber: string;
  supplierName: string;
  orderDate: string;
  deliveryDate: string;
  totalAmount: number;
  status: 'ordered' | 'partial' | 'received' | 'cancelled';
}

// 인사 관련
export interface Employee {
  id: string;
  employeeNumber: string;
  name: string;
  department: string;
  position: string;
  status: 'active' | 'leave' | 'resigned';
  hireDate: string;
}

// 시스템 사용자 관리
export type UserRole = 'CEO' | 'ProductionManager' | 'Worker' | 'SystemAdmin' | 'Sales';

export interface User {
  id: string;
  username: string; // 로그인 ID
  email: string;
  password: string; // 실제로는 해시화되어야 함
  name: string;
  role: UserRole;
  companyName: string;
  position?: string;
  phone?: string;
  businessNumber?: string;
  industry?: string;
  companySize?: string;
  isActive: boolean;
  createdAt: string;
  lastLogin?: string;
}

export interface Attendance {
  id: string;
  employeeId: string;
  date: string;
  checkIn: string;
  checkOut: string;
  status: 'present' | 'absent' | 'late' | 'leave';
}

// 결재 관련
export interface Approval {
  id: string;
  documentNumber: string;
  documentType: string;
  title: string;
  requester: string;
  requestDate: string;
  status: 'pending' | 'approved' | 'rejected' | 'cancelled';
  approvers: string[];
}

// 차량 관련
export interface Vehicle {
  id: string;
  vehicleNumber: string;
  vehicleType: string;
  status: 'available' | 'in-use' | 'maintenance' | 'unavailable';
  driver?: string;
  lastMaintenance: string;
}

// 회계 관련
export interface AccountingTransaction {
  id: string;
  transactionDate: string;
  type: 'income' | 'expense';
  category: string;
  amount: number;
  description: string;
  status: 'pending' | 'completed';
}

// 계산식 관리 - 수정 이력
export interface FormulaRevision {
  revisionNumber: number; // 수정 차수 (1차, 2차, 3차...)
  revisionDate: string; // 수정일
  revisionBy: string; // 수정자
  revisionReason?: string; // 수정 사유
  previousData: CalculationFormula; // 이전 버전의 전체 데이터
}

// 계산식 관리 데이터
export interface CalculationFormula {
  id: string;
  formulaCode: string; // 계산식 코드 (예: FORM-001)
  formulaName: string; // 계산식명 (예: "스크린 프레임 길이")
  category: string; // 카테고리 (스크린/철재/공통)
  formula: string; // 계산식 (예: "(W + H) * 2")
  description?: string; // 설명
  variables: string[]; // 사용 변수 (예: ["W", "H"])
  unit?: string; // 결과 단위
  
  // 이력 관리
  currentRevision: number; // 현재 리비전 번호
  isFinal: boolean; // 최종 확정 여부
  revisions?: FormulaRevision[]; // 수정 이력
  finalizedDate?: string; // 확정일
  finalizedBy?: string; // 확정자
  status: 'draft' | 'active' | 'inactive' | 'finalized'; // 초안 | 활성 | 비활성 | 확정
  
  createdAt: string;
  createdBy: string;
  updatedAt?: string;
  updatedBy?: string;
}

// 추가 조건 정의
export interface AdditionalCondition {
  id: string;
  conditionSource: 'variable' | 'item'; // 조건 소스: 변수 또는 품목
  
  // 변수 기반 조건 (기존)
  variable?: string; // 변수명 (예: "K", "H1", "weight")
  minValue?: number; // 최소값
  maxValue?: number; // 최대값
  
  // 품목 기반 조건 (신규)
  itemCode?: string; // 품목 코드 (예: "MOTOR-150K")
  itemName?: string; // 품목명 (예: "모터 150K")
  
  conditionType: 'and' | 'or'; // 이전 조건과의 연결 방식
  result?: string; // 이 조건이 만족될 때의 결과값 (예: "4인치", "5인치")
  description?: string;
}

// 범위별 품목 정의 (다중 품목 지원)
export interface RangeRuleItem {
  id: string;
  itemCode: string; // 품목 코드
  itemName: string; // 품목명
  quantity: number | string; // 수량 (숫자 또는 수식)
  note?: string; // 비고
}

// 범위 규칙 정의
export interface RangeRule {
  id: string;
  minValue: number; // 최소값 (초과)
  maxValue: number; // 최대값 (이하)
  result: string | number; // 결과값 (표시용)
  
  // 결과 타입별 필드
  resultType?: 'specification' | 'item' | 'quantity' | 'value'; // 결과 타입
  specificationValue?: string; // 규격값 (예: "4인치", "Φ30")
  
  // 단일 품목 필드 (하위 호환성 - deprecated, items 배열 우선 사용)
  itemCode?: string; // 연결된 품목 코드
  itemName?: string; // 연결된 품목명
  quantity?: number | string; // 수량 (숫자 또는 수식)
  
  // 다중 품목 지원 (신규)
  items?: RangeRuleItem[]; // 범위별 품목 목록 (여러 품목 지원)
  
  numericValue?: number; // 수치값
  description?: string;
  
  // 복합 조건 (다중 조건 지원)
  additionalConditions?: AdditionalCondition[]; // 추가 조건 배열
  
  // 하위 호환성을 위한 기존 필드 (deprecated)
  hasSecondaryCondition?: boolean;
  secondaryVariable?: string;
  secondaryMinValue?: number;
  secondaryMaxValue?: number;
  secondaryConditionType?: 'and' | 'or';
}

// 수식 규칙 수정 이력
export interface FormulaRuleRevision {
  revisionNumber: number; // 수정 차수 (1차, 2차, 3차...)
  revisionDate: string; // 수정일
  revisionBy: string; // 수정자
  revisionReason?: string; // 수정 사유
  previousData: {
    ranges?: RangeRule[];
    formula?: string;
    fixedValue?: string | number;
    unit?: string;
    description?: string;
    status: 'active' | 'inactive';
  };
}

// 번호기준 규칙
export interface LotNumberRule {
  id: string;
  ruleName: string; // 번호기준 이름 (예: "견적번호 기준", "수주번호 기준")
  applyTo: ('quote' | 'salesOrder' | 'production' | 'shipping' | 'purchase')[]; // 적용 대상 (복수 선택 가능)
  prefix: string; // 접두사 (예: KD-PR)
  useDate: boolean; // 날짜 사용 여부
  dateFormat: 'YYMMDD' | 'YYYYMMDD' | 'YYMM' | 'YYYYMM'; // 날짜 형식
  sequenceDigits: number; // 순번 자릿수 (2자리: 01~99, 3자리: 001~999)
  separator: string; // 구분자 (-, _, 없음)
  example: string; // 예시 (예: KD-PR-251119-01)
  description?: string; // 설명
  isActive: boolean; // 활성화 여부
  createdAt: string;
  updatedAt?: string;
}

// 수식 규칙 (범위, 조건, 고정값 기반)
export interface FormulaRule {
  id: string;
  ruleCode: string; // 규칙 코드 (예: RULE-001)
  ruleName: string; // 규칙명 (예: "케이스판재 적용 기준")
  category: string; // 카테고리 (스크린/철재/케이스/공통)
  inputVariable: string; // 입력 변수 (예: "S", "W1")
  ruleType: 'range' | 'formula' | 'fixed'; // 범위 | 수식 | 고정값
  
  // 범위 규칙 (ruleType === 'range')
  ranges?: RangeRule[];
  
  // 수식 규칙 (ruleType === 'formula')
  formula?: string;
  
  // 고정값 (ruleType === 'fixed')
  fixedValue?: string | number;
  
  unit?: string;
  description?: string;
  status: 'active' | 'inactive';
  
  // 버전 관리
  currentRevision: number; // 현재 리비전 번호
  revisions?: FormulaRuleRevision[]; // 수정 이력
  isFinal: boolean; // 최종 확정 여부
  finalizedDate?: string; // 확정일
  finalizedBy?: string; // 확정자
  
  // 다단계 프로세스 관련
  isIntermediateRule?: boolean; // 중간 단계 규칙 여부 (다음 단계에서 사용)
  stageLevel?: number; // 단계 번호 (1, 2, 3, 4...)
  intermediateResultType?: 'specification' | 'item' | 'quantity' | 'value'; // 중간 단계 결과 타입
  childStageRuleIds?: string[]; // 연결된 하위 단계 규칙 ID 목록
  parentStageRuleId?: string; // 소속된 상위 단계 규칙 ID
  
  // 하위 호환성을 위한 기존 필드 (deprecated)
  isStage1?: boolean; // @deprecated - isIntermediateRule 사용
  stage1ResultType?: 'specification' | 'item' | 'quantity' | 'value'; // @deprecated - intermediateResultType 사용
  stage2RuleIds?: string[]; // @deprecated - childStageRuleIds 사용
  stage1RuleId?: string; // @deprecated - parentStageRuleId 사용
  
  createdAt: string;
  createdBy?: string;
  updatedAt: string;
  updatedBy?: string;
}

// 2단계 매핑 조건
export interface Stage2MappingCondition {
  id: string;
  conditionType: 'exact' | 'range' | 'contains' | 'formula'; // 조건 타입
  // exact: 정확히 일치 (예: "4인치")
  // range: 범위 (예: 1000~2000)
  // contains: 포함 (예: "샤프트" 포함)
  // formula: 수식 평가
  
  // exact 타입
  exactValue?: string;
  
  // range 타입
  minValue?: number;
  maxValue?: number;
  
  // contains 타입
  containsText?: string;
  
  // formula 타입
  formula?: string; // 예: "stage1Result > 1000 && stage1Result < 2000"
  
  // 결과
  stage2RuleId: string; // 2단계 규칙 ID
  stage2InputVariable?: string; // 2단계 규칙의 입력 변수명
  useStage1Result?: boolean; // 1단계 결과를 2단계 입력값으로 사용할지
  description?: string;
}

// 2단계 프로세스 매핑 (1단계 결과값 -> 2단계 규칙)
export interface Stage2Mapping {
  id: string;
  stage1RuleId: string; // 1단계 규칙 ID
  stage1RuleName?: string; // 1단계 규칙명 (참조용)
  mappingName: string; // 매핑 이름
  
  // 매핑 조건들
  conditions: Stage2MappingCondition[];
  
  // 기본 동작
  defaultStage2RuleId?: string; // 조건 미충족 시 기본 2단계 규칙
  
  description?: string; // 매핑 설명
  status: 'active' | 'inactive';
  createdAt: string;
  updatedAt: string;
}

// 단가 관리 - 수정 이력
export interface PriceRevision {
  revisionNumber: number; // 수정 차수 (1차, 2차, 3차...)
  revisionDate: string; // 수정일
  revisionBy: string; // 수정자
  revisionReason?: string; // 수정 사유
  previousData: PricingData; // 이전 버전의 전체 데이터
}

// 단가 관리 데이터
export interface PricingData {
  id: string;
  itemId: string; // 품목 ID
  itemCode: string; // 품목 코드
  itemName: string; // 품목명
  itemType: string; // 품목 유형
  specification?: string; // 규격
  unit: string; // 단위
  effectiveDate: string; // 적용일
  purchasePrice?: number; // 매입단가
  processingCost?: number; // 가공비
  loss?: number; // LOSS(%)
  roundingRule?: 'round' | 'ceil' | 'floor'; // 반올림 규칙
  roundingUnit?: number; // 반올림 단위 (예: 1, 10, 100, 1000)
  marginRate?: number; // 마진율 (%)
  salesPrice?: number; // 판매단가
  supplier?: string; // 공급업체
  note?: string; // 비고
  
  // 이력 관리
  currentRevision: number; // 현재 리비전 번호
  isFinal: boolean; // 최종 확정 여부
  revisions?: PriceRevision[]; // 수정 이력
  finalizedDate?: string; // 확정일
  finalizedBy?: string; // 확정자
  status: 'draft' | 'active' | 'inactive' | 'finalized'; // 초안 | 활성 | 비활성 | 확정
  
  createdAt: string;
  createdBy: string;
  updatedAt?: string;
  updatedBy?: string;
}

// 현장 관련
export interface SiteAttachment {
  id: string;
  fileName: string;
  fileSize: number;
  fileType: string;
  uploadDate: string;
  fileData?: string; // Base64 인코딩된 파일 데이터
}

export interface Site {
  id: string;
  siteCode: string; // 현장 코드 (PJ-YYYYMM-SEQ)
  siteName: string; // 표준 현장명
  keyAddress: string; // 날짜 주소
  clientCode?: string; // 거래처 코드
  clientName?: string; // 거래처명
  
  // 기본 정보
  siteCategory: '신축' | '증축' | '보강' | 'OEM' | '기타'; // 현장 분류
  contractStartDate: string; // 계약 시작일
  contractEndDate: string; // 계약 종료일
  salesManager: string; // 영업 담당자
  siteManager: string; // 현장 담당자
  
  // 운영 정보
  accumulatedOrderAmount: number; // 누적 수주액
  totalCost: number; // 총 투입 원가
  status: '수주중' | '진행중' | '일시중단' | '완료' | '취소'; // 진행 상태
  specialNotes: string; // 특이 사항
  
  // 첨부파일
  attachments: SiteAttachment[];
  
  createdAt: string;
  updatedAt: string;
}

export interface Receivable {
  id: string;
  customerName: string;
  amount: number;
  dueDate: string;
  status: 'pending' | 'overdue' | 'paid';
}

// 거래처 관리
export interface Client {
  id: string;
  code: string; // 거래처 코드
  businessNumber: string; // 사업자번호
  name: string; // 거래처명
  type: "매입" | "매출" | "매입매출"; // 거래 유형
  representative: string; // 대표자명
  address: string; // 주소
  businessType: string; // 업태
  businessCategory: string; // 종목
  phone: string; // 전화번호
  mobile: string; // 휴대전화
  fax: string; // 팩스
  email: string; // 이메일
  managerName: string; // 담당자명
  managerTel: string; // 담당자 연락처
  memo: string; // 메모
  status: "활성" | "비활성"; // 상태
  createdAt?: string;
  updatedAt?: string;
}

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

// 부품구성표(BOM, Bill of Materials) - 자재 명세서
export interface BOMLine {
  id: string;
  childItemCode: string; // 구성 품목 코드
  childItemName: string; // 구성 품목명
  quantity: number; // 기준 수량
  unit: string; // 단위
  unitPrice?: number; // 단가
  quantityFormula?: string; // 수량 계산식 (예: "W * 2", "H + 100")
  note?: string; // 비고
  // 절곡품 관련 (하위 절곡 부품용)
  isBending?: boolean;
  bendingDiagram?: string; // 전개도 이미지 URL
  bendingDetails?: BendingDetail[]; // 전개도 상세 데이터
}

// 규격 마스터 (원자재/부자재용)
export interface SpecificationMaster {
  id: string;
  specificationCode: string; // 규격 코드 (예: 1.6T x 1219 x 2438)
  itemType: 'RM' | 'SM'; // 원자재 | 부자재
  itemName?: string; // 품목명 (예: SPHC-SD, SPCC-SD) - 품목명별 규격 필터링용
  fieldCount: '1' | '2' | '3'; // 너비 입력 개수
  thickness: string; // 두께
  widthA: string; // 너비A
  widthB?: string; // 너비B
  widthC?: string; // 너비C
  length: string; // 길이
  description?: string; // 설명
  isActive: boolean; // 활성 여부
  createdAt?: string;
  updatedAt?: string;
}

// 원자재/부자재 품목명 마스터
export interface MaterialItemName {
  id: string;
  itemType: 'RM' | 'SM'; // 원자재 | 부자재
  itemName: string; // 품목명 (예: "SPHC-SD", "STS430")
  category?: string; // 분류 (예: "냉연", "열연", "스테인리스")
  description?: string; // 설명
  isActive: boolean; // 활성 여부
  createdAt: string;
  updatedAt?: string;
}

// 품목 마스터 관련
export interface ItemMaster {
  id: string;
  itemCode: string;
  itemName: string;
  itemType: 'FG' | 'PT' | 'SM' | 'RM' | 'CS'; // 제품, ���품, 부자재, 원자재, 소모품
  productCategory?: 'SCREEN' | 'STEEL'; // 제품 카테고리 (스크린/철재)
  partType?: 'ASSEMBLY' | 'BENDING' | 'PURCHASED'; // 부품 유형 (조립/절곡/구매)
  partUsage?: 'GUIDE_RAIL' | 'BOTTOM_FINISH' | 'CASE' | 'DOOR' | 'BRACKET' | 'GENERAL'; // 부품 용도
  unit: string;
  category1?: string;
  category2?: string;
  category3?: string;
  specification?: string;
  isVariableSize?: boolean;
  isActive?: boolean; // 품목 활성/비활성 (제품/부품/원자재/부자재만 사용)
  lotAbbreviation?: string; // 로트 약자 (제품만 사용)
  purchasePrice?: number;
  marginRate?: number;
  processingCost?: number;
  laborCost?: number;
  installCost?: number;
  salesPrice?: number;
  safetyStock?: number;
  leadTime?: number;
  bom?: BOMLine[]; // 부품구성표(BOM) - 자재 명세서
  bomCategories?: string[]; // 견적산출용 샘플 제품의 BOM 카테고리 (예: ['motor', 'guide-rail'])
  
  // 인정 정보
  certificationNumber?: string; // 인정번호
  certificationStartDate?: string; // 인정 유효기간 시작일
  certificationEndDate?: string; // 인정 유효기간 종료일
  specificationFile?: string; // 시방서 파일 (Base64 또는 URL)
  specificationFileName?: string; // 시방서 파일명
  certificationFile?: string; // 인정서 파일 (Base64 또는 URL)
  certificationFileName?: string; // 인정서 파일명
  note?: string; // 비고 (제품만 사용)
  
  // 조립 부품 관련 필드
  installationType?: string; // 설치 유형 (wall: 벽면형, side: 측면형, steel: 스틸, iron: 철재)
  assemblyType?: string; // 종류 (M, T, C, D, S, U 등)
  sideSpecWidth?: string; // 측면 규격 가로 (mm)
  sideSpecHeight?: string; // 측면 규격 세로 (mm)
  assemblyLength?: string; // 길이 (2438, 3000, 3500, 4000, 4300 등)
  
  // 가이드레일 관련 필드
  guideRailModelType?: string; // 가이드레일 모델 유형
  guideRailModel?: string; // 가이드레일 모델
  
  // 절곡품 관련 (부품 유형이 BENDING인 경우)
  bendingDiagram?: string; // 전개도 이미지 URL
  bendingDetails?: BendingDetail[]; // 전개도 상세 데이터
  material?: string; // 재질 (EGI 1.55T, SUS 1.2T 등)
  length?: string; // 길이/목함 (mm)
  
  // 버전 관리
  currentRevision: number; // 현재 차수 (0 = 최초, 1 = 1차 수정...)
  revisions?: ItemRevision[]; // 수정 이력
  isFinal: boolean; // 최종 확정 여부
  finalizedDate?: string; // 최종 확정일
  finalizedBy?: string; // 최종 확정자
  
  createdAt: string;
}

// 품목 수정 이력
export interface ItemRevision {
  revisionNumber: number; // 수정 차수 (1차, 2차, 3차...)
  revisionDate: string; // 수정일
  revisionBy: string; // 수정자
  revisionReason?: string; // 수정 사유
  previousData: any; // 이전 버전의 전체 데이터
}

// 검사기준관리
export interface InspectionStandard {
  id: string;
  standardNumber: string; // 검사기준 번호 (예: IS-2025-001)
  inspectionType: 'incoming' | 'process' | 'final'; // 수입검사 | 중간검사 | 제품검사
  inspectionName: string; // 검사 명칭
  itemCode?: string; // 품목 코드
  itemName?: string; // 품목명
  description?: string; // 설명
  
  // 문서 템플릿 정보
  documentTemplate: {
    logo?: string; // 회사 로고 URL
    title: string; // 문서 제목
    companyName: string; // 회사명
    companyAddress?: string; // 회사 주소
    companyPhone?: string; // 회사 연락처
    
    // 결재라인
    approvalLines: {
      id: string;
      position: string; // 직책 (작성, 검토, 승인)
      name: string; // 이름
      department?: string; // 부서
    }[];
    
    // 기본정보 필드
    basicInfoFields: {
      id: string;
      label: string; // 필드명 (품명, 규격, 납품업체 등)
      value?: string; // 기본값
      type: 'text' | 'date' | 'number';
      required: boolean;
    }[];
    
    // 검사항목 칼럼 구성
    inspectionColumns: {
      id: string;
      name: string; // 칼럼명 (NO, 검사항목, 검사기준 등)
      type: 'text' | 'number' | 'select';
      width?: string;
      options?: string[]; // select 타입일 경우 옵션
    }[];
    
    // 검사항목 데이터 (기본 템플릿)
    inspectionItems: {
      id: string;
      no: number;
      values: Record<string, any>; // 칼럼 ID를 키로 하는 값들
    }[];
    
    // 하단 정보
    notesLabel?: string; // 비고 라벨
    judgmentLabel?: string; // 판정 라벨
    judgmentOptions?: string[]; // 판정 옵션 (합격, 불합격, 조건부합격)
  };
  
  // 버전 관리
  currentRevision: number;
  revisions?: {
    revisionNumber: number;
    revisionDate: string;
    revisionBy: string;
    revisionReason?: string;
    previousData: any;
  }[];
  isFinal: boolean;
  finalizedDate?: string;
  finalizedBy?: string;
  
  status: 'active' | 'inactive'; // 사용 여부
  createdAt: string;
  updatedAt?: string;
  createdBy: string;
  updatedBy?: string;
}

// 품목 기준정보 관리 (Master Data)
export interface ItemCategory {
  id: string;
  categoryType: 'PRODUCT' | 'PART' | 'MATERIAL' | 'SUB_MATERIAL'; // 품목 구분
  category1: string; // 대분류
  category2?: string; // 중분류
  category3?: string; // 소분류
  code?: string; // 코드 (자동생성 또는 수동입력)
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

export interface ItemUnit {
  id: string;
  unitCode: string; // 단위 코드 (EA, SET, M, KG, L 등)
  unitName: string; // 단위명
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

export interface ItemMaterial {
  id: string;
  materialCode: string; // 재질 코드
  materialName: string; // 재질명 (EGI 1.55T, SUS 1.2T 등)
  materialType: 'STEEL' | 'ALUMINUM' | 'PLASTIC' | 'OTHER'; // 재질 유형
  thickness?: string; // 두께 (1.2T, 1.6T 등)
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

export interface SurfaceTreatment {
  id: string;
  treatmentCode: string; // 처리 코드
  treatmentName: string; // 처리명 (무도장, 파우더도장, 아노다이징 등)
  treatmentType: 'PAINTING' | 'COATING' | 'PLATING' | 'NONE'; // 처리 유형
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

export interface PartTypeOption {
  id: string;
  partType: 'ASSEMBLY' | 'BENDING' | 'PURCHASED'; // 부품 유형
  optionCode: string; // 옵션 코드
  optionName: string; // 옵션명
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

export interface PartUsageOption {
  id: string;
  usageCode: string; // 용도 코드
  usageName: string; // 용도명 (가이드레일, 하단마감재, 케이스 등)
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

export interface GuideRailOption {
  id: string;
  optionType: 'MODEL_TYPE' | 'MODEL' | 'CERTIFICATION' | 'SHAPE' | 'FINISH' | 'LENGTH'; // 옵션 유형
  optionCode: string; // 옵션 코드
  optionName: string; // 옵션명
  parentOption?: string; // 상위 옵션 (종속 관계)
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

// ===== 품목기준관리 계층구조 =====

// 항목 마스터 (재사용 가능한 항목 템플릿)
export interface ItemMasterField {
  id: string;
  name: string; // 항목명 (예: "품목코드", "품목명", "분류")
  fieldKey: string; // 필드 키 (예: "itemCode", "itemName", "category")
  property: ItemFieldProperty; // 속성
  properties?: ItemFieldProperty[]; // 하위 속성들 (다중 속성 지원)
  category?: string; // 카테고리 (사용 용도 구분용)
  description?: string; // 설명
  isActive: boolean; // 활성 여부
  createdAt: string;
  order?: number; // 표시 순서
  displayCondition?: FieldDisplayCondition; // 조건부 표시
  _autoGenerated?: boolean; // 자동 생성 여부 (품목기준관리에서 동기화)
}

// 항목 속성
export interface ItemFieldProperty {
  id?: string; // 속성 ID (properties 배열에서 사용)
  key?: string; // 속성 키 (properties 배열에서 사용)
  label?: string; // 속성 라벨 (properties 배열에서 사용)
  type?: 'textbox' | 'dropdown' | 'checkbox' | 'number' | 'date' | 'textarea'; // 속성 타입 (properties 배열에서 사용)
  inputType: 'textbox' | 'dropdown' | 'checkbox' | 'number' | 'date' | 'textarea' | 'section'; // 입력방식
  required: boolean; // 필수 여부
  row: number; // 행 위치
  col: number; // 열 위치
  options?: string[]; // 드롭다운 옵션 (입력방식이 dropdown일 경우)
  optionMapping?: { [key: string]: string }; // 옵션 값-표시명 매핑 (예: { "FG": "제품 (Finished Goods)" })
  defaultValue?: string; // 기본값
  placeholder?: string; // 플레이스홀더
  multiColumn?: boolean; // 다중 컬럼 사용 여부
  columnCount?: number; // 컬럼 개수
  columnNames?: string[]; // 각 컬럼의 이름
}

// 조건부 표시 설정
export interface FieldDisplayCondition {
  targetType: 'field' | 'section'; // 조건 대상 타입
  // 일반항목 조건 (여러 개 가능)
  fieldConditions?: Array<{
    fieldKey: string; // 조건이 되는 필드의 키
    expectedValue: string; // 예상되는 값
  }>;
  // 섹션 조건 (여러 개 가능)
  sectionIds?: string[]; // 표시할 섹션 ID 배열
}

// 항목 (Field)
export interface ItemField {
  id: string;
  name: string; // 항목명 (예: "품목코드", "품목명", "분류")
  fieldKey: string; // 필드 키 (예: "itemCode", "itemName", "category")
  property: ItemFieldProperty; // 속성
  category?: string[]; // 카테고리 조건 (예: ["제품", "부품"]) - 특정 카테고리에서만 표시
  displayCondition?: FieldDisplayCondition; // 조건부 표시 설정
  masterFieldId?: string; // 마스터 항목 ID (마스터에서 가져온 경우)
  referenceSectionId?: string; // 참조 섹션 ID (inputType이 'section'일 경우)
  referencePageId?: string; // 참조 페이지 ID (inputType이 'section'일 경우)
  order?: number; // 항목 순서 (우선순위)
  createdAt: string;
}

// 섹션 (Section)
export interface ItemSection {
  id: string;
  title: string; // 섹션 제목 (예: "기본정보", "BOM")
  description?: string; // 설명
  category?: string[]; // 카테고리 조건 - 특정 카테고리에서만 표시
  fields: ItemField[]; // 섹션에 포함된 항목들
  type?: 'fields' | 'bom'; // 섹션 타입 (일반 필드 또는 BOM)
  bomItems?: BOMItem[]; // BOM 타입일 경우 BOM 품목 목록
  order: number; // 섹션 순서
  isCollapsible: boolean; // 접기/펼치기 가능 여부
  isCollapsed: boolean; // 기본 접힘 상태
  createdAt: string;
}

// 페이지 (Page)
export interface ItemPage {
  id: string;
  pageName: string; // 페이지명 (예: "품목 등록")
  itemType: 'FG' | 'PT' | 'SM' | 'RM' | 'CS'; // 품목유형 (제품/부품/부자재/원자재/소모품)
  sections: ItemSection[]; // 페이지에 포함된 섹션들
  isActive: boolean; // 사용 여부
  absolutePath?: string; // 절대경로 (예: "/제품관리/제품등록")
  createdAt: string;
  updatedAt?: string;
}

// BOM 아이템 타입
export interface BOMItem {
  id: string;
  itemCode: string;
  itemName: string;
  quantity: number;
  unit: string;
  itemType?: string;
  note?: string;
  createdAt: string;
}

// 섹션 템플릿 (재사용 가능한 섹션)
export interface SectionTemplate {
  id: string;
  title: string; // 섹션 제목
  description?: string; // 설명
  category?: string[]; // 적용 가능한 카테고리
  fields: ItemField[]; // 포함된 항목들
  type?: 'fields' | 'bom'; // 섹션 타입 (일반 필드 또는 BOM)
  bomItems?: BOMItem[]; // BOM 타입일 경우 BOM 품목 목록
  isCollapsible: boolean;
  isCollapsed: boolean;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

// 카테고리 그룹 (수식 카테고리들을 묶는 분류)
export interface CategoryGroup {
  id: string;
  name: string; // 그룹명 (예: "오픈형 제품", "면적 기반 제품")
  description?: string; // 설명
  categories: string[]; // 포함된 카테고리 목록 (예: ["오픈사이즈", "제작사이즈"])
  createdAt: string;
  updatedAt?: string;
}

// ===== Context 타입 =====
interface DataContextType {
  // 판매 데이터
  salesOrders: SalesOrder[];
  quotes: Quote[];
  addSalesOrder: (order: SalesOrder) => void;
  updateSalesOrder: (id: string, updates: Partial<SalesOrder>) => void;
  deleteSalesOrder: (id: string) => void;
  addQuote: (quote: Quote) => void;
  updateQuote: (id: string, updates: Partial<Quote>) => void;
  reviseQuote: (id: string, updates: Partial<Quote>, revisionReason?: string, revisionBy?: string) => void;
  finalizeQuote: (id: string, finalizedBy?: string) => void;
  deleteQuote: (id: string) => void;
  
  // 출�� 데이터
  shippingOrders: ShippingOrder[];
  addShippingOrder: (order: ShippingOrder) => void;
  updateShippingOrder: (id: string, updates: Partial<ShippingOrder>) => void;
  
  // 생산 데이터
  productionOrders: ProductionOrder[];
  addProductionOrder: (order: ProductionOrder) => void;
  updateProductionOrder: (id: string, updates: Partial<ProductionOrder>) => void;
  
  // 품질 데이터
  qualityInspections: QualityInspection[];
  addQualityInspection: (inspection: QualityInspection) => void;
  updateQualityInspection: (id: string, updates: Partial<QualityInspection>) => void;
  
  // 재고 데이터
  inventoryItems: InventoryItem[];
  addInventoryItem: (item: InventoryItem) => void;
  updateInventoryItem: (id: string, updates: Partial<InventoryItem>) => void;
  
  // 구매 데이터
  purchaseOrders: PurchaseOrder[];
  addPurchaseOrder: (order: PurchaseOrder) => void;
  updatePurchaseOrder: (id: string, updates: Partial<PurchaseOrder>) => void;
  
  // 인사 데이터
  employees: Employee[];
  attendances: Attendance[];
  addEmployee: (employee: Employee) => void;
  updateEmployee: (id: string, updates: Partial<Employee>) => void;
  addAttendance: (attendance: Attendance) => void;
  
  // 결재 데이터
  approvals: Approval[];
  addApproval: (approval: Approval) => void;
  updateApproval: (id: string, updates: Partial<Approval>) => void;
  
  // 차량 데이터
  vehicles: Vehicle[];
  addVehicle: (vehicle: Vehicle) => void;
  updateVehicle: (id: string, updates: Partial<Vehicle>) => void;
  
  // 회계 데이터
  accountingTransactions: AccountingTransaction[];
  receivables: Receivable[];
  addAccountingTransaction: (transaction: AccountingTransaction) => void;
  addReceivable: (receivable: Receivable) => void;
  updateReceivable: (id: string, updates: Partial<Receivable>) => void;
  
  // 품목 마스터 데이터
  itemMasters: ItemMaster[];
  addItemMaster: (item: ItemMaster) => void;
  updateItemMaster: (id: string, updates: Partial<ItemMaster>) => void;
  deleteItemMaster: (id: string) => void;
  setItemMasters: (items: ItemMaster[]) => void;
  
  // 규격 마스터 데이터 (원자재/부자재)
  specificationMasters: SpecificationMaster[];
  addSpecificationMaster: (spec: SpecificationMaster) => void;
  updateSpecificationMaster: (id: string, updates: Partial<SpecificationMaster>) => void;
  deleteSpecificationMaster: (id: string) => void;
  
  // 원자재/부자재 품목명 마스터 데이터
  materialItemNames: MaterialItemName[];
  addMaterialItemName: (item: MaterialItemName) => void;
  updateMaterialItemName: (id: string, updates: Partial<MaterialItemName>) => void;
  deleteMaterialItemName: (id: string) => void;
  
  // 현장 데이터
  sites: Site[];
  addSite: (site: Site) => void;
  updateSite: (id: string, updates: Partial<Site>) => void;
  deleteSite: (id: string) => void;
  
  // 거래처 데이터
  clients: Client[];
  
  // 계산식 데이터
  formulas: CalculationFormula[];
  addClient: (client: Client) => void;
  updateClient: (id: string, updates: Partial<Client>) => void;
  deleteClient: (id: string) => void;
  
  // 계산식 관리
  addFormula: (formula: CalculationFormula) => void;
  updateFormula: (id: string, updates: Partial<CalculationFormula>) => void;
  reviseFormula: (id: string, updates: Partial<CalculationFormula>, revisionReason?: string, revisionBy?: string) => void;
  finalizeFormula: (id: string, finalizedBy?: string) => void;
  deleteFormula: (id: string) => void;
  
  // 수식 규칙 관리
  formulaRules: FormulaRule[];
  addFormulaRule: (rule: FormulaRule) => void;
  updateFormulaRule: (id: string, updates: Partial<FormulaRule>) => void;
  reviseFormulaRule: (id: string, updates: Partial<FormulaRule>, revisionReason?: string, revisionBy?: string) => void;
  finalizeFormulaRule: (id: string, finalizedBy?: string) => void;
  deleteFormulaRule: (id: string) => void;
  setFormulaRules: (rules: FormulaRule[]) => void;
  
  // 2단계 프로세스 매핑 관리
  stage2Mappings: Stage2Mapping[];
  addStage2Mapping: (mapping: Stage2Mapping) => void;
  updateStage2Mapping: (id: string, updates: Partial<Stage2Mapping>) => void;
  deleteStage2Mapping: (id: string) => void;
  getStage2MappingsByStage1Rule: (stage1RuleId: string) => Stage2Mapping[];
  
  // 단가 관리
  pricing: PricingData[];
  addPricing: (pricing: PricingData) => void;
  updatePricing: (id: string, updates: Partial<PricingData>) => void;
  revisePricing: (id: string, updates: Partial<PricingData>, revisionReason?: string, revisionBy?: string) => void;
  finalizePricing: (id: string, finalizedBy?: string) => void;
  deletePricing: (id: string) => void;
  
  // 견적 자동 산출 내역 관리
  calculationHistories: CalculationHistory[];
  addCalculationHistory: (history: CalculationHistory) => void;
  updateCalculationHistory: (id: string, updates: Partial<CalculationHistory>) => void;
  deleteCalculationHistory: (id: string) => void;
  
  // 검사기준관리
  inspectionStandards: InspectionStandard[];
  addInspectionStandard: (standard: InspectionStandard) => void;
  updateInspectionStandard: (id: string, updates: Partial<InspectionStandard>) => void;
  reviseInspectionStandard: (id: string, updates: Partial<InspectionStandard>, revisionReason?: string, revisionBy?: string) => void;
  finalizeInspectionStandard: (id: string, finalizedBy?: string) => void;
  deleteInspectionStandard: (id: string) => void;
  
  // 품목기준관리 - 마스터 항목
  itemMasterFields: ItemMasterField[];
  addItemMasterField: (field: ItemMasterField) => void;
  
  // LOT번호 규칙 관리
  lotNumberRules: LotNumberRule[];
  addLotNumberRule: (rule: LotNumberRule) => void;
  updateLotNumberRule: (id: string, updates: Partial<LotNumberRule>) => void;
  deleteLotNumberRule: (id: string) => void;
  generateLotNumber: (documentType: 'quote' | 'salesOrder' | 'production' | 'shipping' | 'purchase') => string;
  updateItemMasterField: (id: string, updates: Partial<ItemMasterField>) => void;
  deleteItemMasterField: (id: string) => void;
  
  // 품목기준관리 - 섹션 템플릿
  sectionTemplates: SectionTemplate[];
  addSectionTemplate: (template: SectionTemplate) => void;
  updateSectionTemplate: (id: string, updates: Partial<SectionTemplate>) => void;
  deleteSectionTemplate: (id: string) => void;
  
  // 카테고리 그룹 관리
  categoryGroups: CategoryGroup[];
  addCategoryGroup: (group: CategoryGroup) => void;
  updateCategoryGroup: (id: string, updates: Partial<CategoryGroup>) => void;
  deleteCategoryGroup: (id: string) => void;
  
  // 품목기준관리 계층구조
  itemPages: ItemPage[];
  addItemPage: (page: ItemPage) => void;
  updateItemPage: (id: string, updates: Partial<ItemPage>) => void;
  deleteItemPage: (id: string) => void;
  addSectionToPage: (pageId: string, section: ItemSection) => void;
  updateSection: (pageId: string, sectionId: string, updates: Partial<ItemSection>) => void;
  deleteSection: (pageId: string, sectionId: string) => void;
  reorderSections: (pageId: string, sectionIds: string[]) => void;
  addFieldToSection: (pageId: string, sectionId: string, field: ItemField) => void;
  updateField: (pageId: string, sectionId: string, fieldId: string, updates: Partial<ItemField>) => void;
  deleteField: (pageId: string, sectionId: string, fieldId: string) => void;
  reorderFields: (pageId: string, sectionId: string, fieldIds: string[]) => void;
  
  // 품목 기준정보 관리
  itemCategories: ItemCategory[];
  itemUnits: ItemUnit[];
  itemMaterials: ItemMaterial[];
  surfaceTreatments: SurfaceTreatment[];
  partTypeOptions: PartTypeOption[];
  partUsageOptions: PartUsageOption[];
  guideRailOptions: GuideRailOption[];
  
  addItemCategory: (category: ItemCategory) => void;
  updateItemCategory: (id: string, updates: Partial<ItemCategory>) => void;
  deleteItemCategory: (id: string) => void;
  
  addItemUnit: (unit: ItemUnit) => void;
  updateItemUnit: (id: string, updates: Partial<ItemUnit>) => void;
  deleteItemUnit: (id: string) => void;
  
  addItemMaterial: (material: ItemMaterial) => void;
  updateItemMaterial: (id: string, updates: Partial<ItemMaterial>) => void;
  deleteItemMaterial: (id: string) => void;
  
  addSurfaceTreatment: (treatment: SurfaceTreatment) => void;
  updateSurfaceTreatment: (id: string, updates: Partial<SurfaceTreatment>) => void;
  deleteSurfaceTreatment: (id: string) => void;
  
  addPartTypeOption: (option: PartTypeOption) => void;
  updatePartTypeOption: (id: string, updates: Partial<PartTypeOption>) => void;
  deletePartTypeOption: (id: string) => void;
  
  addPartUsageOption: (option: PartUsageOption) => void;
  updatePartUsageOption: (id: string, updates: Partial<PartUsageOption>) => void;
  deletePartUsageOption: (id: string) => void;
  
  addGuideRailOption: (option: GuideRailOption) => void;
  updateGuideRailOption: (id: string, updates: Partial<GuideRailOption>) => void;
  deleteGuideRailOption: (id: string) => void;
  
  // 사용자 관리
  users: User[];
  currentUser: User | null; // 현재 로그인한 사용자
  setCurrentUser: (user: User | null) => void;
  addUser: (user: User) => void;
  updateUser: (id: string, updates: Partial<User>) => void;
  deleteUser: (id: string) => void;
  getUserByUsername: (username: string) => User | undefined;
  
  // 전체 데이터 초기화
  resetAllData: () => void;
  
  // 샘플 데이터 생성
  generateSampleQuoteData: () => void;
}

// ===== 초기 Mock 데이터 =====
const initialSalesOrders: SalesOrder[] = [
  {
    id: 'SO-001',
    orderNumber: 'KD-PR-25001',
    customerName: '(주)한국건설',
    projectName: '서울 오피스빌딩',
    orderDate: '2025-01-15',
    deliveryDate: '2025-11-10', // 최종 납기일 (3차 출하일)
    totalAmount: 45000000,
    totalQuantity: 100,
    shippedQuantity: 40,
    remainingQuantity: 60,
    status: 'shipping',
    hasMultipleShipping: true,
    items: [
      { id: '1', itemName: '셔터 세트', quantity: 100, unitPrice: 450000, totalPrice: 45000000 }
    ],
    shippingSchedules: [
      {
        id: 'SS-001-1',
        scheduleNumber: 1,
        scheduledDate: '2025-10-20',
        quantity: 40,
        remainingQuantity: 60,
        shippingAddress: '서울시 강남구 테헤란로 123',
        receiverName: '김담당',
        receiverPhone: '010-1234-5678',
        status: 'shipped',
        shippingOrderId: 'SH-001',
        actualShippingDate: '2025-10-20',
        note: '1차 출고 - 본관'
      },
      {
        id: 'SS-001-2',
        scheduleNumber: 2,
        scheduledDate: '2025-10-30',
        quantity: 30,
        remainingQuantity: 30,
        shippingAddress: '서울시 강남구 테헤란로 456',
        receiverName: '이담당',
        receiverPhone: '010-2345-6789',
        status: 'ready',
        note: '2차 출고 - 별관'
      },
      {
        id: 'SS-001-3',
        scheduleNumber: 3,
        scheduledDate: '2025-11-10',
        quantity: 30,
        remainingQuantity: 0,
        shippingAddress: '서울시 강남구 테헤란로 789',
        receiverName: '박담당',
        receiverPhone: '010-3456-7890',
        status: 'scheduled',
        note: '3차 출고 - 후관'
      }
    ]
  },
  {
    id: 'SO-002',
    orderNumber: 'KD-PR-25002',
    customerName: '대한산업',
    projectName: '공장 블라인드',
    orderDate: '2025-01-20',
    deliveryDate: '2025-02-20',
    totalAmount: 28000000,
    totalQuantity: 20,
    shippedQuantity: 0,
    remainingQuantity: 20,
    status: 'confirmed',
    hasMultipleShipping: false,
    items: [
      { id: '2', itemName: '블라인드', quantity: 20, unitPrice: 1400000, totalPrice: 28000000 }
    ]
  }
];

const initialShippingOrders: ShippingOrder[] = [
  {
    id: 'SH-001',
    shippingNumber: 'KD-OT-251020-01',
    salesOrderId: 'SO-001',
    salesOrderNumber: 'KD-PR-25001',
    scheduleNumber: 1,
    customerName: '(주)한국건설',
    projectName: '서울 오피스빌딩',
    shippingDate: '2025-10-20',
    shippingAddress: '서울시 강남구 테헤란로 123',
    receiverName: '김담당',
    receiverPhone: '010-1234-5678',
    status: 'shipped',
    createdAt: '2025-10-19',
    items: [
      {
        id: 'SHI-001',
        itemCode: 'ST-SET-001',
        itemName: '셔터 세트',
        quantity: 40,
        unit: 'SET',
        lotNumber: 'LOT-25-001',
        lotProductionDate: '2025-10-15'
      }
    ],
    note: '1차 출고 완료'
  }
];

const initialQuotes: Quote[] = [
  {
    id: 'Q-001',
    quoteNumber: 'Q-2025-001',
    customerName: '서울건축',
    projectName: '강남 아파트',
    quoteDate: '2025-01-25',
    validUntil: '2025-02-25',
    totalAmount: 52000000,
    status: 'finalized',
    currentRevision: 0,
    isFinal: true,
    finalizedDate: '2025-01-26',
    finalizedBy: '이영업',
    registrationDate: '2025-01-25',
    receiptDate: '2025-01-25',
    author: '영업팀',
    site: '강남 아파트',
    memo: '신축 공사',
    clientContact: '김과장',
    contactPhone: '010-1111-2222',
    completionDate: '2025-03-31',
    client: '서울건축',
    manager: '이영업',
    contact: '010-2222-3333',
    productCode: 'ST-SET-001',
    quantity: 100,
    amount: 52000000,
    calculationRows: [
      {
        id: 'CR-001-1',
        distributionType: '가이드레일(상/하판)',
        thickness: 'EGI 1.6T',
        width: '100',
        result: '계산완료',
        imageUrl: '',
        quantity: 50,
        notes: '본관용'
      },
      {
        id: 'CR-001-2',
        distributionType: '셔터 세트',
        thickness: 'SUS 1.2T',
        width: '80',
        result: '계산완료',
        imageUrl: '',
        quantity: 30,
        notes: '별관용'
      },
      {
        id: 'CR-001-3',
        distributionType: '알루미늄 프레임',
        thickness: '2.0T',
        width: '120',
        result: '계산완료',
        imageUrl: '',
        quantity: 20,
        notes: '지하주차장용'
      }
    ]
  },
  {
    id: 'Q-002',
    quoteNumber: 'Q-2025-002',
    customerName: '부산건설',
    projectName: '해운대 빌딩',
    quoteDate: '2025-01-26',
    validUntil: '2025-02-26',
    totalAmount: 38000000,
    status: 'approved',
    currentRevision: 2,
    isFinal: false,
    registrationDate: '2025-01-22',
    receiptDate: '2025-01-22',
    author: '영업2팀',
    site: '해운대 빌딩',
    completionDate: '2025-04-15',
    client: '부산건설',
    manager: '박영업',
    contact: '010-3333-4444',
    productCode: 'BL-SET-002',
    quantity: 75,
    amount: 38000000,
    revisions: [
      {
        revisionNumber: 1,
        revisionDate: '2025-01-23',
        revisionBy: '박영업',
        revisionReason: '고객 요청으로 수량 증가 (50개 → 65개)',
        previousData: {
          id: 'Q-002',
          quoteNumber: 'Q-2025-002',
          customerName: '부산건설',
          projectName: '해운대 빌딩',
          quoteDate: '2025-01-22',
          validUntil: '2025-02-22',
          totalAmount: 32000000,
          status: 'draft' as const,
          currentRevision: 0,
          isFinal: false,
          quantity: 50,
          productCode: 'BL-SET-002'
        }
      },
      {
        revisionNumber: 2,
        revisionDate: '2025-01-26',
        revisionBy: '박영업',
        revisionReason: '단가 조정 및 추가 옵션 반영',
        previousData: {
          id: 'Q-002',
          quoteNumber: 'Q-2025-002',
          customerName: '부산건설',
          projectName: '해운대 빌딩',
          quoteDate: '2025-01-22',
          validUntil: '2025-02-22',
          totalAmount: 35000000,
          status: 'draft' as const,
          currentRevision: 1,
          isFinal: false,
          quantity: 65,
          productCode: 'BL-SET-002'
        }
      }
    ],
    calculationRows: [
      {
        id: 'CR-002-1',
        distributionType: '방화셔터',
        thickness: 'EGI 2.0T',
        width: '150',
        result: '계산완료',
        imageUrl: '',
        quantity: 25,
        notes: '1층 상가용'
      },
      {
        id: 'CR-002-2',
        distributionType: '알루미늄 창호',
        thickness: '1.5T',
        width: '90',
        result: '계산완료',
        imageUrl: '',
        quantity: 40,
        notes: '사무실용'
      }
    ]
  },
  // 부품구성표(BOM) 기반 자동 계산 견적 샘플 - 스크린 셔터
  {
    id: 'Q-003',
    quoteNumber: 'KQ#-SC-251029-01',
    customerName: '인천건설',
    projectName: '송도 오피스텔',
    quoteDate: '2025-10-29',
    validUntil: '2025-11-29',
    totalAmount: 337000,
    status: 'draft',
    currentRevision: 0,
    isFinal: false,
    registrationDate: '2025-10-29',
    receiptDate: '2025-10-29',
    author: '영업1팀',
    site: '송도 오피스텔 A동',
    siteId: 'SITE-003',
    siteCode: 'PJ-202510-003',
    memo: '스크린 셔터 부품구성표 기반 자동 견적',
    clientContact: '최담당',
    contactPhone: '010-5555-6666',
    completionDate: '2025-11-30',
    client: '인천건설',
    manager: '김영업',
    contact: '010-1234-5678',
    productCode: '스크린 셔터-표준형',
    quantity: 1,
    amount: 337000,
    type: '스크린',
    remarks: '송도 오피스텔 A동 101호 거실창',
    responseMethod: '이메일',
    commitment: '11월말 납품',
    notes: '설치 포함, 원격제어 옵션',
    openSizeWidth: '2000',
    openSizeHeight: '2500',
    modelSelection: '스크린 셔터 (표준형)',
    selectedProducts: ['스크린 셔터 (표준형)'],
    productCategory: 'SCREEN',
    selectedProductId: 'ITEM-100',
    calculationRows: []
  }
];

const initialProductionOrders: ProductionOrder[] = [
  {
    id: 'PO-001',
    orderNumber: 'PO-2025-001',
    productName: '셔터 세트',
    quantity: 10,
    startDate: '2025-01-20',
    dueDate: '2025-02-10',
    status: 'in-progress',
    completedQuantity: 4,
    defectQuantity: 0
  },
  {
    id: 'PO-002',
    orderNumber: 'PO-2025-002',
    productName: '블라인드',
    quantity: 20,
    startDate: '2025-01-22',
    dueDate: '2025-02-12',
    status: 'scheduled',
    completedQuantity: 0,
    defectQuantity: 0
  }
];

const initialQualityInspections: QualityInspection[] = [
  {
    id: 'QI-001',
    inspectionNumber: 'QI-2025-001',
    inspectionType: 'final',
    itemName: '셔터 세트',
    quantity: 4,
    passQuantity: 4,
    failQuantity: 0,
    inspectionDate: '2025-01-27',
    inspector: '김검사',
    result: 'pass'
  },
  {
    id: 'QI-002',
    inspectionNumber: 'QI-2025-002',
    inspectionType: 'incoming',
    itemName: '알루미늄 압출재',
    quantity: 100,
    passQuantity: 98,
    failQuantity: 2,
    inspectionDate: '2025-01-26',
    inspector: '이검사',
    result: 'pass'
  }
];

const initialInventoryItems: InventoryItem[] = [
  {
    id: 'INV-001',
    itemCode: 'RM-000001',
    itemName: '알루미늄 압출재',
    itemType: 'RM',
    currentStock: 450,
    safetyStock: 100,
    unit: 'M',
    location: 'A-01',
    lastUpdated: '2025-01-27'
  },
  {
    id: 'INV-002',
    itemCode: 'FG-000001',
    itemName: '셔터 세트',
    itemType: 'FG',
    currentStock: 15,
    safetyStock: 10,
    unit: 'SET',
    location: 'C-01',
    lastUpdated: '2025-01-27'
  },
  {
    id: 'INV-003',
    itemCode: 'FG-SCREEN-STD',
    itemName: '스크린 셔터 (표준형)',
    itemType: 'FG',
    currentStock: 8,
    safetyStock: 5,
    unit: 'SET',
    location: 'C-02',
    lastUpdated: '2025-01-27'
  },
  {
    id: 'INV-004',
    itemCode: 'FG-STEEL-STD',
    itemName: '철재문 (표준형)',
    itemType: 'FG',
    currentStock: 6,
    safetyStock: 5,
    unit: 'SET',
    location: 'C-03',
    lastUpdated: '2025-01-27'
  }
];

const initialPurchaseOrders: PurchaseOrder[] = [
  {
    id: 'PUR-001',
    orderNumber: 'PUR-2025-001',
    supplierName: '서진TNS',
    orderDate: '2025-01-20',
    deliveryDate: '2025-01-27',
    totalAmount: 3500000,
    status: 'received'
  },
  {
    id: 'PUR-002',
    orderNumber: 'PUR-2025-002',
    supplierName: '대한철강',
    orderDate: '2025-01-25',
    deliveryDate: '2025-02-01',
    totalAmount: 2800000,
    status: 'ordered'
  }
];

const initialEmployees: Employee[] = [
  {
    id: 'EMP-001',
    employeeNumber: 'E2025001',
    name: '김철수',
    department: '생산팀',
    position: '팀장',
    status: 'active',
    hireDate: '2020-01-15'
  },
  {
    id: 'EMP-002',
    employeeNumber: 'E2025002',
    name: '이영희',
    department: '품질팀',
    position: '대리',
    status: 'active',
    hireDate: '2021-03-20'
  }
];

const initialAttendances: Attendance[] = [
  {
    id: 'ATT-001',
    employeeId: 'EMP-001',
    date: '2025-01-28',
    checkIn: '09:00',
    checkOut: '18:00',
    status: 'present'
  },
  {
    id: 'ATT-002',
    employeeId: 'EMP-002',
    date: '2025-01-28',
    checkIn: '09:05',
    checkOut: '18:00',
    status: 'late'
  }
];

const initialApprovals: Approval[] = [
  {
    id: 'APP-001',
    documentNumber: 'DOC-2025-001',
    documentType: '구매요청',
    title: '원자재 구매 요청',
    requester: '김철수',
    requestDate: '2025-01-27',
    status: 'pending',
    approvers: ['이팀장', '박부장']
  },
  {
    id: 'APP-002',
    documentNumber: 'DOC-2025-002',
    documentType: '휴가신청',
    title: '연차 신청',
    requester: '이영희',
    requestDate: '2025-01-26',
    status: 'approved',
    approvers: ['김팀장']
  }
];

const initialVehicles: Vehicle[] = [
  {
    id: 'VEH-001',
    vehicleNumber: '12가3456',
    vehicleType: '1톤 트럭',
    status: 'in-use',
    driver: '박기사',
    lastMaintenance: '2025-01-15'
  },
  {
    id: 'VEH-002',
    vehicleNumber: '34나5678',
    vehicleType: '2.5톤 트럭',
    status: 'available',
    lastMaintenance: '2025-01-10'
  }
];

const initialSites: Site[] = [
  {
    id: 'SITE-001',
    siteCode: 'PJ-202501-001',
    siteName: '강남 오피스빌딩 신축공사',
    keyAddress: '서울시 강남구 테헤란로 123',
    clientCode: 'CLI-001',
    clientName: '(주)한국건설',
    siteCategory: '신축',
    contractStartDate: '2025-01-15',
    contractEndDate: '2025-12-31',
    salesManager: '이영업',
    siteManager: '김현장',
    accumulatedOrderAmount: 450000000,
    totalCost: 320000000,
    status: '진행중',
    specialNotes: '지하 4층, 지상 20층 규모. 주요 셔터 및 방화문 설치',
    attachments: [],
    createdAt: '2025-01-15',
    updatedAt: '2025-01-27'
  },
  {
    id: 'SITE-002',
    siteCode: 'PJ-202501-002',
    siteName: '부산 해운대 상가 보강공사',
    keyAddress: '부산시 해운대구 해운대로 567',
    clientCode: 'CLI-002',
    clientName: '부산건설',
    siteCategory: '보강',
    contractStartDate: '2025-02-01',
    contractEndDate: '2025-06-30',
    salesManager: '박영업',
    siteManager: '최현장',
    accumulatedOrderAmount: 180000000,
    totalCost: 125000000,
    status: '수주중',
    specialNotes: '기존 건물 보강 작업. 철재 보강재 추가 설치',
    attachments: [],
    createdAt: '2025-01-20',
    updatedAt: '2025-01-27'
  }
];

const initialAccountingTransactions: AccountingTransaction[] = [
  {
    id: 'ACC-001',
    transactionDate: '2025-01-27',
    type: 'income',
    category: '제품 판매',
    amount: 45000000,
    description: '(주)한국건설 - 셔터 세트',
    status: 'completed'
  },
  {
    id: 'ACC-002',
    transactionDate: '2025-01-26',
    type: 'expense',
    category: '자재 구매',
    amount: 3500000,
    description: '서진TNS - 알루미늄 압출재',
    status: 'completed'
  }
];

const initialReceivables: Receivable[] = [
  {
    id: 'REC-001',
    customerName: '(주)한국건설',
    amount: 22500000,
    dueDate: '2025-02-15',
    status: 'pending'
  },
  {
    id: 'REC-002',
    customerName: '서울건축',
    amount: 15000000,
    dueDate: '2025-01-30',
    status: 'overdue'
  }
];

const initialItemMasters: ItemMaster[] = [
  // 원자재
  {
    id: 'ITEM-001',
    itemCode: '알루미늄 압출재-6063-T5',
    itemName: '알루미늄 압출재',
    itemType: 'RM',
    unit: 'M',
    specification: '6063-T5',
    isVariableSize: false,
    purchasePrice: 8000,
    marginRate: 20,
    salesPrice: 9600,
    safetyStock: 100,
    leadTime: 7,
    createdAt: '2025-01-15'
  },
  // 레거시 제품 (하위 호환성)
  {
    id: 'ITEM-LEGACY-001',
    itemCode: '셔터 세트-레거시',
    itemName: '셔터 세트',
    itemType: 'FG',
    productCategory: 'STEEL',
    unit: 'SET',
    isVariableSize: true,
    purchasePrice: 150000,
    processingCost: 120000,
    laborCost: 120000,
    installCost: 60000,
    marginRate: 30,
    salesPrice: 450000,
    safetyStock: 10,
    leadTime: 14,
    createdAt: '2025-01-15'
  },
  {
    id: 'ITEM-002',
    itemCode: 'SUS 강판-SUS304 1.2T',
    itemName: 'SUS 강판',
    itemType: 'RM',
    unit: 'KG',
    specification: 'SUS304 1.2T',
    isVariableSize: false,
    purchasePrice: 5000,
    marginRate: 15,
    salesPrice: 5750,
    safetyStock: 200,
    leadTime: 5,
    createdAt: '2025-01-15'
  },
  {
    id: 'ITEM-003',
    itemCode: 'EGI 강판-EGI 1.6T',
    itemName: 'EGI 강판',
    itemType: 'RM',
    unit: 'KG',
    specification: 'EGI 1.6T',
    isVariableSize: false,
    purchasePrice: 3500,
    marginRate: 20,
    salesPrice: 4200,
    safetyStock: 300,
    leadTime: 5,
    createdAt: '2025-01-15'
  },
  
  // 부품 - 모터 용량별
  {
    id: 'MOTOR-150K',
    itemCode: 'MOTOR-150K',
    itemName: '모터 150K',
    itemType: 'PT',
    itemCategory: '모터',
    unit: 'EA',
    specification: '150K',
    isVariableSize: false,
    purchasePrice: 50000,
    marginRate: 30,
    salesPrice: 65000,
    safetyStock: 10,
    leadTime: 7,
    createdAt: '2025-11-18'
  },
  {
    id: 'MOTOR-300K',
    itemCode: 'MOTOR-300K',
    itemName: '모터 300K',
    itemType: 'PT',
    itemCategory: '모터',
    unit: 'EA',
    specification: '300K',
    isVariableSize: false,
    purchasePrice: 80000,
    marginRate: 30,
    salesPrice: 104000,
    safetyStock: 10,
    leadTime: 7,
    createdAt: '2025-11-18'
  },
  {
    id: 'MOTOR-400K',
    itemCode: 'MOTOR-400K',
    itemName: '모터 400K',
    itemType: 'PT',
    itemCategory: '모터',
    unit: 'EA',
    specification: '400K',
    isVariableSize: false,
    purchasePrice: 100000,
    marginRate: 30,
    salesPrice: 130000,
    safetyStock: 10,
    leadTime: 7,
    createdAt: '2025-11-18'
  },
  {
    id: 'MOTOR-500K',
    itemCode: 'MOTOR-500K',
    itemName: '모터 500K',
    itemType: 'PT',
    itemCategory: '모터',
    unit: 'EA',
    specification: '500K',
    isVariableSize: false,
    purchasePrice: 120000,
    marginRate: 30,
    salesPrice: 156000,
    safetyStock: 10,
    leadTime: 7,
    createdAt: '2025-11-18'
  },
  {
    id: 'MOTOR-600K',
    itemCode: 'MOTOR-600K',
    itemName: '모터 600K',
    itemType: 'PT',
    itemCategory: '모터',
    unit: 'EA',
    specification: '600K',
    isVariableSize: false,
    purchasePrice: 140000,
    marginRate: 30,
    salesPrice: 182000,
    safetyStock: 10,
    leadTime: 7,
    createdAt: '2025-11-18'
  },
  {
    id: 'MOTOR-800K',
    itemCode: 'MOTOR-800K',
    itemName: '모터 800K',
    itemType: 'PT',
    itemCategory: '모터',
    unit: 'EA',
    specification: '800K',
    isVariableSize: false,
    purchasePrice: 180000,
    marginRate: 30,
    salesPrice: 234000,
    safetyStock: 10,
    leadTime: 7,
    createdAt: '2025-11-18'
  },
  {
    id: 'MOTOR-1000K',
    itemCode: 'MOTOR-1000K',
    itemName: '모터 1000K',
    itemType: 'PT',
    itemCategory: '모터',
    unit: 'EA',
    specification: '1000K',
    isVariableSize: false,
    purchasePrice: 220000,
    marginRate: 30,
    salesPrice: 286000,
    safetyStock: 10,
    leadTime: 7,
    createdAt: '2025-11-18'
  },

  // 브라케트 품목
  {
    id: 'BRACKET-380-180',
    itemCode: 'BRACKET-380-180',
    itemName: '브라케트 380×180',
    itemType: 'PT',
    itemCategory: '브라케트',
    unit: 'EA',
    specification: '380×180',
    isVariableSize: false,
    purchasePrice: 15000,
    marginRate: 25,
    salesPrice: 18750,
    safetyStock: 20,
    leadTime: 5,
    createdAt: '2025-11-18'
  },
  {
    id: 'BRACKET-530-320',
    itemCode: 'BRACKET-530-320',
    itemName: '브라케트 530×320',
    itemType: 'PT',
    itemCategory: '브라케트',
    unit: 'EA',
    specification: '530×320',
    isVariableSize: false,
    purchasePrice: 22000,
    marginRate: 25,
    salesPrice: 27500,
    safetyStock: 20,
    leadTime: 5,
    createdAt: '2025-11-18'
  },
  {
    id: 'BRACKET-600-350',
    itemCode: 'BRACKET-600-350',
    itemName: '브라케트 600×350',
    itemType: 'PT',
    itemCategory: '브라케트',
    unit: 'EA',
    specification: '600×350',
    isVariableSize: false,
    purchasePrice: 26000,
    marginRate: 25,
    salesPrice: 32500,
    safetyStock: 20,
    leadTime: 5,
    createdAt: '2025-11-18'
  },
  {
    id: 'BRACKET-690-390',
    itemCode: 'BRACKET-690-390',
    itemName: '브라케트 690×390',
    itemType: 'PT',
    itemCategory: '브라케트',
    unit: 'EA',
    specification: '690×390',
    isVariableSize: false,
    purchasePrice: 30000,
    marginRate: 25,
    salesPrice: 37500,
    safetyStock: 20,
    leadTime: 5,
    createdAt: '2025-11-18'
  },

  // 받침용앵글 품목
  {
    id: 'ANGLE-40-40-380',
    itemCode: 'ANGLE-40-40-380',
    itemName: '받침용앵글 40×40×380',
    itemType: 'PT',
    itemCategory: '받침용앵글',
    unit: 'EA',
    specification: '40×40×380',
    isVariableSize: false,
    purchasePrice: 8000,
    marginRate: 25,
    salesPrice: 10000,
    safetyStock: 30,
    leadTime: 5,
    createdAt: '2025-11-18'
  },
  {
    id: 'ANGLE-50-50-530',
    itemCode: 'ANGLE-50-50-530',
    itemName: '받침용앵글 50×50×530',
    itemType: 'PT',
    itemCategory: '받침용앵글',
    unit: 'EA',
    specification: '50×50×530',
    isVariableSize: false,
    purchasePrice: 12000,
    marginRate: 25,
    salesPrice: 15000,
    safetyStock: 30,
    leadTime: 5,
    createdAt: '2025-11-18'
  },
  {
    id: 'ANGLE-50-50-600',
    itemCode: 'ANGLE-50-50-600',
    itemName: '받침용앵글 50×50×600',
    itemType: 'PT',
    itemCategory: '받침용앵글',
    unit: 'EA',
    specification: '50×50×600',
    isVariableSize: false,
    purchasePrice: 13000,
    marginRate: 25,
    salesPrice: 16250,
    safetyStock: 30,
    leadTime: 5,
    createdAt: '2025-11-18'
  },
  {
    id: 'ANGLE-50-50-690',
    itemCode: 'ANGLE-50-50-690',
    itemName: '받침용앵글 50×50×690',
    itemType: 'PT',
    itemCategory: '받침용앵글',
    unit: 'EA',
    specification: '50×50×690',
    isVariableSize: false,
    purchasePrice: 14500,
    marginRate: 25,
    salesPrice: 18125,
    safetyStock: 30,
    leadTime: 5,
    createdAt: '2025-11-18'
  },
  
  // 기존 모터 (레거시)
  {
    id: 'ITEM-010',
    itemCode: '모터-1HP 220V',
    itemName: '모터',
    itemType: 'PT',
    unit: 'EA',
    specification: '1HP 220V',
    isVariableSize: false,
    purchasePrice: 80000,
    marginRate: 30,
    salesPrice: 104000,
    safetyStock: 20,
    leadTime: 7,
    createdAt: '2025-01-16',
    bom: [
      {
        id: 'BOM-PT10-1',
        childItemCode: '구리선-1.5mm',
        childItemName: '구리선',
        quantity: 50,
        unit: 'M',
        unitPrice: 500,
        note: '모터 권선용'
      },
      {
        id: 'BOM-PT10-2',
        childItemCode: '알루미늄 케이스-Φ150',
        childItemName: '알루미늄 케이스',
        quantity: 1,
        unit: 'EA',
        unitPrice: 15000,
        note: '모터 외함'
      },
      {
        id: 'BOM-PT10-3',
        childItemCode: '베어링-6201',
        childItemName: '베어링',
        quantity: 2,
        unit: 'EA',
        unitPrice: 3000,
        note: '축 베어링'
      }
    ]
  },
  {
    id: 'ITEM-011',
    itemCode: '가이드레일-SUS 1.2T',
    itemName: '가이드레일',
    itemType: 'PT',
    unit: 'M',
    specification: 'SUS 1.2T',
    isVariableSize: true,
    purchasePrice: 9600,
    processingCost: 3000,
    marginRate: 25,
    salesPrice: 15750,
    safetyStock: 50,
    leadTime: 3,
    createdAt: '2025-01-16',
    bom: [
      {
        id: 'BOM-PT11-1',
        childItemCode: 'SUS304 판재-1.2T',
        childItemName: 'SUS304 판재',
        quantity: 1.2,
        unit: 'KG',
        unitPrice: 8000,
        note: '절단 및 절곡 가공'
      }
    ]
  },
  {
    id: 'ITEM-012',
    itemCode: '가이드레일-EGI 1.6T',
    itemName: '가이드레일',
    itemType: 'PT',
    unit: 'M',
    specification: 'EGI 1.6T',
    isVariableSize: true,
    purchasePrice: 8750,
    processingCost: 2500,
    marginRate: 25,
    salesPrice: 14063,
    safetyStock: 50,
    leadTime: 3,
    createdAt: '2025-01-16',
    bom: [
      {
        id: 'BOM-PT12-1',
        childItemCode: 'EGI 강판-1.6T',
        childItemName: 'EGI 강판',
        quantity: 2.5,
        unit: 'KG',
        unitPrice: 3500,
        note: '절단 및 절곡 가공'
      }
    ]
  },
  // 새로운 규격별 가이드레일 (2025-01-17 추가)
  {
    id: 'ITEM-GR-2438',
    itemCode: 'GR-2438',
    itemName: '가이드레일 2438mm',
    itemType: 'PT',
    unit: 'EA',
    specification: '2438mm',
    isVariableSize: false,
    purchasePrice: 18000,
    processingCost: 5000,
    marginRate: 25,
    salesPrice: 28750,
    safetyStock: 20,
    leadTime: 5,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-GR2438-1',
        childItemCode: 'SUS304 판재-1.2T',
        childItemName: 'SUS304 판재',
        quantity: 2.9,
        unit: 'KG',
        unitPrice: 8000,
        note: '가이드레일 2438mm용'
      }
    ]
  },
  {
    id: 'ITEM-GR-3000',
    itemCode: 'GR-3000',
    itemName: '가이드레일 3000mm',
    itemType: 'PT',
    unit: 'EA',
    specification: '3000mm',
    isVariableSize: false,
    purchasePrice: 22000,
    processingCost: 6000,
    marginRate: 25,
    salesPrice: 35000,
    safetyStock: 20,
    leadTime: 5,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-GR3000-1',
        childItemCode: 'SUS304 판재-1.2T',
        childItemName: 'SUS304 판재',
        quantity: 3.6,
        unit: 'KG',
        unitPrice: 8000,
        note: '가이드레일 3000mm용'
      }
    ]
  },
  {
    id: 'ITEM-GR-3500',
    itemCode: 'GR-3500',
    itemName: '가이드레일 3500mm',
    itemType: 'PT',
    unit: 'EA',
    specification: '3500mm',
    isVariableSize: false,
    purchasePrice: 25000,
    processingCost: 7000,
    marginRate: 25,
    salesPrice: 40000,
    safetyStock: 15,
    leadTime: 5,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-GR3500-1',
        childItemCode: 'SUS304 판재-1.2T',
        childItemName: 'SUS304 판재',
        quantity: 4.2,
        unit: 'KG',
        unitPrice: 8000,
        note: '가이드레일 3500mm용'
      }
    ]
  },
  {
    id: 'ITEM-GR-4000',
    itemCode: 'GR-4000',
    itemName: '가이드레일 4000mm',
    itemType: 'PT',
    unit: 'EA',
    specification: '4000mm',
    isVariableSize: false,
    purchasePrice: 28000,
    processingCost: 8000,
    marginRate: 25,
    salesPrice: 45000,
    safetyStock: 15,
    leadTime: 5,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-GR4000-1',
        childItemCode: 'SUS304 판재-1.2T',
        childItemName: 'SUS304 판재',
        quantity: 4.8,
        unit: 'KG',
        unitPrice: 8000,
        note: '가이드레일 4000mm용'
      }
    ]
  },
  {
    id: 'ITEM-GR-4300',
    itemCode: 'GR-4300',
    itemName: '가이드레일 4300mm',
    itemType: 'PT',
    unit: 'EA',
    specification: '4300mm',
    isVariableSize: false,
    purchasePrice: 30000,
    processingCost: 8500,
    marginRate: 25,
    salesPrice: 48125,
    safetyStock: 10,
    leadTime: 5,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-GR4300-1',
        childItemCode: 'SUS304 판재-1.2T',
        childItemName: 'SUS304 판재',
        quantity: 5.2,
        unit: 'KG',
        unitPrice: 8000,
        note: '가이드레일 4300mm용'
      }
    ]
  },
  {
    id: 'ITEM-GR-COMBO-3000-3500',
    itemCode: 'GR-COMBO-3000-3500',
    itemName: '가이드레일 조합 (3000+3500)',
    itemType: 'PT',
    unit: 'SET',
    specification: '3000mm x2 + 3500mm x2',
    isVariableSize: false,
    purchasePrice: 94000,
    processingCost: 26000,
    marginRate: 25,
    salesPrice: 150000,
    safetyStock: 5,
    leadTime: 5,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-GRCOMBO-1',
        childItemCode: 'GR-3000',
        childItemName: '가이드레일 3000mm',
        quantity: 2,
        unit: 'EA',
        unitPrice: 35000,
        note: '가이드레일 3000mm 2개'
      },
      {
        id: 'BOM-GRCOMBO-2',
        childItemCode: 'GR-3500',
        childItemName: '가이드레일 3500mm',
        quantity: 2,
        unit: 'EA',
        unitPrice: 40000,
        note: '가이드레일 3500mm 2개'
      }
    ]
  },
  {
    id: 'ITEM-BASE-WALL',
    itemCode: 'BASE-WALL',
    itemName: '하부 Base (벽면형)',
    itemType: 'PT',
    unit: 'EA',
    specification: '벽면형 고정 베이스',
    isVariableSize: false,
    purchasePrice: 15000,
    processingCost: 3000,
    marginRate: 25,
    salesPrice: 22500,
    safetyStock: 20,
    leadTime: 3,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-BASEWALL-1',
        childItemCode: 'SPCC-2.0T',
        childItemName: 'SPCC 철판',
        quantity: 1.5,
        unit: 'KG',
        unitPrice: 3000,
        note: '벽면형 Base 철판'
      }
    ]
  },
  {
    id: 'ITEM-BASE-SIDE',
    itemCode: 'BASE-SIDE',
    itemName: '하부 Base (측면형)',
    itemType: 'PT',
    unit: 'EA',
    specification: '측면형 고정 베이스',
    isVariableSize: false,
    purchasePrice: 18000,
    processingCost: 4000,
    marginRate: 25,
    salesPrice: 27500,
    safetyStock: 15,
    leadTime: 3,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-BASESIDE-1',
        childItemCode: 'SPCC-2.3T',
        childItemName: 'SPCC 철판',
        quantity: 2.0,
        unit: 'KG',
        unitPrice: 3000,
        note: '측면형 Base 철판'
      }
    ]
  },
  {
    id: 'ITEM-013',
    itemCode: '연기차단재-실리콘',
    itemName: '연기차단재',
    itemType: 'PT',
    unit: 'M',
    specification: '실리콘',
    isVariableSize: true,
    purchasePrice: 5000,
    marginRate: 20,
    salesPrice: 6000,
    safetyStock: 100,
    leadTime: 7,
    createdAt: '2025-01-16',
    bom: [
      {
        id: 'BOM-PT13-1',
        childItemCode: '실리콘 원료-내열',
        childItemName: '실리콘 원료',
        quantity: 0.5,
        unit: 'KG',
        unitPrice: 8000,
        note: '압출 성형'
      }
    ]
  },
  {
    id: 'ITEM-014',
    itemCode: '케이스판재-AL 1.0T',
    itemName: '케이스판재',
    itemType: 'PT',
    unit: 'EA',
    specification: 'AL 1.0T',
    isVariableSize: true,
    purchasePrice: 22500,
    processingCost: 15000,
    marginRate: 25,
    salesPrice: 46875,
    safetyStock: 30,
    leadTime: 5,
    createdAt: '2025-01-16',
    bom: [
      {
        id: 'BOM-PT14-1',
        childItemCode: '알루미늄 판재-3.0T x 1000W',
        childItemName: '알루미늄 판재',
        quantity: 0.5,
        unit: 'M2',
        unitPrice: 45000,
        note: '절단 및 벤딩'
      }
    ]
  },
  {
    id: 'ITEM-015',
    itemCode: '하단마감재-PVC',
    itemName: '하단마감재',
    itemType: 'PT',
    unit: 'M',
    specification: 'PVC',
    isVariableSize: true,
    purchasePrice: 8000,
    marginRate: 20,
    salesPrice: 9600,
    safetyStock: 50,
    leadTime: 5,
    createdAt: '2025-01-16',
    bom: [
      {
        id: 'BOM-PT15-1',
        childItemCode: 'PVC 압출재-50mm',
        childItemName: 'PVC 압출재',
        quantity: 1.1,
        unit: 'M',
        unitPrice: 5000,
        note: '절단 및 조립'
      },
      {
        id: 'BOM-PT15-2',
        childItemCode: '고무패킹-10mm',
        childItemName: '고무패킹',
        quantity: 1,
        unit: 'M',
        unitPrice: 1500,
        note: '밀폐용'
      }
    ]
  },
  {
    id: 'ITEM-016',
    itemCode: '감기샤프트-AL Ø60',
    itemName: '감기샤프트',
    itemType: 'PT',
    unit: 'M',
    specification: 'AL Ø60',
    isVariableSize: true,
    purchasePrice: 10500,
    processingCost: 12000,
    marginRate: 25,
    salesPrice: 28125,
    safetyStock: 20,
    leadTime: 7,
    createdAt: '2025-01-16',
    bom: [
      {
        id: 'BOM-PT16-1',
        childItemCode: '알루미늄 파이프-Ø60x3T',
        childItemName: '알루미늄 파이프',
        quantity: 1.05,
        unit: 'M',
        unitPrice: 10000,
        note: '절단 및 가공'
      }
    ]
  },
  {
    id: 'ITEM-017',
    itemCode: '각파이프-25x25x1.5T',
    itemName: '각파이프',
    itemType: 'PT',
    unit: 'M',
    specification: '25x25x1.5T',
    isVariableSize: true,
    purchasePrice: 4000,
    marginRate: 20,
    salesPrice: 4800,
    safetyStock: 100,
    leadTime: 5,
    createdAt: '2025-01-16',
    bom: [
      {
        id: 'BOM-PT17-1',
        childItemCode: '강관-Φ50x2.3T',
        childItemName: '강관',
        quantity: 1.05,
        unit: 'M',
        unitPrice: 8500,
        note: '절단 및 용접'
      }
    ]
  },
  {
    id: 'ITEM-018',
    itemCode: '환봉-SUS Ø12',
    itemName: '환봉',
    itemType: 'PT',
    unit: 'M',
    specification: 'SUS Ø12',
    isVariableSize: true,
    purchasePrice: 6000,
    marginRate: 20,
    salesPrice: 7200,
    safetyStock: 80,
    leadTime: 7,
    createdAt: '2025-01-16',
    bom: [
      {
        id: 'BOM-PT18-1',
        childItemCode: 'SUS304 환봉-Ø12',
        childItemName: 'SUS304 환봉 원자재',
        quantity: 1.05,
        unit: 'M',
        unitPrice: 5000,
        note: '절단'
      }
    ]
  },
  {
    id: 'ITEM-019',
    itemCode: '조인트바-AL 40x20',
    itemName: '조인트바',
    itemType: 'PT',
    unit: 'M',
    specification: 'AL 40x20',
    isVariableSize: true,
    purchasePrice: 13200,
    processingCost: 7000,
    marginRate: 25,
    salesPrice: 25250,
    safetyStock: 60,
    leadTime: 5,
    createdAt: '2025-01-16',
    bom: [
      {
        id: 'BOM-PT19-1',
        childItemCode: '알루미늄 앵글-50x50x5T',
        childItemName: '알루미늄 앵글',
        quantity: 1.1,
        unit: 'M',
        unitPrice: 12000,
        note: '절단 및 가공'
      }
    ]
  },
  
  // 제품 - 스크린
  {
    id: 'ITEM-100',
    itemCode: '스크린 셔터-표준형',
    itemName: '스크린 셔터 (표준형)',
    itemType: 'FG',
    productCategory: 'SCREEN',
    unit: 'SET',
    isVariableSize: true,
    purchasePrice: 180000,
    processingCost: 100000,
    laborCost: 100000,
    installCost: 50000,
    marginRate: 30,
    salesPrice: 450000,
    safetyStock: 10,
    leadTime: 14,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-1',
        childItemCode: '모터-1HP 220V',
        childItemName: '모터',
        quantity: 1,
        unit: 'EA',
        unitPrice: 80000,
        note: '고정 수량'
      },
      {
        id: 'BOM-2',
        childItemCode: '가이드레일-SUS 1.2T',
        childItemName: '가이드레일 (SUS)',
        quantity: 1,
        unit: 'M',
        unitPrice: 3000,
        quantityFormula: 'W * 2',
        note: '폭 x 2'
      },
      {
        id: 'BOM-3',
        childItemCode: '가이드레일-EGI 1.6T',
        childItemName: '가이드레일 (EGI)',
        quantity: 1,
        unit: 'M',
        unitPrice: 2500,
        quantityFormula: 'H * 2',
        note: '높이 x 2'
      },
      {
        id: 'BOM-4',
        childItemCode: '알루미늄 압출재-6063-T5',
        childItemName: '알루미늄 압출재',
        quantity: 1,
        unit: 'M',
        unitPrice: 8000,
        quantityFormula: '(W + H) * 2',
        note: '(폭+높이) x 2'
      }
    ]
  },
  {
    id: 'ITEM-101',
    itemCode: '스크린 셔터-프리미엄A',
    itemName: '스크린 셔터 (프리미엄)',
    itemType: 'FG',
    productCategory: 'SCREEN',
    unit: 'SET',
    isVariableSize: true,
    purchasePrice: 280000,
    processingCost: 150000,
    laborCost: 150000,
    installCost: 80000,
    marginRate: 35,
    salesPrice: 650000,
    safetyStock: 5,
    leadTime: 21,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-5',
        childItemCode: '모터-1HP 220V',
        childItemName: '모터',
        quantity: 2,
        unit: 'EA',
        unitPrice: 80000,
        note: '고정 수량 (듀얼 모터)'
      },
      {
        id: 'BOM-6',
        childItemCode: '가이드레일-SUS 1.2T',
        childItemName: '가이드레일 (SUS)',
        quantity: 1,
        unit: 'M',
        unitPrice: 3000,
        quantityFormula: '(W + H) * 2',
        note: '(폭+높이) x 2'
      },
      {
        id: 'BOM-7',
        childItemCode: '알루미늄 압출재-6063-T5',
        childItemName: '알루미늄 압출재',
        quantity: 1,
        unit: 'M',
        unitPrice: 8000,
        quantityFormula: '(W + H) * 3',
        note: '(폭+높이) x 3'
      }
    ]
  },
  
  // 제품 - 철재
  {
    id: 'ITEM-200',
    itemCode: '철재 셔터-표준형',
    itemName: '철재 셔터 (표준형)',
    itemType: 'FG',
    productCategory: 'STEEL',
    unit: 'SET',
    isVariableSize: true,
    purchasePrice: 200000,
    processingCost: 120000,
    laborCost: 120000,
    installCost: 60000,
    marginRate: 32,
    salesPrice: 500000,
    safetyStock: 8,
    leadTime: 14,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-10',
        childItemCode: '모터-1HP 220V',
        childItemName: '모터',
        quantity: 1,
        unit: 'EA',
        unitPrice: 80000,
        note: '고정 수량'
      },
      {
        id: 'BOM-11',
        childItemCode: '가이드레일-EGI 1.6T',
        childItemName: '가이드레일 (EGI)',
        quantity: 1,
        unit: 'M',
        unitPrice: 2500,
        quantityFormula: 'W * 2',
        note: '폭 x 2'
      },
      {
        id: 'BOM-12',
        childItemCode: 'EGI 강판-EGI 1.6T',
        childItemName: 'EGI 강판',
        quantity: 1,
        unit: 'KG',
        unitPrice: 3500,
        quantityFormula: 'W * H / 1000 * 5',
        note: '면적 대비 중량'
      }
    ]
  },
  {
    id: 'ITEM-201',
    itemCode: '철재 셔터-중량형',
    itemName: '철재 셔터 (중량형)',
    itemType: 'FG',
    productCategory: 'STEEL',
    unit: 'SET',
    isVariableSize: true,
    purchasePrice: 350000,
    processingCost: 180000,
    laborCost: 180000,
    installCost: 100000,
    marginRate: 35,
    salesPrice: 750000,
    safetyStock: 3,
    leadTime: 21,
    createdAt: '2025-01-17',
    bom: [
      {
        id: 'BOM-15',
        childItemCode: '모터-1HP 220V',
        childItemName: '모터',
        quantity: 2,
        unit: 'EA',
        unitPrice: 80000,
        note: '고정 수량 (듀얼 모터)'
      },
      {
        id: 'BOM-16',
        childItemCode: '가이드레일-SUS 1.2T',
        childItemName: '가이드레일 (SUS)',
        quantity: 1,
        unit: 'M',
        unitPrice: 3000,
        quantityFormula: 'W * 2',
        note: '폭 x 2 (SUS 강화)'
      },
      {
        id: 'BOM-17',
        childItemCode: 'SUS 강판-SUS304 1.2T',
        childItemName: 'SUS 강판',
        quantity: 1,
        unit: 'KG',
        unitPrice: 5000,
        quantityFormula: 'W * H / 1000 * 7',
        note: '면적 대비 중량'
      }
    ]
  },
  
  // 추가 원자재 - 알루미늄 및 강재
  {
    id: 'ITEM-004',
    itemCode: '알루미늄 앵글-50x50x5T',
    itemName: '알루미늄 앵글',
    itemType: 'RM',
    unit: 'M',
    specification: '50x50x5T',
    isVariableSize: false,
    purchasePrice: 12000,
    marginRate: 18,
    salesPrice: 14160,
    safetyStock: 80,
    leadTime: 7,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-005',
    itemCode: '알루미늄 판재-3.0T x 1000W',
    itemName: '알루미늄 판재',
    itemType: 'RM',
    unit: 'M2',
    specification: '3.0T x 1000W',
    isVariableSize: false,
    purchasePrice: 45000,
    marginRate: 20,
    salesPrice: 54000,
    safetyStock: 50,
    leadTime: 10,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-006',
    itemCode: '강관-Φ50x2.3T',
    itemName: '강관',
    itemType: 'RM',
    unit: 'M',
    specification: 'Φ50x2.3T',
    isVariableSize: false,
    purchasePrice: 8500,
    marginRate: 15,
    salesPrice: 9775,
    safetyStock: 100,
    leadTime: 5,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-007',
    itemCode: '형강-[100x50x5x7.5T',
    itemName: '형강 (채널)',
    itemType: 'RM',
    unit: 'M',
    specification: '[100x50x5x7.5T',
    isVariableSize: false,
    purchasePrice: 15000,
    marginRate: 18,
    salesPrice: 17700,
    safetyStock: 60,
    leadTime: 7,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-008',
    itemCode: '아연도금 강판-GI 0.8T',
    itemName: '아연도금 강판',
    itemType: 'RM',
    unit: 'KG',
    specification: 'GI 0.8T',
    isVariableSize: false,
    purchasePrice: 2800,
    marginRate: 20,
    salesPrice: 3360,
    safetyStock: 500,
    leadTime: 5,
    createdAt: '2025-10-29'
  },
  
  // 추가 원자재 - 스크린 관련
  {
    id: 'ITEM-020',
    itemCode: '스크린 원단-PVC 100% 차단',
    itemName: '스크린 원단 (차단)',
    itemType: 'RM',
    unit: 'M2',
    specification: 'PVC 100% 차단',
    isVariableSize: false,
    purchasePrice: 18000,
    marginRate: 25,
    salesPrice: 22500,
    safetyStock: 200,
    leadTime: 14,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-021',
    itemCode: '스크린 원단-PVC 95% 차광',
    itemName: '스크린 원단 (차광)',
    itemType: 'RM',
    unit: 'M2',
    specification: 'PVC 95% 차광',
    isVariableSize: false,
    purchasePrice: 15000,
    marginRate: 25,
    salesPrice: 18750,
    safetyStock: 200,
    leadTime: 14,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-022',
    itemCode: '스크린 원단-PVC 20% 투시',
    itemName: '스크린 원단 (투시)',
    itemType: 'RM',
    unit: 'M2',
    specification: 'PVC 20% 투시',
    isVariableSize: false,
    purchasePrice: 12000,
    marginRate: 25,
    salesPrice: 15000,
    safetyStock: 150,
    leadTime: 14,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-023',
    itemCode: '스크린 원단-PVC 메쉬형',
    itemName: '스크린 원단 (메쉬)',
    itemType: 'RM',
    unit: 'M2',
    specification: 'PVC 메쉬형',
    isVariableSize: false,
    purchasePrice: 10000,
    marginRate: 25,
    salesPrice: 12500,
    safetyStock: 150,
    leadTime: 14,
    createdAt: '2025-10-29'
  },
  
  // 추가 원자재 - 부품 제조용
  {
    id: 'ITEM-038',
    itemCode: '구리선-1.5mm',
    itemName: '구리선',
    itemType: 'RM',
    unit: 'M',
    specification: '1.5mm',
    isVariableSize: false,
    purchasePrice: 500,
    marginRate: 15,
    salesPrice: 575,
    safetyStock: 1000,
    leadTime: 7,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-039',
    itemCode: '알루미늄 케이스-Φ150',
    itemName: '알루미늄 케이스',
    itemType: 'RM',
    unit: 'EA',
    specification: 'Φ150',
    isVariableSize: false,
    purchasePrice: 15000,
    marginRate: 20,
    salesPrice: 18000,
    safetyStock: 50,
    leadTime: 10,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-044',
    itemCode: '베어링-6201',
    itemName: '베어링',
    itemType: 'RM',
    unit: 'EA',
    specification: '6201',
    isVariableSize: false,
    purchasePrice: 3000,
    marginRate: 25,
    salesPrice: 3750,
    safetyStock: 100,
    leadTime: 7,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-045',
    itemCode: 'SUS304 판재-1.2T',
    itemName: 'SUS304 판재',
    itemType: 'RM',
    unit: 'KG',
    specification: '1.2T',
    isVariableSize: false,
    purchasePrice: 8000,
    marginRate: 20,
    salesPrice: 9600,
    safetyStock: 500,
    leadTime: 7,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-056',
    itemCode: 'EGI 강판-1.6T',
    itemName: 'EGI 강판',
    itemType: 'RM',
    unit: 'KG',
    specification: '1.6T',
    isVariableSize: false,
    purchasePrice: 3500,
    marginRate: 20,
    salesPrice: 4200,
    safetyStock: 800,
    leadTime: 5,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-057',
    itemCode: '볼트-M6x20',
    itemName: '볼트',
    itemType: 'RM',
    unit: 'EA',
    specification: 'M6x20',
    isVariableSize: false,
    purchasePrice: 100,
    marginRate: 30,
    salesPrice: 130,
    safetyStock: 2000,
    leadTime: 3,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-058',
    itemCode: '실리콘 원료-내열',
    itemName: '실리콘 원료',
    itemType: 'RM',
    unit: 'KG',
    specification: '내열',
    isVariableSize: false,
    purchasePrice: 8000,
    marginRate: 25,
    salesPrice: 10000,
    safetyStock: 200,
    leadTime: 10,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-059',
    itemCode: 'PVC 압출재-50mm',
    itemName: 'PVC 압출재',
    itemType: 'RM',
    unit: 'M',
    specification: '50mm',
    isVariableSize: false,
    purchasePrice: 5000,
    marginRate: 20,
    salesPrice: 6000,
    safetyStock: 300,
    leadTime: 7,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-060',
    itemCode: '고무패킹-10mm',
    itemName: '고무패킹',
    itemType: 'RM',
    unit: 'M',
    specification: '10mm',
    isVariableSize: false,
    purchasePrice: 1500,
    marginRate: 30,
    salesPrice: 1950,
    safetyStock: 500,
    leadTime: 5,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-061',
    itemCode: '알루미늄 파이프-Ø60x3T',
    itemName: '알루미늄 파이프',
    itemType: 'RM',
    unit: 'M',
    specification: 'Ø60x3T',
    isVariableSize: false,
    purchasePrice: 10000,
    marginRate: 20,
    salesPrice: 12000,
    safetyStock: 100,
    leadTime: 7,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-062',
    itemCode: 'SUS304 환봉-Ø12',
    itemName: 'SUS304 환봉',
    itemType: 'RM',
    unit: 'M',
    specification: 'Ø12',
    isVariableSize: false,
    purchasePrice: 5000,
    marginRate: 20,
    salesPrice: 6000,
    safetyStock: 200,
    leadTime: 7,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-077',
    itemCode: '알루미늄 판재-3.0T x 1000W',
    itemName: '알루미늄 판재',
    itemType: 'RM',
    unit: 'M2',
    specification: '3.0T x 1000W',
    isVariableSize: false,
    purchasePrice: 45000,
    marginRate: 20,
    salesPrice: 54000,
    safetyStock: 50,
    leadTime: 10,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-078',
    itemCode: '강관-Φ50x2.3T',
    itemName: '강관',
    itemType: 'RM',
    unit: 'M',
    specification: 'Φ50x2.3T',
    isVariableSize: false,
    purchasePrice: 8500,
    marginRate: 18,
    salesPrice: 10030,
    safetyStock: 100,
    leadTime: 7,
    createdAt: '2025-10-31'
  },
  {
    id: 'ITEM-079',
    itemCode: '알루미늄 앵글-50x50x5T',
    itemName: '알루미늄 앵글',
    itemType: 'RM',
    unit: 'M',
    specification: '50x50x5T',
    isVariableSize: false,
    purchasePrice: 12000,
    marginRate: 22,
    salesPrice: 14640,
    safetyStock: 80,
    leadTime: 10,
    createdAt: '2025-10-31'
  },
  
  // 추가 부품 - 모터 및 제어기
  {
    id: 'ITEM-069',
    itemCode: '모터-2HP 220V',
    itemName: '모터',
    itemType: 'PT',
    unit: 'EA',
    specification: '2HP 220V',
    isVariableSize: false,
    purchasePrice: 150000,
    marginRate: 30,
    salesPrice: 195000,
    safetyStock: 15,
    leadTime: 7,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-070',
    itemCode: '제어기-표준형 220V',
    itemName: '제어기',
    itemType: 'PT',
    unit: 'EA',
    specification: '표준형 220V',
    isVariableSize: false,
    purchasePrice: 45000,
    marginRate: 35,
    salesPrice: 60750,
    safetyStock: 30,
    leadTime: 5,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-071',
    itemCode: '스마트 제어기-IoT 연동형',
    itemName: '스마트 제어기',
    itemType: 'PT',
    unit: 'EA',
    specification: 'IoT 연동형',
    isVariableSize: false,
    purchasePrice: 85000,
    marginRate: 40,
    salesPrice: 119000,
    safetyStock: 20,
    leadTime: 7,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-072',
    itemCode: '리모컨-기본형 RF',
    itemName: '리모컨',
    itemType: 'PT',
    unit: 'EA',
    specification: '기본형 RF',
    isVariableSize: false,
    purchasePrice: 15000,
    marginRate: 30,
    salesPrice: 19500,
    safetyStock: 50,
    leadTime: 3,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-073',
    itemCode: '풍속 센서-자동 제어용',
    itemName: '풍속 센서',
    itemType: 'PT',
    unit: 'EA',
    specification: '자동 제어용',
    isVariableSize: false,
    purchasePrice: 65000,
    marginRate: 35,
    salesPrice: 87750,
    safetyStock: 10,
    leadTime: 10,
    createdAt: '2025-10-29'
  },
  
  // 추가 부품 - 가이드 및 레일
  {
    id: 'ITEM-074',
    itemCode: '가이드레일-알루미늄',
    itemName: '가이드레일',
    itemType: 'PT',
    unit: 'M',
    specification: '알루미늄',
    isVariableSize: true,
    processingCost: 4000,
    marginRate: 25,
    salesPrice: 5000,
    safetyStock: 50,
    leadTime: 3,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-075',
    itemCode: '하단바-알루미늄 가중바',
    itemName: '하단바',
    itemType: 'PT',
    unit: 'EA',
    specification: '알루미늄 가중바',
    isVariableSize: true,
    processingCost: 8000,
    marginRate: 25,
    salesPrice: 10000,
    safetyStock: 30,
    leadTime: 3,
    createdAt: '2025-10-29'
  },
  
  // 부자재
  {
    id: 'ITEM-066',
    itemCode: '볼트-M8x40 SUS',
    itemName: '볼트',
    itemType: 'SM',
    unit: 'EA',
    specification: 'M8x40 SUS',
    isVariableSize: false,
    purchasePrice: 150,
    marginRate: 20,
    salesPrice: 180,
    safetyStock: 1000,
    leadTime: 3,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-067',
    itemCode: '너트-M8 SUS',
    itemName: '너트',
    itemType: 'SM',
    unit: 'EA',
    specification: 'M8 SUS',
    isVariableSize: false,
    purchasePrice: 80,
    marginRate: 20,
    salesPrice: 96,
    safetyStock: 2000,
    leadTime: 3,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-068',
    itemCode: '브라켓-알루미늄 고정용',
    itemName: '브라켓',
    itemType: 'SM',
    unit: 'EA',
    specification: '알루미늄 고정용',
    isVariableSize: false,
    purchasePrice: 3500,
    marginRate: 25,
    salesPrice: 4375,
    safetyStock: 100,
    leadTime: 5,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-053',
    itemCode: '스프링-장력 조절용',
    itemName: '스프링',
    itemType: 'SM',
    unit: 'EA',
    specification: '장력 조절용',
    isVariableSize: false,
    purchasePrice: 1200,
    marginRate: 25,
    salesPrice: 1500,
    safetyStock: 200,
    leadTime: 5,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-054',
    itemCode: '체인-SUS 구동용',
    itemName: '체인',
    itemType: 'SM',
    unit: 'M',
    specification: 'SUS 구동용',
    isVariableSize: false,
    purchasePrice: 8000,
    marginRate: 20,
    salesPrice: 9600,
    safetyStock: 50,
    leadTime: 7,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-055',
    itemCode: '와이어로프-Φ5mm SUS',
    itemName: '와이어로프',
    itemType: 'SM',
    unit: 'M',
    specification: 'Φ5mm SUS',
    isVariableSize: false,
    purchasePrice: 5500,
    marginRate: 22,
    salesPrice: 6710,
    safetyStock: 100,
    leadTime: 7,
    createdAt: '2025-10-29'
  },
  
  // 방화문 전용 부품
  {
    id: 'ITEM-040',
    itemCode: '자동 클로저-방화문용',
    itemName: '도어 클로저',
    itemType: 'PT',
    unit: 'EA',
    specification: '방화문용 자동 폐쇄',
    isVariableSize: false,
    purchasePrice: 45000,
    marginRate: 25,
    salesPrice: 56250,
    safetyStock: 20,
    leadTime: 7,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-041',
    itemCode: '방화 경첩-3인치 SUS',
    itemName: '방화 경첩',
    itemType: 'PT',
    unit: 'EA',
    specification: '3인치 SUS',
    isVariableSize: false,
    purchasePrice: 8500,
    marginRate: 22,
    salesPrice: 10370,
    safetyStock: 100,
    leadTime: 5,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-042',
    itemCode: '방화 도어록-표준형',
    itemName: '방화 도어록',
    itemType: 'PT',
    unit: 'EA',
    specification: '표준형 레버',
    isVariableSize: false,
    purchasePrice: 35000,
    marginRate: 28,
    salesPrice: 44800,
    safetyStock: 30,
    leadTime: 7,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-043',
    itemCode: '방화 충진재-세라믹',
    itemName: '방화 충진재',
    itemType: 'SM',
    unit: 'KG',
    specification: '세라믹 섬유',
    isVariableSize: false,
    purchasePrice: 12000,
    marginRate: 20,
    salesPrice: 14400,
    safetyStock: 200,
    leadTime: 14,
    createdAt: '2025-10-29'
  },
  
  // 추가 제품 - 방화문
  {
    id: 'ITEM-202',
    itemCode: '방화문-표준형 60분',
    itemName: '방화문 (표준형 60분)',
    itemType: 'FG',
    productCategory: 'STEEL',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 200000,
    installCost: 120000,
    marginRate: 30,
    salesPrice: 850000,
    safetyStock: 5,
    leadTime: 21,
    createdAt: '2025-10-29',
    bom: [
      {
        id: 'BOM-20',
        childItemCode: '형강-[100x50x5x7.5T',
        childItemName: '형강 (채널) - 프레임',
        quantity: 1,
        unit: 'M',
        unitPrice: 15000,
        quantityFormula: '(W + H) * 2 / 1000',
        note: '프레임용 (폭+높이) x 2'
      },
      {
        id: 'BOM-21',
        childItemCode: 'SUS 강판-SUS304 1.2T',
        childItemName: 'SUS 강판 - 도어 패널',
        quantity: 1,
        unit: 'KG',
        unitPrice: 5000,
        quantityFormula: 'W * H / 1000000 * 9.5',
        note: '도어 패널 (면적 대비 중량)'
      },
      {
        id: 'BOM-22',
        childItemCode: '자동 클로저-방화문용',
        childItemName: '도어 클로저',
        quantity: 1,
        unit: 'EA',
        unitPrice: 45000,
        note: '방화문용 자동 폐��장치'
      },
      {
        id: 'BOM-23',
        childItemCode: '방화 경첩-3인치 SUS',
        childItemName: '방화 경첩',
        quantity: 3,
        unit: 'EA',
        unitPrice: 8500,
        note: '개당 3개 기준'
      },
      {
        id: 'BOM-24',
        childItemCode: '방화 도어록-표준형',
        childItemName: '방화 도어록',
        quantity: 1,
        unit: 'EA',
        unitPrice: 35000,
        note: '표준 잠금장치'
      },
      {
        id: 'BOM-25',
        childItemCode: '방화 충진재-세라믹',
        childItemName: '방화 충진재',
        quantity: 1,
        unit: 'KG',
        unitPrice: 12000,
        quantityFormula: 'W * H / 100000',
        note: '내부 충진재 (면적 대비)'
      },
      {
        id: 'BOM-26',
        childItemCode: '볼트-M8x40 SUS',
        childItemName: '볼트',
        quantity: 20,
        unit: 'EA',
        unitPrice: 150,
        note: '고정용 볼트'
      },
      {
        id: 'BOM-27',
        childItemCode: '너트-M8 SUS',
        childItemName: '너트',
        quantity: 20,
        unit: 'EA',
        unitPrice: 80,
        note: '고정용 너트'
      }
    ]
  },
  {
    id: 'ITEM-203',
    itemCode: '롤러셔터-자동 전동형',
    itemName: '롤러셔터 (자동 전동형)',
    itemType: 'FG',
    productCategory: 'STEEL',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 250000,
    installCost: 150000,
    marginRate: 32,
    salesPrice: 1200000,
    safetyStock: 3,
    leadTime: 28,
    createdAt: '2025-10-29',
    bom: [
      {
        id: 'BOM-30',
        childItemCode: '모터-2HP 220V',
        childItemName: '모터 (2HP)',
        quantity: 1,
        unit: 'EA',
        unitPrice: 150000,
        note: '전동 구동용'
      },
      {
        id: 'BOM-31',
        childItemCode: '스마트 제어기-IoT 연동형',
        childItemName: '스마트 제어기',
        quantity: 1,
        unit: 'EA',
        unitPrice: 85000,
        note: 'IoT 원격 제어'
      },
      {
        id: 'BOM-32',
        childItemCode: '리모컨-기본형 RF',
        childItemName: '리모컨',
        quantity: 2,
        unit: 'EA',
        unitPrice: 15000,
        note: '기본 리모컨 2개'
      },
      {
        id: 'BOM-33',
        childItemCode: '가이드레일-EGI 1.6T',
        childItemName: '가이드레일 (EGI)',
        quantity: 1,
        unit: 'M',
        unitPrice: 2500,
        quantityFormula: 'H * 2 / 1000',
        note: '높이 x 2 (양쪽 레일)'
      },
      {
        id: 'BOM-34',
        childItemCode: 'EGI 강판-EGI 1.6T',
        childItemName: 'EGI 강판 - 셔터 슬랫',
        quantity: 1,
        unit: 'KG',
        unitPrice: 3500,
        quantityFormula: 'W * H / 1000000 * 6',
        note: '슬랫 판재 (면적 대비)'
      },
      {
        id: 'BOM-35',
        childItemCode: '체인-SUS 구동용',
        childItemName: '구동 체인',
        quantity: 1,
        unit: 'M',
        unitPrice: 8000,
        quantityFormula: 'H / 1000 * 1.2',
        note: '높�� x 1.2 (구동 체인)'
      },
      {
        id: 'BOM-36',
        childItemCode: '브라켓-알루미늄 고정용',
        childItemName: '고정 브라켓',
        quantity: 4,
        unit: 'EA',
        unitPrice: 3500,
        note: '설치용 브라켓 4개'
      },
      {
        id: 'BOM-37',
        childItemCode: '풍속 센서-자동 제어용',
        childItemName: '풍속 센서',
        quantity: 1,
        unit: 'EA',
        unitPrice: 65000,
        note: '자동 안전 제어'
      }
    ]
  },
  {
    id: 'ITEM-102',
    itemCode: '스크린 셔터-모터리스 수동',
    itemName: '스크린 셔터 (수동형)',
    itemType: 'FG',
    productCategory: 'SCREEN',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 60000,
    installCost: 30000,
    marginRate: 28,
    salesPrice: 280000,
    safetyStock: 10,
    leadTime: 10,
    createdAt: '2025-10-29',
    bom: [
      {
        id: 'BOM-40',
        childItemCode: '가이드레일-알루미늄',
        childItemName: '가이드레일 (알루미늄)',
        quantity: 1,
        unit: 'M',
        unitPrice: 4000,
        quantityFormula: '(W + H) * 2 / 1000',
        note: '(폭+높이) x 2'
      },
      {
        id: 'BOM-41',
        childItemCode: '스크린 원단-PVC 95% 차광',
        childItemName: '스크린 원단 (차광)',
        quantity: 1,
        unit: 'M2',
        unitPrice: 15000,
        quantityFormula: 'W * H / 1000000 * 1.1',
        note: '면적 x 1.1 (여유분 포함)'
      },
      {
        id: 'BOM-42',
        childItemCode: '하단바-알루미늄 가중바',
        childItemName: '하단바 (가중바)',
        quantity: 1,
        unit: 'EA',
        unitPrice: 8000,
        note: '수동 조작용 하단바'
      },
      {
        id: 'BOM-43',
        childItemCode: '스프링-장력 조절용',
        childItemName: '스프링 (장력 조절)',
        quantity: 2,
        unit: 'EA',
        unitPrice: 1200,
        note: '양쪽 장력 조절'
      },
      {
        id: 'BOM-44',
        childItemCode: '브라켓-알루미늄 고정용',
        childItemName: '고정 브라켓',
        quantity: 2,
        unit: 'EA',
        unitPrice: 3500,
        note: '설치용 브라켓'
      }
    ]
  },
  {
    id: 'ITEM-076',
    itemCode: '와이어로프-Φ5mm SUS',
    itemName: '와이어로프',
    itemType: 'SM',
    unit: 'M',
    specification: 'Φ5mm SUS',
    isVariableSize: false,
    purchasePrice: 3500,
    marginRate: 20,
    salesPrice: 4200,
    safetyStock: 100,
    leadTime: 5,
    createdAt: '2025-10-29'
  },
  
  // 소모품
  {
    id: 'ITEM-047',
    itemCode: '용접봉-Φ3.2mm',
    itemName: '용접봉',
    itemType: 'CS',
    unit: 'KG',
    specification: 'Φ3.2mm',
    isVariableSize: false,
    purchasePrice: 12000,
    marginRate: 15,
    salesPrice: 13800,
    safetyStock: 50,
    leadTime: 3,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-048',
    itemCode: '그리스-리튬 베이스',
    itemName: '그리스',
    itemType: 'CS',
    unit: 'KG',
    specification: '리튬 베이스',
    isVariableSize: false,
    purchasePrice: 8000,
    marginRate: 20,
    salesPrice: 9600,
    safetyStock: 30,
    leadTime: 3,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-049',
    itemCode: '절단석-Φ180mm',
    itemName: '절단석',
    itemType: 'CS',
    unit: 'EA',
    specification: 'Φ180mm',
    isVariableSize: false,
    purchasePrice: 1500,
    marginRate: 25,
    salesPrice: 1875,
    safetyStock: 100,
    leadTime: 3,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-050',
    itemCode: '연마석-Φ180mm',
    itemName: '연마석',
    itemType: 'CS',
    unit: 'EA',
    specification: 'Φ180mm',
    isVariableSize: false,
    purchasePrice: 2000,
    marginRate: 25,
    salesPrice: 2500,
    safetyStock: 100,
    leadTime: 3,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-051',
    itemCode: '분체도료-폴리에스터 화이트',
    itemName: '분체도료',
    itemType: 'CS',
    unit: 'KG',
    specification: '폴리에스터 화이���',
    isVariableSize: false,
    purchasePrice: 15000,
    marginRate: 20,
    salesPrice: 18000,
    safetyStock: 100,
    leadTime: 7,
    createdAt: '2025-10-29'
  },
  {
    id: 'ITEM-052',
    itemCode: '신너-락카용',
    itemName: '신너',
    itemType: 'CS',
    unit: 'L',
    specification: '락카용',
    isVariableSize: false,
    purchasePrice: 5000,
    marginRate: 20,
    salesPrice: 6000,
    safetyStock: 50,
    leadTime: 3,
    createdAt: '2025-10-29'
  },
  
  // 추가 스크린 제품
  {
    id: 'ITEM-105',
    itemCode: '스크린 셔터-컴팩트',
    itemName: '스크린 셔터 (컴팩트)',
    itemType: 'FG',
    productCategory: 'SCREEN',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 80000,
    installCost: 40000,
    marginRate: 28,
    salesPrice: 350000,
    safetyStock: 15,
    leadTime: 10,
    createdAt: '2025-01-18',
    bom: [
      {
        id: 'BOM-105-1',
        childItemCode: '모터-1HP 220V',
        childItemName: '모터',
        quantity: 1,
        unit: 'EA',
        unitPrice: 80000,
        note: '고정 수량'
      },
      {
        id: 'BOM-105-2',
        childItemCode: '가이드레일-EGI 1.6T',
        childItemName: '가이드레일 (EGI)',
        quantity: 1,
        unit: 'M',
        unitPrice: 2500,
        quantityFormula: '(W + H) * 1.5',
        note: '(폭+높이) x 1.5'
      },
      {
        id: 'BOM-105-3',
        childItemCode: '알루미늄 압출재-6063-T5',
        childItemName: '알루미늄 압출재',
        quantity: 1,
        unit: 'M',
        unitPrice: 8000,
        quantityFormula: 'W + H',
        note: '폭+높이'
      }
    ]
  },
  // 추가 철재 제품
  {
    id: 'ITEM-210',
    itemCode: '철재 방화셔터-방화등급',
    itemName: '철재 방화셔터',
    itemType: 'FG',
    productCategory: 'STEEL',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 200000,
    installCost: 120000,
    marginRate: 38,
    salesPrice: 950000,
    safetyStock: 2,
    leadTime: 28,
    createdAt: '2025-01-18',
    bom: [
      {
        id: 'BOM-210-1',
        childItemCode: '모터-1HP 220V',
        childItemName: '모터',
        quantity: 2,
        unit: 'EA',
        unitPrice: 80000,
        note: '고정 수량 (방화용 듀얼)'
      },
      {
        id: 'BOM-210-2',
        childItemCode: '가이드레일-SUS 1.2T',
        childItemName: '가이드레일 (SUS)',
        quantity: 1,
        unit: 'M',
        unitPrice: 3000,
        quantityFormula: '(W + H) * 2.5',
        note: '(폭+높이) x 2.5'
      },
      {
        id: 'BOM-210-3',
        childItemCode: 'SUS 강판-SUS304 1.2T',
        childItemName: 'SUS 강판',
        quantity: 1,
        unit: 'KG',
        unitPrice: 5000,
        quantityFormula: 'W * H / 1000 * 9',
        note: '면적 대비 중량 (방화등급)'
      }
    ]
  },
  // 추가 스크린 제품 2
  {
    id: 'ITEM-103',
    itemCode: '스크린 셔터-프리미엄B',
    itemName: '스크린 셔터 (프리미엄)',
    itemType: 'FG',
    productCategory: 'SCREEN',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 120000,
    installCost: 60000,
    marginRate: 32,
    salesPrice: 580000,
    safetyStock: 8,
    leadTime: 12,
    createdAt: '2025-01-19'
  },
  {
    id: 'ITEM-104',
    itemCode: '스크린 자동셔터-IoT형',
    itemName: '스크린 자동셔터',
    itemType: 'FG',
    productCategory: 'SCREEN',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 150000,
    installCost: 80000,
    marginRate: 35,
    salesPrice: 680000,
    safetyStock: 5,
    leadTime: 15,
    createdAt: '2025-01-19'
  },
  // 추가 철재 제품 2
  {
    id: 'ITEM-211',
    itemCode: '철재 셔터-컴팩트',
    itemName: '철재 셔터 (컴팩트)',
    itemType: 'FG',
    productCategory: 'STEEL',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 140000,
    installCost: 70000,
    marginRate: 32,
    salesPrice: 620000,
    safetyStock: 5,
    leadTime: 18,
    createdAt: '2025-01-19'
  },
  {
    id: 'ITEM-204',
    itemCode: '철재 보안셔터-강화형',
    itemName: '철재 보안셔터',
    itemType: 'FG',
    productCategory: 'STEEL',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 220000,
    installCost: 110000,
    marginRate: 40,
    salesPrice: 1050000,
    safetyStock: 2,
    leadTime: 25,
    createdAt: '2025-01-19'
  },
  
  // 견적산출용 샘플 제품
  {
    id: 'SAMPLE-001',
    itemCode: '견적산출용 샘플1',
    itemName: '견적산출용 샘플1',
    itemType: 'FG',
    productCategory: 'SCREEN',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 100000,
    installCost: 50000,
    marginRate: 30,
    salesPrice: 450000,
    safetyStock: 10,
    leadTime: 14,
    createdAt: '2025-10-31',
    bomCategories: ['motor', 'guide-rail', 'case', 'bottom-bar', 'smoke-barrier'],
    bom: [
      { id: 'BOM-S1-1', childItemCode: '모터-1HP 220V', childItemName: '모터', quantity: 1, unit: 'EA', unitPrice: 80000, note: '고정 수량' },
      { id: 'BOM-S1-2', childItemCode: '가이드레일-SUS 1.2T', childItemName: '가이드레일', quantity: 1, unit: 'M', unitPrice: 3000, quantityFormula: '(W1 + H1) / 500', note: '(폭+높이)/500' },
      { id: 'BOM-S1-3', childItemCode: '케이스판재-AL 1.0T', childItemName: '케이스판재', quantity: 2, unit: 'EA', unitPrice: 15000, note: '고정 수량' },
      { id: 'BOM-S1-4', childItemCode: '하단마감재-PVC', childItemName: '하단마감재', quantity: 1, unit: 'M', unitPrice: 8000, quantityFormula: 'W1 / 1000', note: '폭/1000' },
      { id: 'BOM-S1-5', childItemCode: '연기차단재-실리콘', childItemName: '연기차단재', quantity: 1, unit: 'M', unitPrice: 5000, quantityFormula: '(W1 + H1) / 500', note: '(폭+높이)/500' },
      { id: 'BOM-S1-6', childItemCode: '환봉-SUS Ø12', childItemName: '환봉', quantity: 2, unit: 'M', unitPrice: 6000, quantityFormula: 'W1 / 1000 * 2', note: '폭/1000*2개' },
      { id: 'BOM-S1-7', childItemCode: '각파이프-25x25x1.5T', childItemName: '각파이프', quantity: 1, unit: 'M', unitPrice: 4000, quantityFormula: 'H1 / 500', note: '높이/500' },
      { id: 'BOM-S1-8', childItemCode: '조인트바-AL 40x20', childItemName: '조인트바', quantity: 1, unit: 'M', unitPrice: 7000, quantityFormula: 'W1 / 1000 * 1.1', note: '폭/1000*1.1 (여유)' }
    ]
  },
  {
    id: 'SAMPLE-002',
    itemCode: '견적산출용 샘플2',
    itemName: '견적산출용 샘플2',
    itemType: 'FG',
    productCategory: 'SCREEN',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 120000,
    installCost: 60000,
    marginRate: 32,
    salesPrice: 520000,
    safetyStock: 8,
    leadTime: 16,
    createdAt: '2025-10-31',
    bomCategories: ['winding-shaft', 'square-pipe', 'round-bar', 'guide-rail', 'motor'],
    bom: [
      { id: 'BOM-S2-1', childItemCode: '감기샤프트-AL Ø60', childItemName: '감기샤프트', quantity: 1, unit: 'M', unitPrice: 12000, quantityFormula: 'W1 / 1000', note: '폭/1000' },
      { id: 'BOM-S2-2', childItemCode: '각파이프-25x25x1.5T', childItemName: '각파이프', quantity: 2, unit: 'M', unitPrice: 4000, quantityFormula: 'H1 / 500 * 2', note: '높이/500*2개' },
      { id: 'BOM-S2-3', childItemCode: '환봉-SUS Ø12', childItemName: '환봉', quantity: 1, unit: 'M', unitPrice: 6000, quantityFormula: 'W1 / 1000', note: '폭/1000' },
      { id: 'BOM-S2-4', childItemCode: '가이드레일-EGI 1.6T', childItemName: '가이드레일', quantity: 1, unit: 'M', unitPrice: 2500, quantityFormula: '(W1 + H1) / 500', note: '(폭+높이)/500' },
      { id: 'BOM-S2-5', childItemCode: '모터-1HP 220V', childItemName: '모터', quantity: 1, unit: 'EA', unitPrice: 80000, note: '고정 수량' },
      { id: 'BOM-S2-6', childItemCode: '케이스판재-AL 1.0T', childItemName: '케이스판재', quantity: 1, unit: 'EA', unitPrice: 15000, note: '고정 수량' },
      { id: 'BOM-S2-7', childItemCode: '하단마감재-PVC', childItemName: '하단마감재', quantity: 1, unit: 'M', unitPrice: 8000, quantityFormula: 'W1 / 1000 * 1.05', note: '폭/1000*1.05 (여유)' },
      { id: 'BOM-S2-8', childItemCode: '조인트바-AL 40x20', childItemName: '조인트바', quantity: 3, unit: 'M', unitPrice: 7000, quantityFormula: 'W1 / 1000 * 0.3', note: '폭/1000*0.3' }
    ]
  },
  {
    id: 'SAMPLE-003',
    itemCode: '견적산출용 샘플3',
    itemName: '견적산출용 샘플3',
    itemType: 'FG',
    productCategory: 'STEEL',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 150000,
    installCost: 80000,
    marginRate: 35,
    salesPrice: 600000,
    safetyStock: 5,
    leadTime: 18,
    createdAt: '2025-10-31',
    bomCategories: ['joint-bar', 'smoke-barrier', 'case', 'motor', 'bottom-bar'],
    bom: [
      { id: 'BOM-S3-1', childItemCode: '조인트바-AL 40x20', childItemName: '조인트바', quantity: 2, unit: 'M', unitPrice: 7000, quantityFormula: 'W1 / 1000 * 2', note: '폭/1000*2개' },
      { id: 'BOM-S3-2', childItemCode: '연기차단재-실리콘', childItemName: '연기차단재', quantity: 1, unit: 'M', unitPrice: 5000, quantityFormula: '(W1 + H1) / 500', note: '(폭+높이)/500' },
      { id: 'BOM-S3-3', childItemCode: '케이스판재-AL 1.0T', childItemName: '케이스판재', quantity: 3, unit: 'EA', unitPrice: 15000, note: '고정 수량 3개' },
      { id: 'BOM-S3-4', childItemCode: '모터-1HP 220V', childItemName: '모터', quantity: 1, unit: 'EA', unitPrice: 80000, note: '고정 수량' },
      { id: 'BOM-S3-5', childItemCode: '하단마감재-PVC', childItemName: '하단마감재', quantity: 1, unit: 'M', unitPrice: 8000, quantityFormula: 'W1 / 1000', note: '폭/1000' },
      { id: 'BOM-S3-6', childItemCode: '가이드레일-SUS 1.2T', childItemName: '가이드레일', quantity: 1, unit: 'M', unitPrice: 3000, quantityFormula: '(W1 + H1) / 500 * 1.2', note: '(폭+높이)/500*1.2' },
      { id: 'BOM-S3-7', childItemCode: '감기샤프트-AL Ø60', childItemName: '감기샤프트', quantity: 1, unit: 'M', unitPrice: 12000, quantityFormula: 'W1 / 1000 * 1.1', note: '폭/1000*1.1 (여유)' },
      { id: 'BOM-S3-8', childItemCode: '환봉-SUS Ø12', childItemName: '환봉', quantity: 4, unit: 'M', unitPrice: 6000, quantityFormula: 'H1 / 500 * 0.5', note: '높이/500*0.5' }
    ]
  },
  {
    id: 'SAMPLE-004',
    itemCode: '견적산출용 샘플4',
    itemName: '견적산출용 샘플4',
    itemType: 'FG',
    productCategory: 'STEEL',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 180000,
    installCost: 100000,
    marginRate: 38,
    salesPrice: 750000,
    safetyStock: 3,
    leadTime: 21,
    createdAt: '2025-10-31',
    bomCategories: ['guide-rail', 'winding-shaft', 'case', 'square-pipe', 'joint-bar'],
    bom: [
      { id: 'BOM-S4-1', childItemCode: '가이드레일-SUS 1.2T', childItemName: '가이드레일', quantity: 2, unit: 'M', unitPrice: 3000, quantityFormula: '(W1 + H1) / 500 * 2', note: '(폭+높이)/500*2개' },
      { id: 'BOM-S4-2', childItemCode: '감기샤프트-AL Ø60', childItemName: '감기샤프트', quantity: 1, unit: 'M', unitPrice: 12000, quantityFormula: 'W1 / 1000', note: '폭/1000' },
      { id: 'BOM-S4-3', childItemCode: '케이스판재-AL 1.0T', childItemName: '케이스판재', quantity: 2, unit: 'EA', unitPrice: 15000, note: '고정 수량 2개' },
      { id: 'BOM-S4-4', childItemCode: '각파이프-25x25x1.5T', childItemName: '각파이프', quantity: 3, unit: 'M', unitPrice: 4000, quantityFormula: 'H1 / 500 * 1.5', note: '높이/500*1.5' },
      { id: 'BOM-S4-5', childItemCode: '조인트바-AL 40x20', childItemName: '조인트바', quantity: 2, unit: 'M', unitPrice: 7000, quantityFormula: 'W1 / 1000 * 2', note: '폭/1000*2개' },
      { id: 'BOM-S4-6', childItemCode: '모터-1HP 220V', childItemName: '모터', quantity: 1, unit: 'EA', unitPrice: 80000, note: '고정 수량' },
      { id: 'BOM-S4-7', childItemCode: '연기차단재-실리콘', childItemName: '연기차단재', quantity: 1, unit: 'M', unitPrice: 5000, quantityFormula: '(W1 + H1) / 500 * 1.3', note: '(폭+높이)/500*1.3' },
      { id: 'BOM-S4-8', childItemCode: '환봉-SUS Ø12', childItemName: '환봉', quantity: 2, unit: 'M', unitPrice: 6000, quantityFormula: 'W1 / 1000 * 2.2', note: '폭/1000*2.2' }
    ]
  },
  {
    id: 'SAMPLE-005',
    itemCode: '견적산출용 샘플5',
    itemName: '견적산출용 샘플5',
    itemType: 'FG',
    productCategory: 'SCREEN',
    unit: 'SET',
    isVariableSize: true,
    laborCost: 110000,
    installCost: 55000,
    marginRate: 30,
    salesPrice: 480000,
    safetyStock: 7,
    leadTime: 15,
    createdAt: '2025-10-31',
    bomCategories: ['motor', 'round-bar', 'bottom-bar', 'smoke-barrier', 'winding-shaft'],
    bom: [
      { id: 'BOM-S5-1', childItemCode: '모터-1HP 220V', childItemName: '모터', quantity: 1, unit: 'EA', unitPrice: 80000, note: '고정 수량' },
      { id: 'BOM-S5-2', childItemCode: '환봉-SUS Ø12', childItemName: '환봉', quantity: 3, unit: 'M', unitPrice: 6000, quantityFormula: 'W1 / 1000 * 1.5', note: '폭/1000*1.5' },
      { id: 'BOM-S5-3', childItemCode: '하단마감재-PVC', childItemName: '하단마감재', quantity: 1, unit: 'M', unitPrice: 8000, quantityFormula: 'W1 / 1000', note: '폭/1000' },
      { id: 'BOM-S5-4', childItemCode: '연기차단재-실리콘', childItemName: '연기차단재', quantity: 1, unit: 'M', unitPrice: 5000, quantityFormula: '(W1 + H1) / 500 * 1.1', note: '(폭+높이)/500*1.1' },
      { id: 'BOM-S5-5', childItemCode: '감기샤프트-AL Ø60', childItemName: '감기샤프트', quantity: 1, unit: 'M', unitPrice: 12000, quantityFormula: 'W1 / 1000 * 1.05', note: '폭/1000*1.05 (여유)' },
      { id: 'BOM-S5-6', childItemCode: '가이드레일-EGI 1.6T', childItemName: '가이드레일', quantity: 2, unit: 'M', unitPrice: 2500, quantityFormula: '(W1 + H1) / 500 * 2', note: '(폭+높이)/500*2개' },
      { id: 'BOM-S5-7', childItemCode: '각파이프-25x25x1.5T', childItemName: '각파이프', quantity: 2, unit: 'M', unitPrice: 4000, quantityFormula: 'H1 / 500 * 2', note: '높이/500*2개' },
      { id: 'BOM-S5-8', childItemCode: '조인트바-AL 40x20', childItemName: '조인트바', quantity: 1, unit: 'M', unitPrice: 7000, quantityFormula: 'W1 / 1000', note: '폭/1000' }
    ]
  }
];

const initialFormulas: CalculationFormula[] = [
  {
    id: 'FORM-001',
    formulaCode: 'FORM-001',
    formulaName: '프레임 둘레 계산',
    category: '공통',
    formula: '(W + H) * 2',
    description: '폭과 높이의 합 x 2 (프레임 둘레)',
    variables: ['W', 'H'],
    unit: 'mm',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-01-10',
    createdBy: '시스템'
  },
  {
    id: 'FORM-002',
    formulaCode: 'FORM-002',
    formulaName: '프레임 둘레 계산 (1.5배)',
    category: '스크린',
    formula: '(W + H) * 1.5',
    description: '폭과 높이의 합 x 1.5 (스크린 프레임용)',
    variables: ['W', 'H'],
    unit: 'mm',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-01-10',
    createdBy: '시스템'
  },
  {
    id: 'FORM-003',
    formulaCode: 'FORM-003',
    formulaName: '프레임 둘레 계산 (3배)',
    category: '스크린',
    formula: '(W + H) * 3',
    description: '폭과 높이의 합 x 3 (강화 프레임용)',
    variables: ['W', 'H'],
    unit: 'mm',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-01-10',
    createdBy: '시스템'
  },
  {
    id: 'FORM-004',
    formulaCode: 'FORM-004',
    formulaName: '폭 양쪽 레일',
    category: '철재',
    formula: 'W * 2',
    description: '폭 x 2 (양쪽 가이드레일)',
    variables: ['W'],
    unit: 'mm',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-01-10',
    createdBy: '시스템'
  },
  {
    id: 'FORM-005',
    formulaCode: 'FORM-005',
    formulaName: '면적 대비 중량 (EGI)',
    category: '철재',
    formula: 'W * H / 1000 * 5',
    description: '면적 대비 중량 계산 (EGI 강판)',
    variables: ['W', 'H'],
    unit: 'KG',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-01-10',
    createdBy: '시스템'
  },
  {
    id: 'FORM-006',
    formulaCode: 'FORM-006',
    formulaName: '면적 대비 중량 (SUS)',
    category: '철재',
    formula: 'W * H / 1000 * 7',
    description: '면적 대비 중량 계산 (SUS 강판)',
    variables: ['W', 'H'],
    unit: 'KG',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-01-10',
    createdBy: '시스템'
  }
];

const initialFormulaRules: FormulaRule[] = [
  // === 기본 산출 (제작사이즈, 면적, 중량) ===
  
  // W1 (제작폭) 계산 - 스크린 (실리카/와이어)
  {
    id: 'RULE-BASIC-001',
    ruleCode: 'W1-CALCULATION-SCREEN',
    ruleName: '제작폭(W1) 계산 - 스크린',
    category: '스크린',
    inputVariable: 'W0',
    ruleType: 'formula',
    formula: 'W0 + 140',
    unit: 'mm',
    description: '스크린(실리카/와이어) 제작폭 = 오픈사이즈 W0 + 140mm',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // W1 (제작폭) 계산 - 철재
  {
    id: 'RULE-BASIC-002',
    ruleCode: 'W1-CALCULATION-STEEL',
    ruleName: '제작폭(W1) 계산 - 철재',
    category: '철재',
    inputVariable: 'W0',
    ruleType: 'formula',
    formula: 'W0 + 110',
    unit: 'mm',
    description: '철재 셔터 제작폭 = 오픈사이즈 W0 + 110mm',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // H1 (제작높이) 계산 - 스크린
  {
    id: 'RULE-BASIC-003',
    ruleCode: 'H1-CALCULATION-SCREEN',
    ruleName: '제작높이(H1) 계산 - 스크린',
    category: '스크린',
    inputVariable: 'H0',
    ruleType: 'formula',
    formula: 'H0 + 350',
    unit: 'mm',
    description: '스크린 제작높이 = 오픈사이즈 H0 + 350mm (일부 케이스는 고정값 900 사용)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // H1 (제작높이) 계산 - 철재
  {
    id: 'RULE-BASIC-004',
    ruleCode: 'H1-CALCULATION-STEEL',
    ruleName: '제작높이(H1) 계산 - 철재',
    category: '철재',
    inputVariable: 'H0',
    ruleType: 'formula',
    formula: 'H0 + 350',
    unit: 'mm',
    description: '철재 셔터 제작높이 = 오픈사이즈 H0 + 350mm',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 면적(M) 계산
  {
    id: 'RULE-BASIC-005',
    ruleCode: 'AREA-CALCULATION',
    ruleName: '면적(M) 계산',
    category: '공통',
    inputVariable: 'W1,H1',
    ruleType: 'formula',
    formula: '(W1 * H1) / 1000000',
    unit: 'm²',
    description: '면적(M) = W1 × H1 ÷ 1,000,000',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 중량(K) 계산 - 스크린
  {
    id: 'RULE-BASIC-006',
    ruleCode: 'WEIGHT-CALCULATION-SCREEN',
    ruleName: '중량(K) 계산 - 스크린',
    category: '스크린',
    inputVariable: 'M,W0',
    ruleType: 'formula',
    formula: '(M * 2) + (W0 * 14.17 / 1000)',
    unit: 'kg',
    description: '스크린 중량(K) = (M × 2) + (W0 × 14.17 ÷ 1000)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 중량(K) 계산 - 철재
  {
    id: 'RULE-BASIC-007',
    ruleCode: 'WEIGHT-CALCULATION-STEEL',
    ruleName: '중량(K) 계산 - 철재',
    category: '철재',
    inputVariable: 'M',
    ruleType: 'formula',
    formula: 'M * 25',
    unit: 'kg',
    description: '철재 중량(K) = M × 25',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // === 산출 기준 (범위 조건) ===
  
  // 1. 케이스판재 선택 기준 (제작사이즈 S 기준)
  {
    id: 'RULE-001',
    ruleCode: 'CASE-PLATE',
    ruleName: '케이스판재 선택',
    category: '스크린',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 1219, result: '1219', description: '1219 이하' },
      { id: 'R2', minValue: 1219, maxValue: 2438, result: '2438', description: '1219 초과 2438 이하' },
      { id: 'R3', minValue: 2438, maxValue: 3050, result: '3050', description: '2438 초과 3050 이하' },
      { id: 'R4', minValue: 3050, maxValue: 9999999, result: '특주', description: '3050 초과 (특주 제작)' }
    ],
    unit: 'mm',
    description: '제작사이즈에 따른 케이스판재 규격 선택 기준',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 2. 가이드레일 품목 선택 기준 (중량 기준)
  {
    id: 'RULE-002',
    ruleCode: 'GUIDE-RAIL-TYPE',
    ruleName: '가이드레일 품목 선택',
    category: '공통',
    inputVariable: 'weight',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 30, result: '알루미늄', description: '30kg 이하 (경량)' },
      { id: 'R2', minValue: 30, maxValue: 80, result: 'EGI 1.6T', description: '30~80kg (중량)' },
      { id: 'R3', minValue: 80, maxValue: 9999999, result: 'SUS 1.5T', description: '80kg 초과 (중중량)' }
    ],
    unit: '',
    description: '제품 중량에 따른 가이드레일 품목 선택 기준',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 3. 자재비율 - 스크린용 (면적 기준)
  {
    id: 'RULE-003',
    ruleCode: 'MATERIAL-RATIO-SCREEN',
    ruleName: '자재비율 - 스크린용',
    category: '스크린',
    inputVariable: 'area',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 5, result: '65', description: '5m² 이하' },
      { id: 'R2', minValue: 5, maxValue: 10, result: '60', description: '5~10m²' },
      { id: 'R3', minValue: 10, maxValue: 20, result: '55', description: '10~20m²' },
      { id: 'R4', minValue: 20, maxValue: 9999999, result: '50', description: '20m² 초과' }
    ],
    unit: '%',
    description: '면적 범위별 자재비 비율 (총 원가 대비)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 4. 자재비율 - 철재용 (면적 기준)
  {
    id: 'RULE-004',
    ruleCode: 'MATERIAL-RATIO-STEEL',
    ruleName: '자재비율 - 철재용',
    category: '철재',
    inputVariable: 'area',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 5, result: '70', description: '5m² 이하' },
      { id: 'R2', minValue: 5, maxValue: 10, result: '68', description: '5~10m²' },
      { id: 'R3', minValue: 10, maxValue: 20, result: '65', description: '10~20m²' },
      { id: 'R4', minValue: 20, maxValue: 9999999, result: '62', description: '20m² 초과' }
    ],
    unit: '%',
    description: '면적 범위별 자재비 비율 (철재는 스크린보다 자재비 높음)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 5. 도장비율 (면적 기준)
  {
    id: 'RULE-005',
    ruleCode: 'PAINT-RATIO',
    ruleName: '도장비율',
    category: '공통',
    inputVariable: 'area',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 5, result: '15', description: '5m² 이하' },
      { id: 'R2', minValue: 5, maxValue: 10, result: '12', description: '5~10m²' },
      { id: 'R3', minValue: 10, maxValue: 20, result: '10', description: '10~20m²' },
      { id: 'R4', minValue: 20, maxValue: 9999999, result: '8', description: '20m² 초과' }
    ],
    unit: '%',
    description: '면적 범위별 도장비 비율 (총 원가 대비)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  
  // === 산출 수식 (계산식) ===
  
  // 6. 가이드레일 제작길이 계산 (G)
  {
    id: 'RULE-006',
    ruleCode: 'GR-LENGTH',
    ruleName: '가이드레일 제작길이 (G)',
    category: '공통',
    inputVariable: 'H0',
    ruleType: 'formula',
    formula: 'H0 + 250',
    unit: 'mm',
    description: '오픈사이즈 세로값(H0) + 250mm (가이드레일 제작길이, 기본 2량=1SET)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 7. 슬랫 수량 계산
  {
    id: 'RULE-007',
    ruleCode: 'SLAT-QTY',
    ruleName: '슬랫 수량',
    category: '철재',
    inputVariable: 'H1',
    ruleType: 'formula',
    formula: 'CEIL(H1 / 150)',
    unit: '개',
    description: '높이를 150mm(슬랫 1개 높이)로 나눈 후 올림',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 8. 케이스세로대 수량
  {
    id: 'RULE-008',
    ruleCode: 'CASE-VERTICAL',
    ruleName: '케이스세로대 수량',
    category: '스크린',
    inputVariable: 'W1',
    ruleType: 'formula',
    formula: 'IF(W1 <= 1219, 2, 2 + CEIL((W1 - 1219) / 1000))',
    unit: '개',
    description: '기본 2개 + 1m당 1개 추가',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 9. 케이스가로대 수량
  {
    id: 'RULE-009',
    ruleCode: 'CASE-HORIZONTAL',
    ruleName: '케이스가로대 수량',
    category: '스크린',
    inputVariable: 'H1',
    ruleType: 'formula',
    formula: 'CEIL(H1 / 3000) * 2',
    unit: '개',
    description: '높이 3m당 상하 2개씩',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 10. 브라켓 수량
  {
    id: 'RULE-010',
    ruleCode: 'BRACKET-QTY',
    ruleName: '브라켓 수량',
    category: '공통',
    inputVariable: 'W1',
    ruleType: 'formula',
    formula: 'IF(W1 <= 3000, 4, IF(W1 <= 6000, 6, CEIL(W1 / 1000)))',
    unit: '개',
    description: '3m 이하 4개, 6m 이하 6개, 이상은 1m당 1개',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 11. 체인 길이
  {
    id: 'RULE-011',
    ruleCode: 'CHAIN-LENGTH',
    ruleName: '체인 길이',
    category: '공통',
    inputVariable: 'H1',
    ruleType: 'formula',
    formula: '(H1 / 1000) * 2 * 1.1',
    unit: 'm',
    description: '높이 × 2 (왕복) × 1.1 (여유)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 12. 원단 면적
  {
    id: 'RULE-012',
    ruleCode: 'FABRIC-AREA',
    ruleName: '원단 면적',
    category: '스크린',
    inputVariable: 'area',
    ruleType: 'formula',
    formula: 'area * 1.15',
    unit: 'm²',
    description: '제작면적 × 1.15 (15% 여유)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 13. 도장 면적
  {
    id: 'RULE-013',
    ruleCode: 'PAINT-AREA',
    ruleName: '도장 면적',
    category: '공통',
    inputVariable: 'area',
    ruleType: 'formula',
    formula: 'area * 2.2',
    unit: 'm²',
    description: '제작면적 × 2.2 (양면 + 측면)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 14. 가공비 기본
  {
    id: 'RULE-014',
    ruleCode: 'PROCESS-COST-BASE',
    ruleName: '가공비 기본',
    category: '공통',
    inputVariable: 'area',
    ruleType: 'formula',
    formula: 'area * 35000',
    unit: '원',
    description: 'm²당 35,000원 (절곡, 용접, 조립 포함)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 15. 감기샤프트 길이
  {
    id: 'RULE-015',
    ruleCode: 'WINDING-SHAFT',
    ruleName: '감기샤프트 길이',
    category: '공통',
    inputVariable: 'W1',
    ruleType: 'formula',
    formula: '(W1 / 1000) + 0.2',
    unit: 'm',
    description: '제작폭 + 0.2m (양쪽 여유)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 16. 하단바 길이
  {
    id: 'RULE-016',
    ruleCode: 'BOTTOM-BAR',
    ruleName: '하단바 길이',
    category: '공통',
    inputVariable: 'W1',
    ruleType: 'formula',
    formula: 'W1 / 1000',
    unit: 'm',
    description: '제작폭과 동일',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  
  // === 모터 용량 산정 기준 ===
  // 샤프트별 중량 범위에 따른 모터 용량 자동 매칭 기준
  
  // 17. 모터 용량 - 스크린 4" 샤프트
  {
    id: 'RULE-017',
    ruleCode: 'MOTOR-SCREEN-4',
    ruleName: '모터 용량 - 스크린 4"',
    category: '스크린',
    inputVariable: 'weight',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 123, result: '모터 150K', itemCode: 'MOTOR-150K', itemName: '모터 150K', quantity: 1, description: '0~123kg → 150K' },
      { id: 'R2', minValue: 123, maxValue: 208, result: '모터 300K', itemCode: 'MOTOR-300K', itemName: '모터 300K', quantity: 1, description: '124~208kg → 300K' }
    ],
    unit: '',
    description: '스크린 제품 4" 샤프트 중량별 모터 용량 산정',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 18. 모터 용량 - 스크린 5" 샤프트
  {
    id: 'RULE-018',
    ruleCode: 'MOTOR-SCREEN-5',
    ruleName: '모터 용량 - 스크린 5"',
    category: '스크린',
    inputVariable: 'weight',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 150, result: '모터 150K', itemCode: 'MOTOR-150K', itemName: '모터 150K', quantity: 1, description: '0~150kg → 150K' },
      { id: 'R2', minValue: 150, maxValue: 246, result: '모터 300K', itemCode: 'MOTOR-300K', itemName: '모터 300K', quantity: 1, description: '151~246kg → 300K' },
      { id: 'R3', minValue: 246, maxValue: 277, result: '모터 400K', itemCode: 'MOTOR-400K', itemName: '모터 400K', quantity: 1, description: '247~277kg → 400K' }
    ],
    unit: '',
    description: '스크린 제품 5" 샤프트 중량별 모터 용량 산정',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 19. 모터 용량 - 스크린 6" 샤프트
  {
    id: 'RULE-019',
    ruleCode: 'MOTOR-SCREEN-6',
    ruleName: '모터 용량 - 스크린 6"',
    category: '스크린',
    inputVariable: 'weight',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 208, result: '모터 150K', itemCode: 'MOTOR-150K', itemName: '모터 150K', quantity: 1, description: '0~208kg → 150K' },
      { id: 'R2', minValue: 208, maxValue: 246, result: '모터 300K', itemCode: 'MOTOR-300K', itemName: '모터 300K', quantity: 1, description: '209~246kg → 300K' },
      { id: 'R3', minValue: 246, maxValue: 324, result: '모터 400K', itemCode: 'MOTOR-400K', itemName: '모터 400K', quantity: 1, description: '247~324kg → 400K' },
      { id: 'R4', minValue: 324, maxValue: 388, result: '모터 500K', itemCode: 'MOTOR-500K', itemName: '모터 500K', quantity: 1, description: '325~388kg → 500K' },
      { id: 'R5', minValue: 388, maxValue: 494, result: '모터 800K', itemCode: 'MOTOR-800K', itemName: '모터 800K', quantity: 1, description: '389~494kg → 600K' }
    ],
    unit: '',
    description: '스크린 제품 6" 샤프트 중량별 모터 용량 산정',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 20. 모터 용량 - 철재 4" 샤프트
  {
    id: 'RULE-020',
    ruleCode: 'MOTOR-STEEL-4',
    ruleName: '모터 용량 - 철재 4"',
    category: '철재',
    inputVariable: 'weight',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 277, result: '모터 300K', itemCode: 'MOTOR-300K', itemName: '모터 300K', quantity: 1, description: '0~277kg → 300K' },
      { id: 'R2', minValue: 277, maxValue: 327, result: '모터 400K', itemCode: 'MOTOR-400K', itemName: '모터 400K', quantity: 1, description: '278~327kg → 400K' },
      { id: 'R3', minValue: 327, maxValue: 400, result: '모터 500K', itemCode: 'MOTOR-500K', itemName: '모터 500K', quantity: 1, description: '328~400kg → 500K' }
    ],
    unit: '',
    description: '철재 제품 4" 샤프트 중량별 모터 용량 산정',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 21. 모터 용량 - 철재 5" 샤프트
  {
    id: 'RULE-021',
    ruleCode: 'MOTOR-STEEL-5',
    ruleName: '모터 용량 - 철재 5"',
    category: '철재',
    inputVariable: 'weight',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 300, result: '모터 300K', itemCode: 'MOTOR-300K', itemName: '모터 300K', quantity: 1, description: '0~300kg → 300K' },
      { id: 'R2', minValue: 300, maxValue: 424, result: '모터 400K', itemCode: 'MOTOR-400K', itemName: '모터 400K', quantity: 1, description: '301~424kg → 400K' },
      { id: 'R3', minValue: 424, maxValue: 600, result: '모터 500K', itemCode: 'MOTOR-500K', itemName: '모터 500K', quantity: 1, description: '425~600kg → 500K' }
    ],
    unit: '',
    description: '철재 제품 5" 샤프트 중량별 모터 용량 산정',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 22. 모터 용량 - 철재 6" 샤프트
  {
    id: 'RULE-022',
    ruleCode: 'MOTOR-STEEL-6',
    ruleName: '모터 용량 - 철재 6"',
    category: '철재',
    inputVariable: 'weight',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 327, result: '모터 300K', itemCode: 'MOTOR-300K', itemName: '모터 300K', quantity: 1, description: '0~327kg → 300K' },
      { id: 'R2', minValue: 327, maxValue: 494, result: '모터 400K', itemCode: 'MOTOR-400K', itemName: '모터 400K', quantity: 1, description: '328~494kg → 400K' },
      { id: 'R3', minValue: 494, maxValue: 600, result: '모터 500K', itemCode: 'MOTOR-500K', itemName: '모터 500K', quantity: 1, description: '495~600kg → 500K' },
      { id: 'R4', minValue: 600, maxValue: 800, result: '모터 800K', itemCode: 'MOTOR-800K', itemName: '모터 800K', quantity: 1, description: '601~800kg → 600K' }
    ],
    unit: '',
    description: '철재 제품 6" 샤프트 중량별 모터 용량 산정',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 23. 모터 용량 - 철재 8" 샤프트
  {
    id: 'RULE-023',
    ruleCode: 'MOTOR-STEEL-8',
    ruleName: '모터 용량 - 철재 8"',
    category: '철재',
    inputVariable: 'weight',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 0, maxValue: 600, result: '모터 500K', itemCode: 'MOTOR-500K', itemName: '모터 500K', quantity: 1, description: '0~600kg → 500K' },
      { id: 'R2', minValue: 600, maxValue: 800, result: '모터 800K', itemCode: 'MOTOR-800K', itemName: '모터 800K', quantity: 1, description: '601~800kg → 800K' },
      { id: 'R3', minValue: 800, maxValue: 1000, result: '모터 1000K', itemCode: 'MOTOR-1000K', itemName: '모터 1000K', quantity: 1, description: '801~1000kg → 1000K' }
    ],
    unit: '',
    description: '철재 제품 8" 샤프트 중량별 모터 용량 산정',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // === 기타 산출 수식 ===
  
  // 24. 각파이프 총 길이
  {
    id: 'RULE-024',
    ruleCode: 'SQUARE-PIPE-TOTAL',
    ruleName: '각파이프 총 길이',
    category: '철재',
    inputVariable: 'W1',
    ruleType: 'formula',
    formula: '((W1 / 1000) + (H1 / 1000)) * 2',
    unit: 'm',
    description: '(폭 + 높이) × 2 (프레임 둘레)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // === 가이드레일 자재 적용 기준 (1SET = 2량 기준) ===
  
  // 25. 가이드레일 자재 - 1219~2438mm 구간
  {
    id: 'RULE-025',
    ruleCode: 'GR-MATERIAL-2438',
    ruleName: '가이드레일 자재 선택 (2438mm)',
    category: '공통',
    inputVariable: 'G',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 1219, maxValue: 2438, result: '2438×2EA', description: '1219 < G ≤ 2438: 2438mm 2개' }
    ],
    unit: '',
    description: '가이드레일 제작길이(G)가 1219~2438mm 구간 시 2438mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 26. 가이드레일 자재 - 2438~3000mm 구간
  {
    id: 'RULE-026',
    ruleCode: 'GR-MATERIAL-3000-A',
    ruleName: '가이드레일 자재 선택 (3000mm-A)',
    category: '공통',
    inputVariable: 'G',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 2438, maxValue: 3000, result: '3000×2EA', description: '2438 < G ≤ 3000: 3000mm 2개' }
    ],
    unit: '',
    description: '가이드레일 제작길이(G)가 2438~3000mm 구간 시 3000mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 27. 가이드레일 자재 - 3000~3500mm 구간
  {
    id: 'RULE-027',
    ruleCode: 'GR-MATERIAL-3500-A',
    ruleName: '가이드레일 자재 선택 (3500mm-A)',
    category: '공통',
    inputVariable: 'G',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 3000, maxValue: 3500, result: '3500×2EA', description: '3000 < G ≤ 3500: 3500mm 2개' }
    ],
    unit: '',
    description: '가이드레일 제작길이(G)가 3000~3500mm 구간 시 3500mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 28. 가이드레일 자재 - 3500~4000mm 구간
  {
    id: 'RULE-028',
    ruleCode: 'GR-MATERIAL-4000-A',
    ruleName: '가이드레일 자재 선택 (4000mm-A)',
    category: '공통',
    inputVariable: 'G',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 3500, maxValue: 4000, result: '4000×2EA', description: '3500 < G ≤ 4000: 4000mm 2개' }
    ],
    unit: '',
    description: '가이드레일 제작길이(G)가 3500~4000mm 구간 시 4000mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 29. 가이드레일 자재 - 4000~4300mm 구간
  {
    id: 'RULE-029',
    ruleCode: 'GR-MATERIAL-4300-A',
    ruleName: '가이드레일 자재 선택 (4300mm-A)',
    category: '공통',
    inputVariable: 'G',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 4000, maxValue: 4300, result: '4300×2EA', description: '4000 < G ≤ 4300: 4300mm 2개' }
    ],
    unit: '',
    description: '가이드레일 제작길이(G)가 4000~4300mm 구간 시 4300mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 30. 가이드레일 자재 - 4300~5438mm 구간
  {
    id: 'RULE-030',
    ruleCode: 'GR-MATERIAL-MIXED-A',
    ruleName: '가이드레일 자재 선택 (혼합-A)',
    category: '공통',
    inputVariable: 'G',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 4300, maxValue: 5438, result: '2438×2EA + 3000×2EA', description: '4300 < G ≤ 5438: 2438mm 2개 + 3000mm 2개' }
    ],
    unit: '',
    description: '가이드레일 제작길이(G)가 4300~5438mm 구간 시 2438mm 2개 + 3000mm 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 31. 가이드레일 자재 - 5438~6000mm 구간
  {
    id: 'RULE-031',
    ruleCode: 'GR-MATERIAL-3000-B',
    ruleName: '가이드레일 자재 선택 (3000mm-B)',
    category: '공통',
    inputVariable: 'G',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 5438, maxValue: 6000, result: '3000×4EA', description: '5438 < G ≤ 6000: 3000mm 4개' }
    ],
    unit: '',
    description: '가이드레일 제작길이(G)가 5438~6000mm 구간 시 3000mm 자재 4개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 32. 가이드레일 자재 - 6000~6500mm 구간
  {
    id: 'RULE-032',
    ruleCode: 'GR-MATERIAL-4000-B',
    ruleName: '가이드레일 자재 선택 (4000mm-B)',
    category: '공통',
    inputVariable: 'G',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 6000, maxValue: 6500, result: '4000×2EA', description: '6000 < G ≤ 6500: 4000mm 2개' }
    ],
    unit: '',
    description: '가이드레일 제작길이(G)가 6000~6500mm 구간 시 4000mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 33. 가이드레일 자재 - 6500~7000mm 구간
  {
    id: 'RULE-033',
    ruleCode: 'GR-MATERIAL-4300-B',
    ruleName: '가이드레일 자재 선택 (4300mm-B)',
    category: '공통',
    inputVariable: 'G',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 6500, maxValue: 7000, result: '4300×2EA', description: '6500 < G ≤ 7000: 4300mm 2개' }
    ],
    unit: '',
    description: '가이드레일 제작길이(G)가 6500~7000mm 구간 시 4300mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 34. 가이드레일 자재 - 7000~7300mm 구간
  {
    id: 'RULE-034',
    ruleCode: 'GR-MATERIAL-4300-C',
    ruleName: '가이드레일 자재 선택 (4300mm-C)',
    category: '공통',
    inputVariable: 'G',
    ruleType: 'range',
    ranges: [
      { id: 'R1', minValue: 7000, maxValue: 7300, result: '4300×2EA', description: '7000 < G ≤ 7300: 4300mm 2개' }
    ],
    unit: '',
    description: '가이드레일 제작길이(G)가 7000~7300mm 구간 시 4300mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // === 가이드레일 하부BASE 규격 - 스크린용 ===
  
  // 35. 가이드레일 하부BASE - 스크린 벽면형
  {
    id: 'RULE-035',
    ruleCode: 'GR-BASE-SCREEN-WALL',
    ruleName: '가이드레일 하부BASE - 스크린 벽면형',
    category: '스크린',
    inputVariable: 'installType',
    ruleType: 'fixed',
    fixedValue: 0,
    unit: '',
    description: '스크린 벽면형(120×70): 하부BASE1 130×80, 하부BASE2 130×80',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 36. 가이드레일 하부BASE - 스크린 측면형
  {
    id: 'RULE-036',
    ruleCode: 'GR-BASE-SCREEN-SIDE',
    ruleName: '가이드레일 하부BASE - 스크린 측면형',
    category: '스크린',
    inputVariable: 'installType',
    ruleType: 'fixed',
    fixedValue: 0,
    unit: '',
    description: '스크린 측면형(120×120): 하부BASE1 130×130, 하부BASE2 130×130',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 37. 가이드레일 하부BASE - 스크린 혼합형
  {
    id: 'RULE-037',
    ruleCode: 'GR-BASE-SCREEN-MIXED',
    ruleName: '가이드레일 하부BASE - 스크린 혼합형',
    category: '스크린',
    inputVariable: 'installType',
    ruleType: 'fixed',
    fixedValue: 0,
    unit: '',
    description: '스크린 혼합형: 하부BASE1 130×80, 하부BASE2 130×130',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // === 가이드레일 하부BASE 규격 - 철재용 ===
  
  // 38. 가이드레일 하부BASE - 철재 벽면형
  {
    id: 'RULE-038',
    ruleCode: 'GR-BASE-STEEL-WALL',
    ruleName: '가이드레일 하부BASE - 철재 벽면형',
    category: '철재',
    inputVariable: 'installType',
    ruleType: 'fixed',
    fixedValue: 0,
    unit: '',
    description: '철재 벽면형(130×75): 하부BASE1 140×85, 하부BASE2 140×85',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 39. 가이드레일 하부BASE - 철재 측면형
  {
    id: 'RULE-039',
    ruleCode: 'GR-BASE-STEEL-SIDE',
    ruleName: '가이드레일 하부BASE - 철재 측면형',
    category: '철재',
    inputVariable: 'installType',
    ruleType: 'fixed',
    fixedValue: 0,
    unit: '',
    description: '철재 측면형(130×125): 하부BASE1 140×135, 하부BASE2 140×135',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 40. 가이드레일 하부BASE - 철재 혼합형
  {
    id: 'RULE-040',
    ruleCode: 'GR-BASE-STEEL-MIXED',
    ruleName: '가이드레일 하부BASE - 철재 혼합형',
    category: '철재',
    inputVariable: 'installType',
    ruleType: 'fixed',
    fixedValue: 0,
    unit: '',
    description: '철재 혼합형: 하부BASE1 140×85, 하부BASE2 140×135',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // === 연기차단재 산출 기준 ===
  
  // 41. 연기차단재 수량 - 스크린
  {
    id: 'RULE-041',
    ruleCode: 'SMOKE-BARRIER-QTY-SCREEN',
    ruleName: '연기차단재 수량 - 스크린',
    category: '스크린',
    inputVariable: 'category',
    ruleType: 'fixed',
    fixedValue: 2,
    unit: '개/1량',
    description: '스크린: 가이드레일 내부 삽입, 1량당 2개 (1SET = 2량 기준, 총 4개)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 42. 연기차단재 수량 - 철재
  {
    id: 'RULE-042',
    ruleCode: 'SMOKE-BARRIER-QTY-STEEL',
    ruleName: '연기차단재 수량 - 철재',
    category: '철재',
    inputVariable: 'category',
    ruleType: 'fixed',
    fixedValue: 1,
    unit: '개/1량',
    description: '철재: 가이드레일 내부 삽입, 1량당 1개 (1SET = 2량 기준, 총 2개)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // 43. 연기차단재 재단 길이
  {
    id: 'RULE-043',
    ruleCode: 'SMOKE-BARRIER-LENGTH',
    ruleName: '연기차단재 재단 길이',
    category: '공통',
    inputVariable: 'G',
    ruleType: 'formula',
    formula: 'G',
    unit: 'mm',
    description: '가이드레일 1량과 동일한 길이(G)로 재단',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-30',
    updatedAt: '2025-10-30'
  },
  
  // === 케이스(셔터박스) 산출 기준 ===
  
  // 44. 케이스판재/상부덮개 자재 선택 - 0~1219mm
  {
    id: 'RULE-044',
    ruleCode: 'CASE-MATERIAL-1219',
    ruleName: '케이스판재 자재 - 0~1219mm',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { min: 0, max: 1219, result: '1219mm', quantity: 1 }
    ],
    unit: 'mm',
    description: '제작사이즈(S) 0~1219mm: 1219mm 자재 1개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 45. 케이스판재/상부덮개 자재 선택 - 1219~2438mm
  {
    id: 'RULE-045',
    ruleCode: 'CASE-MATERIAL-2438',
    ruleName: '케이스판재 자재 - 1219~2438mm',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { min: 1219, max: 2438, result: '2438mm', quantity: 1 }
    ],
    unit: 'mm',
    description: '제작사이즈(S) 1219~2438mm: 2438mm 자재 1개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 46. 케이스판재/상부덮개 자재 선택 - 2438~3000mm
  {
    id: 'RULE-046',
    ruleCode: 'CASE-MATERIAL-3000',
    ruleName: '케이스판재 자재 - 2438~3000mm',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { min: 2438, max: 3000, result: '3000mm', quantity: 1 }
    ],
    unit: 'mm',
    description: '제작사이즈(S) 2438~3000mm: 3000mm 자재 1개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 47. 케이스판재/상부덮개 자재 선택 - 3000~3500mm
  {
    id: 'RULE-047',
    ruleCode: 'CASE-MATERIAL-3500',
    ruleName: '케이스판재 자재 - 3000~3500mm',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { min: 3000, max: 3500, result: '3500mm', quantity: 1 }
    ],
    unit: 'mm',
    description: '제작사이즈(S) 3000~3500mm: 3500mm 자재 1개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 48. 케이스판재/상부덮개 자재 선택 - 3500~4000mm
  {
    id: 'RULE-048',
    ruleCode: 'CASE-MATERIAL-4000',
    ruleName: '케이스판재 자재 - 3500~4000mm',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { min: 3500, max: 4000, result: '4000mm', quantity: 1 }
    ],
    unit: 'mm',
    description: '제작사이즈(S) 3500~4000mm: 4000mm 자재 1개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 49. 케이스판재/상부덮개 자재 선택 - 4000~4150mm
  {
    id: 'RULE-049',
    ruleCode: 'CASE-MATERIAL-4150',
    ruleName: '케이스판재 자재 - 4000~4150mm',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { min: 4000, max: 4150, result: '4150mm', quantity: 1 }
    ],
    unit: 'mm',
    description: '제작사이즈(S) 4000~4150mm: 4150mm 자재 1개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 50. 케이스판재/상부덮개 자재 선택 - 4150~4719mm
  {
    id: 'RULE-050',
    ruleCode: 'CASE-MATERIAL-2438-1219',
    ruleName: '케이스판재 자재 - 4150~4719mm',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { min: 4150, max: 4719, result: '2438mm + 1219mm', quantity: 2 }
    ],
    unit: 'mm',
    description: '제작사이즈(S) 4150~4719mm: 2438mm + 1219mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 51. 케이스판재/상부덮개 자재 선택 - 4719~6000mm
  {
    id: 'RULE-051',
    ruleCode: 'CASE-MATERIAL-3000X2',
    ruleName: '케이스판재 자재 - 4719~6000mm',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { min: 4719, max: 6000, result: '3000mm × 2', quantity: 2 }
    ],
    unit: 'mm',
    description: '제작사이즈(S) 4719~6000mm: 3000mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 52. 케이스판재/상부덮개 자재 선택 - 6000~7000mm
  {
    id: 'RULE-052',
    ruleCode: 'CASE-MATERIAL-3500X2',
    ruleName: '케이스판재 자재 - 6000~7000mm',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { min: 6000, max: 7000, result: '3500mm × 2', quantity: 2 }
    ],
    unit: 'mm',
    description: '제작사이즈(S) 6000~7000mm: 3500mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 53. 케이스판재/상부덮개 자재 선택 - 7000~8000mm
  {
    id: 'RULE-053',
    ruleCode: 'CASE-MATERIAL-4000X2',
    ruleName: '케이스판재 자재 - 7000~8000mm',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { min: 7000, max: 8000, result: '4000mm × 2', quantity: 2 }
    ],
    unit: 'mm',
    description: '제작사이즈(S) 7000~8000mm: 4000mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 54. 케이스판재/상부덮개 자재 선택 - 8000~8300mm
  {
    id: 'RULE-054',
    ruleCode: 'CASE-MATERIAL-4150X2',
    ruleName: '케이스판재 자재 - 8000~8300mm',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      { min: 8000, max: 8300, result: '4150mm × 2', quantity: 2 }
    ],
    unit: 'mm',
    description: '제작사이즈(S) 8000~8300mm: 4150mm 자재 2개 사용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 55. 마구리(Marguri) 수량
  {
    id: 'RULE-055',
    ruleCode: 'MARGURI-QTY',
    ruleName: '마구리 수량',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'fixed',
    fixedValue: 2,
    unit: 'EA',
    description: '1SET = 2EA, 제작사이즈와 무관하게 1SET 적용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 56. 케이스용 연기차단재 수량
  {
    id: 'RULE-056',
    ruleCode: 'CASE-SMOKE-BARRIER-QTY',
    ruleName: '케이스용 연기차단재 수량',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'formula',
    formula: 'CEIL(S / 3000) * 2',
    unit: '개',
    description: '자재 길이 3000mm, 2줄 삽입. 예: S=6500 → ceil(6500/3000)=3 → 3×2=6개',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // 57. 상부덮개 수량 (NEW)
  {
    id: 'RULE-057',
    ruleCode: 'TOP-COVER-QTY',
    ruleName: '상부덮개 수량',
    category: '케이스',
    inputVariable: 'S',
    ruleType: 'formula',
    formula: 'CEIL(S / 1219)',
    unit: '개',
    description: '자재 길이 1219mm 고정, 셔터박스 상단 덮개로 1장 적용. 예: S=3200 → ceil(3200/1219)=3개',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-10-31',
    updatedAt: '2025-10-31'
  },
  
  // === 감기샤프트 규격 선택 (복합 조건) ===
  
  // 58. 감기샤프트 철재 - 복합조건 (제작사이즈 + 산출중량)
  {
    id: 'RULE-058',
    ruleCode: 'WINDING-SHAFT-STEEL',
    ruleName: '감기샤프트 규격 - 철재 (복합조건)',
    category: '철재',
    inputVariable: 'W1',
    ruleType: 'range',
    ranges: [
      { 
        id: 'WS-STEEL-1', 
        minValue: 0, 
        maxValue: 2400, 
        result: '4인치', 
        description: 'W1≤2400 & K≤400',
        additionalConditions: [
          { id: 'COND-1-1', variable: 'K', minValue: 0, maxValue: 400, conditionType: 'and' }
        ]
      },
      { 
        id: 'WS-STEEL-2', 
        minValue: 0, 
        maxValue: 2400, 
        result: '5인치', 
        description: 'W1≤2400 & 400<K≤600',
        additionalConditions: [
          { id: 'COND-2-1', variable: 'K', minValue: 400, maxValue: 600, conditionType: 'and' }
        ]
      },
      { 
        id: 'WS-STEEL-3', 
        minValue: 0, 
        maxValue: 2400, 
        result: '6인치', 
        description: 'W1≤2400 & K>600',
        additionalConditions: [
          { id: 'COND-3-1', variable: 'K', minValue: 600, maxValue: 99999, conditionType: 'and' }
        ]
      },
      { 
        id: 'WS-STEEL-4', 
        minValue: 2400, 
        maxValue: 3000, 
        result: '5인치', 
        description: '2400<W1≤3000 & K≤600',
        additionalConditions: [
          { id: 'COND-4-1', variable: 'K', minValue: 0, maxValue: 600, conditionType: 'and' }
        ]
      },
      { 
        id: 'WS-STEEL-5', 
        minValue: 2400, 
        maxValue: 3000, 
        result: '6인치', 
        description: '2400<W1≤3000 & K>600',
        additionalConditions: [
          { id: 'COND-5-1', variable: 'K', minValue: 600, maxValue: 99999, conditionType: 'and' }
        ]
      },
      { 
        id: 'WS-STEEL-6', 
        minValue: 3000, 
        maxValue: 3600, 
        result: '6인치', 
        description: '3000<W1≤3600 & K≤800',
        additionalConditions: [
          { id: 'COND-6-1', variable: 'K', minValue: 0, maxValue: 800, conditionType: 'and' }
        ]
      },
      { 
        id: 'WS-STEEL-7', 
        minValue: 3000, 
        maxValue: 3600, 
        result: '8인치', 
        description: '3000<W1≤3600 & K>800',
        additionalConditions: [
          { id: 'COND-7-1', variable: 'K', minValue: 800, maxValue: 99999, conditionType: 'and' }
        ]
      },
      { 
        id: 'WS-STEEL-8', 
        minValue: 3600, 
        maxValue: 99999, 
        result: '8인치', 
        description: 'W1>3600 (중량 무관)',
        additionalConditions: []
      }
    ],
    unit: '',
    description: '철재 감기샤프트 규격 선택: 제작사이즈(W1)와 산출중량(K)의 복합조건으로 4/5/6/8인치 규격 결정',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    isStage1: true,
    stage1ResultType: 'specification',
    createdAt: '2025-11-17',
    updatedAt: '2025-11-17'
  },

  // === 하단마감재 산정 기준 ===
  
  // 하장바 - 철재 (60×30)
  {
    id: 'RULE-059',
    ruleCode: 'BOTTOM-BAR-STEEL',
    ruleName: '하장바 - 철재 (60×30)',
    category: 'bottom-finish',
    inputVariable: 'W0_2B',
    ruleType: 'range',
    ranges: [
      { 
        id: 'BBS-1', 
        minValue: 0, 
        maxValue: 3000, 
        result: '3000mm 1개', 
        itemCode: 'BF-BAR-S-3000',
        itemName: '하장바 60×30 3000mm',
        quantity: 1,
        description: '0~3000: 3000mm 1개'
      },
      { 
        id: 'BBS-2', 
        minValue: 3000, 
        maxValue: 4000, 
        result: '4000mm 1개', 
        itemCode: 'BF-BAR-S-4000',
        itemName: '하장바 60×30 4000mm',
        quantity: 1,
        description: '3001~4000: 4000mm 1개'
      },
      { 
        id: 'BBS-3', 
        minValue: 4000, 
        maxValue: 6000, 
        result: '3000mm 2개', 
        itemCode: 'BF-BAR-S-3000',
        itemName: '하장바 60×30 3000mm',
        quantity: 2,
        description: '4001~6000: 3000mm 2개'
      },
      { 
        id: 'BBS-4', 
        minValue: 6000, 
        maxValue: 7000, 
        result: '4000mm 1개 + 3000mm 1개', 
        items: [
          {
            id: 'BBS-4-1',
            itemCode: 'BF-BAR-S-4000',
            itemName: '하장바 60×30 4000mm',
            quantity: 1
          },
          {
            id: 'BBS-4-2',
            itemCode: 'BF-BAR-S-3000',
            itemName: '하장바 60×30 3000mm',
            quantity: 1
          }
        ],
        description: '6001~7000: 4000mm 1개 + 3000mm 1개'
      },
      { 
        id: 'BBS-5', 
        minValue: 7000, 
        maxValue: 8000, 
        result: '4000mm 2개', 
        itemCode: 'BF-BAR-S-4000',
        itemName: '하장바 60×30 4000mm',
        quantity: 2,
        description: '7001~8000: 4000mm 2개'
      },
      { 
        id: 'BBS-6', 
        minValue: 8000, 
        maxValue: 9000, 
        result: '3000mm 3개', 
        itemCode: 'BF-BAR-S-3000',
        itemName: '하장바 60×30 3000mm',
        quantity: 3,
        description: '8001~9000: 3000mm 3개'
      },
      { 
        id: 'BBS-7', 
        minValue: 9000, 
        maxValue: 10000, 
        result: '4000mm 1개 + 3000mm 2개', 
        items: [
          {
            id: 'BBS-7-1',
            itemCode: 'BF-BAR-S-4000',
            itemName: '하장바 60×30 4000mm',
            quantity: 1
          },
          {
            id: 'BBS-7-2',
            itemCode: 'BF-BAR-S-3000',
            itemName: '하장바 60×30 3000mm',
            quantity: 2
          }
        ],
        description: '9001~10000: 4000mm 1개 + 3000mm 2개'
      },
      { 
        id: 'BBS-8', 
        minValue: 10000, 
        maxValue: 12000, 
        result: '4000mm 2개 + 3000mm 1개', 
        items: [
          {
            id: 'BBS-8-1',
            itemCode: 'BF-BAR-S-4000',
            itemName: '하장바 60×30 4000mm',
            quantity: 2
          },
          {
            id: 'BBS-8-2',
            itemCode: 'BF-BAR-S-3000',
            itemName: '하장바 60×30 3000mm',
            quantity: 1
          }
        ],
        description: '10001~12000: 4000mm 2개 + 3000mm 1개'
      },
      { 
        id: 'BBS-9', 
        minValue: 12000, 
        maxValue: 99999, 
        result: '4000mm 3개', 
        itemCode: 'BF-BAR-S-4000',
        itemName: '하장바 60×30 4000mm',
        quantity: 3,
        description: '12001~: 4000mm 3개'
      }
    ],
    unit: '',
    description: '하장바 철재 (60×30): (W0×2 + B×2) 구간별 3000mm, 4000mm 품목 수량 산출',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // 하장바 - 스크린 (60×40)
  {
    id: 'RULE-060',
    ruleCode: 'BOTTOM-BAR-SCREEN',
    ruleName: '하장바 - 스크린 (60×40)',
    category: 'bottom-finish',
    inputVariable: 'W0_2B',
    ruleType: 'range',
    ranges: [
      { 
        id: 'BBSC-1', 
        minValue: 0, 
        maxValue: 3000, 
        result: '3000mm 1개', 
        itemCode: 'BF-BAR-SC-3000',
        itemName: '하장바 60×40 3000mm',
        quantity: 1,
        description: '0~3000: 3000mm 1개'
      },
      { 
        id: 'BBSC-2', 
        minValue: 3000, 
        maxValue: 4000, 
        result: '4000mm 1개', 
        itemCode: 'BF-BAR-SC-4000',
        itemName: '하장바 60×40 4000mm',
        quantity: 1,
        description: '3001~4000: 4000mm 1개'
      },
      { 
        id: 'BBSC-3', 
        minValue: 4000, 
        maxValue: 6000, 
        result: '3000mm 2개', 
        itemCode: 'BF-BAR-SC-3000',
        itemName: '하장바 60×40 3000mm',
        quantity: 2,
        description: '4001~6000: 3000mm 2개'
      },
      { 
        id: 'BBSC-4', 
        minValue: 6000, 
        maxValue: 7000, 
        result: '4000mm 1개 + 3000mm 1개', 
        items: [
          {
            id: 'BBSC-4-1',
            itemCode: 'BF-BAR-SC-4000',
            itemName: '하장바 60×40 4000mm',
            quantity: 1
          },
          {
            id: 'BBSC-4-2',
            itemCode: 'BF-BAR-SC-3000',
            itemName: '하장바 60×40 3000mm',
            quantity: 1
          }
        ],
        description: '6001~7000: 4000mm 1개 + 3000mm 1개'
      },
      { 
        id: 'BBSC-5', 
        minValue: 7000, 
        maxValue: 8000, 
        result: '4000mm 2개', 
        itemCode: 'BF-BAR-SC-4000',
        itemName: '하장바 60×40 4000mm',
        quantity: 2,
        description: '7001~8000: 4000mm 2개'
      },
      { 
        id: 'BBSC-6', 
        minValue: 8000, 
        maxValue: 9000, 
        result: '3000mm 3개', 
        itemCode: 'BF-BAR-SC-3000',
        itemName: '하장바 60×40 3000mm',
        quantity: 3,
        description: '8001~9000: 3000mm 3개'
      },
      { 
        id: 'BBSC-7', 
        minValue: 9000, 
        maxValue: 10000, 
        result: '4000mm 1개 + 3000mm 2개', 
        items: [
          {
            id: 'BBSC-7-1',
            itemCode: 'BF-BAR-SC-4000',
            itemName: '하장바 60×40 4000mm',
            quantity: 1
          },
          {
            id: 'BBSC-7-2',
            itemCode: 'BF-BAR-SC-3000',
            itemName: '하장바 60×40 3000mm',
            quantity: 2
          }
        ],
        description: '9001~10000: 4000mm 1개 + 3000mm 2개'
      },
      { 
        id: 'BBSC-8', 
        minValue: 10000, 
        maxValue: 12000, 
        result: '4000mm 2개 + 3000mm 1개', 
        items: [
          {
            id: 'BBSC-8-1',
            itemCode: 'BF-BAR-SC-4000',
            itemName: '하장바 60×40 4000mm',
            quantity: 2
          },
          {
            id: 'BBSC-8-2',
            itemCode: 'BF-BAR-SC-3000',
            itemName: '하장바 60×40 3000mm',
            quantity: 1
          }
        ],
        description: '10001~12000: 4000mm 2개 + 3000mm 1개'
      },
      { 
        id: 'BBSC-9', 
        minValue: 12000, 
        maxValue: 99999, 
        result: '4000mm 3개', 
        itemCode: 'BF-BAR-SC-4000',
        itemName: '하장바 60×40 4000mm',
        quantity: 3,
        description: '12001~: 4000mm 3개'
      }
    ],
    unit: '',
    description: '하장바 스크린 (60×40): (W0×2 + B×2) 구간별 3000mm, 4000mm 품목 수량 산출',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // 엘바 - 스크린 전용 (17×60×2개)
  {
    id: 'RULE-061',
    ruleCode: 'L-BAR-SCREEN',
    ruleName: '엘바 - 스크린 (17×60×2개)',
    category: 'bottom-finish',
    inputVariable: 'W1',
    ruleType: 'range',
    ranges: [
      { 
        id: 'LB-1', 
        minValue: 0, 
        maxValue: 3000, 
        result: '3000mm 1개', 
        itemCode: 'BF-LBAR-3000',
        itemName: '엘바 17×60×2개 3000mm',
        quantity: 1,
        description: '0~3000: 3000mm 1개'
      },
      { 
        id: 'LB-2', 
        minValue: 3000, 
        maxValue: 6000, 
        result: '3000mm 2개', 
        itemCode: 'BF-LBAR-3000',
        itemName: '엘바 17×60×2개 3000mm',
        quantity: 2,
        description: '3001~6000: 3000mm 2개'
      },
      { 
        id: 'LB-3', 
        minValue: 6000, 
        maxValue: 9000, 
        result: '3000mm 3개', 
        itemCode: 'BF-LBAR-3000',
        itemName: '엘바 17×60×2개 3000mm',
        quantity: 3,
        description: '6001~9000: 3000mm 3개'
      },
      { 
        id: 'LB-4', 
        minValue: 9000, 
        maxValue: 12000, 
        result: '3000mm 4개', 
        itemCode: 'BF-LBAR-3000',
        itemName: '엘바 17×60×2개 3000mm',
        quantity: 4,
        description: '9001~12000: 3000mm 4개'
      },
      { 
        id: 'LB-5', 
        minValue: 12000, 
        maxValue: 99999, 
        result: '3000mm 5개', 
        itemCode: 'BF-LBAR-3000',
        itemName: '엘바 17×60×2개 3000mm',
        quantity: 5,
        description: '12001~: 3000mm 5개'
      }
    ],
    unit: '',
    description: '엘바 스크린 전용 (17×60×2개): W1 기준 3000mm 단위 수량 산출',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // 보강평철 - 스크린 전용 (50)
  {
    id: 'RULE-062',
    ruleCode: 'REINFORCE-FLAT-SCREEN',
    ruleName: '보강평철 - 스크린 (50)',
    category: 'bottom-finish',
    inputVariable: 'W1',
    ruleType: 'range',
    ranges: [
      { 
        id: 'RF-1', 
        minValue: 0, 
        maxValue: 3000, 
        result: '3000mm 1개', 
        itemCode: 'BF-RFLAT-3000',
        itemName: '보강평철 50 3000mm',
        quantity: 1,
        description: '0~3000: 3000mm 1개'
      },
      { 
        id: 'RF-2', 
        minValue: 3000, 
        maxValue: 4000, 
        result: '4000mm 1개', 
        itemCode: 'BF-RFLAT-4000',
        itemName: '보강평철 50 4000mm',
        quantity: 1,
        description: '3001~4000: 4000mm 1개'
      },
      { 
        id: 'RF-3', 
        minValue: 4000, 
        maxValue: 6000, 
        result: '3000mm 2개', 
        itemCode: 'BF-RFLAT-3000',
        itemName: '보강평철 50 3000mm',
        quantity: 2,
        description: '4001~6000: 3000mm 2개'
      },
      { 
        id: 'RF-4', 
        minValue: 6000, 
        maxValue: 7000, 
        result: '4000mm 1개 + 3000mm 1개', 
        items: [
          {
            id: 'RF-4-1',
            itemCode: 'BF-RFLAT-4000',
            itemName: '보강평철 50 4000mm',
            quantity: 1
          },
          {
            id: 'RF-4-2',
            itemCode: 'BF-RFLAT-3000',
            itemName: '보강평철 50 3000mm',
            quantity: 1
          }
        ],
        description: '6001~7000: 4000mm 1개 + 3000mm 1개'
      },
      { 
        id: 'RF-5', 
        minValue: 7000, 
        maxValue: 8000, 
        result: '4000mm 2개', 
        itemCode: 'BF-RFLAT-4000',
        itemName: '보강평철 50 4000mm',
        quantity: 2,
        description: '7001~8000: 4000mm 2개'
      },
      { 
        id: 'RF-6', 
        minValue: 8000, 
        maxValue: 9000, 
        result: '3000mm 3개', 
        itemCode: 'BF-RFLAT-3000',
        itemName: '보강평철 50 3000mm',
        quantity: 3,
        description: '8001~9000: 3000mm 3개'
      },
      { 
        id: 'RF-7', 
        minValue: 9000, 
        maxValue: 10000, 
        result: '4000mm 1개 + 3000mm 2개', 
        items: [
          {
            id: 'RF-7-1',
            itemCode: 'BF-RFLAT-4000',
            itemName: '보강평철 50 4000mm',
            quantity: 1
          },
          {
            id: 'RF-7-2',
            itemCode: 'BF-RFLAT-3000',
            itemName: '보강평철 50 3000mm',
            quantity: 2
          }
        ],
        description: '9001~10000: 4000mm 1개 + 3000mm 2개'
      },
      { 
        id: 'RF-8', 
        minValue: 10000, 
        maxValue: 12000, 
        result: '4000mm 2개 + 3000mm 1개', 
        items: [
          {
            id: 'RF-8-1',
            itemCode: 'BF-RFLAT-4000',
            itemName: '보강평철 50 4000mm',
            quantity: 2
          },
          {
            id: 'RF-8-2',
            itemCode: 'BF-RFLAT-3000',
            itemName: '보강평철 50 3000mm',
            quantity: 1
          }
        ],
        description: '10001~12000: 4000mm 2개 + 3000mm 1개'
      },
      { 
        id: 'RF-9', 
        minValue: 12000, 
        maxValue: 99999, 
        result: '4000mm 3개', 
        itemCode: 'BF-RFLAT-4000',
        itemName: '보강평철 50 4000mm',
        quantity: 3,
        description: '12001~: 4000mm 3개'
      }
    ],
    unit: '',
    description: '보강평철 스크린 전용 (50): W1 기준 3000mm, 4000mm 품목 수량 산출',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // 무게평철 - 스크린 전용 (50×12T×2개)
  {
    id: 'RULE-063',
    ruleCode: 'WEIGHT-FLAT-SCREEN',
    ruleName: '무게평철 - 스크린 (50×12T×2개)',
    category: 'bottom-finish',
    inputVariable: 'B_2',
    ruleType: 'range',
    ranges: [
      { 
        id: 'WF-1', 
        minValue: 0, 
        maxValue: 2000, 
        result: '2000mm 1개', 
        itemCode: 'BF-WFLAT-2000',
        itemName: '무게평철 50×12T×2개 2000mm',
        quantity: 1,
        description: '0~2000: 2000mm 1개'
      },
      { 
        id: 'WF-2', 
        minValue: 2000, 
        maxValue: 4000, 
        result: '2000mm 2개', 
        itemCode: 'BF-WFLAT-2000',
        itemName: '무게평철 50×12T×2개 2000mm',
        quantity: 2,
        description: '2001~4000: 2000mm 2개'
      },
      { 
        id: 'WF-3', 
        minValue: 4000, 
        maxValue: 6000, 
        result: '2000mm 3개', 
        itemCode: 'BF-WFLAT-2000',
        itemName: '무게평철 50×12T×2개 2000mm',
        quantity: 3,
        description: '4001~6000: 2000mm 3개'
      },
      { 
        id: 'WF-4', 
        minValue: 6000, 
        maxValue: 8000, 
        result: '2000mm 4개', 
        itemCode: 'BF-WFLAT-2000',
        itemName: '무게평철 50×12T×2개 2000mm',
        quantity: 4,
        description: '6001~8000: 2000mm 4개'
      },
      { 
        id: 'WF-5', 
        minValue: 8000, 
        maxValue: 10000, 
        result: '2000mm 5개', 
        itemCode: 'BF-WFLAT-2000',
        itemName: '무게평철 50×12T×2개 2000mm',
        quantity: 5,
        description: '8001~10000: 2000mm 5개'
      },
      { 
        id: 'WF-6', 
        minValue: 10000, 
        maxValue: 12000, 
        result: '2000mm 6개', 
        itemCode: 'BF-WFLAT-2000',
        itemName: '무게평철 50×12T×2개 2000mm',
        quantity: 6,
        description: '10001~12000: 2000mm 6개'
      },
      { 
        id: 'WF-7', 
        minValue: 12000, 
        maxValue: 14000, 
        result: '2000mm 7개', 
        itemCode: 'BF-WFLAT-2000',
        itemName: '무게평철 50×12T×2개 2000mm',
        quantity: 7,
        description: '12001~14000: 2000mm 7개'
      },
      { 
        id: 'WF-8', 
        minValue: 14000, 
        maxValue: 16000, 
        result: '2000mm 8개', 
        itemCode: 'BF-WFLAT-2000',
        itemName: '무게평철 50×12T×2개 2000mm',
        quantity: 8,
        description: '14001~16000: 2000mm 8개'
      },
      { 
        id: 'WF-9', 
        minValue: 16000, 
        maxValue: 18000, 
        result: '2000mm 9개', 
        itemCode: 'BF-WFLAT-2000',
        itemName: '무게평철 50×12T×2개 2000mm',
        quantity: 9,
        description: '16001~18000: 2000mm 9개'
      },
      { 
        id: 'WF-10', 
        minValue: 18000, 
        maxValue: 20000, 
        result: '2000mm 10개', 
        itemCode: 'BF-WFLAT-2000',
        itemName: '무게평철 50×12T×2개 2000mm',
        quantity: 10,
        description: '18001~20000: 2000mm 10개'
      }
    ],
    unit: '',
    description: '무게평철 스크린 전용 (50×12T×2개): B×2 기준 2000mm 단위 수량 산출 (10개 구간)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // === 케이스(셔터박스) ===
  // 케이스 스크린 - S 변수 계산
  {
    id: 'RULE-CASE-001',
    ruleCode: 'CASE-SIZE-SCREEN',
    ruleName: '케이스 사이즈(S) - 스크린',
    category: '스크린',
    inputVariable: 'W0',
    ruleType: 'formula',
    formula: 'W0 + 220',
    unit: 'mm',
    description: '스크린용 케이스 사이즈: S = W0 + 220',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    isStage1: true,
    stageLevel: 1,
    stage1ResultType: 'value',
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // 케이스 철재 - S 변수 계산
  {
    id: 'RULE-CASE-002',
    ruleCode: 'CASE-SIZE-STEEL',
    ruleName: '케이스 사이즈(S) - 철재',
    category: '철재',
    inputVariable: 'W0',
    ruleType: 'formula',
    formula: 'W0 + 240',
    unit: 'mm',
    description: '철재용 케이스 사이즈: S = W0 + 240',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    isStage1: true,
    stageLevel: 1,
    stage1ResultType: 'value',
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // === 샘플: 2단계 규칙 (케이스 품목 선택) ===
  {
    id: 'RULE-CASE-STAGE2-001',
    ruleCode: 'CASE-ITEM-SCREEN',
    ruleName: '케이스 품목 선택 - 스크린 (2단계)',
    category: '스크린',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      {
        id: 'CS-1',
        minValue: 0,
        maxValue: 1500,
        result: '케이스 소형',
        itemCode: 'CASE-S-1500',
        itemName: '케이스판재 1500mm',
        quantity: 1,
        description: '0~1500mm: 소형 케이스'
      },
      {
        id: 'CS-2',
        minValue: 1500,
        maxValue: 3000,
        result: '케이스 중형',
        itemCode: 'CASE-S-3000',
        itemName: '케이스판재 3000mm',
        quantity: 1,
        description: '1500~3000mm: 중형 케이스'
      },
      {
        id: 'CS-3',
        minValue: 3000,
        maxValue: 5000,
        result: '케이스 대형',
        itemCode: 'CASE-S-4000',
        itemName: '케이스판재 4000mm',
        quantity: 1,
        description: '3000~5000mm: 대형 케이스'
      }
    ],
    unit: 'EA',
    description: '케이스 사이즈(S)에 따른 스크린용 케이스 품목 선택 (2단계)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    isStage1: true,
    stageLevel: 2,
    stage1ResultType: 'item',
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  {
    id: 'RULE-CASE-STAGE2-002',
    ruleCode: 'CASE-ITEM-STEEL',
    ruleName: '케이스 품목 선택 - 철재 (2단계)',
    category: '철재',
    inputVariable: 'S',
    ruleType: 'range',
    ranges: [
      {
        id: 'CT-1',
        minValue: 0,
        maxValue: 1500,
        result: '케이스 소형',
        itemCode: 'CASE-T-1500',
        itemName: '케이스판재 철재 1500mm',
        quantity: 1,
        description: '0~1500mm: 소형 케이스'
      },
      {
        id: 'CT-2',
        minValue: 1500,
        maxValue: 3000,
        result: '케이스 중형',
        itemCode: 'CASE-T-3000',
        itemName: '케이스판재 철재 3000mm',
        quantity: 1,
        description: '1500~3000mm: 중형 케이스'
      }
    ],
    unit: 'EA',
    description: '케이스 사이즈(S)에 따른 철재용 케이스 품목 선택 (2단계)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    isStage1: true,
    stageLevel: 2,
    stage1ResultType: 'item',
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // === 브라케트 산정 기준 (품목 조건 사용) ===
  // 스크린용 브라케트
  {
    id: 'RULE-BRACKET-SCREEN-001',
    ruleCode: 'BRACKET-SCREEN',
    ruleName: '브라케트 규격 - 스크린',
    category: '스크린',
    inputVariable: 'motorCapacity',
    ruleType: 'range',
    ranges: [
      {
        id: 'BS-1',
        minValue: 0,
        maxValue: 999,
        result: '브라케트 380×180',
        itemCode: 'BRACKET-380-180',
        itemName: '브라케트 380×180',
        quantity: 1,
        description: '모터 150K용',
        additionalConditions: [
          {
            id: 'BS-1-COND',
            conditionSource: 'item',
            itemCode: 'MOTOR-150K',
            itemName: '모터 150K',
            conditionType: 'and',
            description: '모터 150K 사용 시'
          }
        ]
      },
      {
        id: 'BS-2',
        minValue: 0,
        maxValue: 999,
        result: '브라케트 530×320',
        itemCode: 'BRACKET-530-320',
        itemName: '브라케트 530×320',
        quantity: 1,
        description: '모터 300K/400K용',
        additionalConditions: [
          {
            id: 'BS-2-COND-1',
            conditionSource: 'item',
            itemCode: 'MOTOR-300K',
            itemName: '모터 300K',
            conditionType: 'and',
            description: '모터 300K 사용 시'
          }
        ]
      },
      {
        id: 'BS-3',
        minValue: 0,
        maxValue: 999,
        result: '브라케트 530×320',
        itemCode: 'BRACKET-530-320',
        itemName: '브라케트 530×320',
        quantity: 1,
        description: '모터 400K용',
        additionalConditions: [
          {
            id: 'BS-3-COND',
            conditionSource: 'item',
            itemCode: 'MOTOR-400K',
            itemName: '모터 400K',
            conditionType: 'and',
            description: '모터 400K 사용 시'
          }
        ]
      }
    ],
    unit: 'EA',
    description: '스크린용 브라케트 규격 - 모터 용량별',
    status: 'active',
    currentRevision: 0,
    isFinal: true,
    isStage1: false,
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // 철재용 브라케트
  {
    id: 'RULE-BRACKET-STEEL-001',
    ruleCode: 'BRACKET-STEEL',
    ruleName: '브라케트 규격 - 철재',
    category: '철재',
    inputVariable: 'motorCapacity',
    ruleType: 'range',
    ranges: [
      {
        id: 'BT-1',
        minValue: 0,
        maxValue: 999,
        result: '브라케트 530×320',
        itemCode: 'BRACKET-530-320',
        itemName: '브라케트 530×320',
        quantity: 1,
        description: '모터 300K용',
        additionalConditions: [
          {
            id: 'BT-1-COND',
            conditionSource: 'item',
            itemCode: 'MOTOR-300K',
            itemName: '모터 300K',
            conditionType: 'and',
            description: '모터 300K 사용 시'
          }
        ]
      },
      {
        id: 'BT-2',
        minValue: 0,
        maxValue: 999,
        result: '브라케트 600×350',
        itemCode: 'BRACKET-600-350',
        itemName: '브라케트 600×350',
        quantity: 1,
        description: '모터 400K/500K용',
        additionalConditions: [
          {
            id: 'BT-2-COND-1',
            conditionSource: 'item',
            itemCode: 'MOTOR-400K',
            itemName: '모터 400K',
            conditionType: 'and',
            description: '모터 400K 사용 시'
          }
        ]
      },
      {
        id: 'BT-3',
        minValue: 0,
        maxValue: 999,
        result: '브라케트 600×350',
        itemCode: 'BRACKET-600-350',
        itemName: '브라케트 600×350',
        quantity: 1,
        description: '모터 500K용',
        additionalConditions: [
          {
            id: 'BT-3-COND',
            conditionSource: 'item',
            itemCode: 'MOTOR-500K',
            itemName: '모터 500K',
            conditionType: 'and',
            description: '모터 500K 사용 시'
          }
        ]
      },
      {
        id: 'BT-4',
        minValue: 0,
        maxValue: 999,
        result: '브라케트 690×390',
        itemCode: 'BRACKET-690-390',
        itemName: '브라케트 690×390',
        quantity: 1,
        description: '모터 600K/800K용',
        additionalConditions: [
          {
            id: 'BT-4-COND-1',
            conditionSource: 'item',
            itemCode: 'MOTOR-600K',
            itemName: '모터 600K',
            conditionType: 'and',
            description: '모터 600K 사용 시'
          }
        ]
      },
      {
        id: 'BT-5',
        minValue: 0,
        maxValue: 999,
        result: '브라케트 690×390',
        itemCode: 'BRACKET-690-390',
        itemName: '브라케트 690×390',
        quantity: 1,
        description: '모터 800K용',
        additionalConditions: [
          {
            id: 'BT-5-COND',
            conditionSource: 'item',
            itemCode: 'MOTOR-800K',
            itemName: '모터 800K',
            conditionType: 'and',
            description: '모터 800K 사용 시'
          }
        ]
      }
    ],
    unit: 'EA',
    description: '철재용 브라케트 규격 - 모터 용량별',
    status: 'active',
    currentRevision: 0,
    isFinal: true,
    isStage1: false,
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // === 샘플: 3단계 규칙 (수량 세분화) ===
  {
    id: 'RULE-CASE-STAGE3-001',
    ruleCode: 'CASE-QTY-DETAIL',
    ruleName: '케이스 수량 세분화 (3단계)',
    category: '공통',
    inputVariable: 'H1',
    ruleType: 'range',
    ranges: [
      {
        id: 'CQ-1',
        minValue: 0,
        maxValue: 2000,
        result: '표준 수량',
        quantity: 1,
        description: '높이 2000mm 이하: 기본 1개'
      },
      {
        id: 'CQ-2',
        minValue: 2000,
        maxValue: 4000,
        result: '증량',
        quantity: 2,
        description: '높이 2000~4000mm: 2개'
      },
      {
        id: 'CQ-3',
        minValue: 4000,
        maxValue: 10000,
        result: '대량',
        quantity: 3,
        description: '높이 4000mm 이상: 3개'
      }
    ],
    unit: 'EA',
    description: '제작높이(H1)에 따른 케이스 수량 세분화 (3단계)',
    status: 'active',
    currentRevision: 0,
    isFinal: true,
    isStage1: false,
    stageLevel: 3,
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // === 단가 계산 수식 ===
  {
    id: 'RULE-PRICE-001',
    ruleCode: 'PRICE-SCREEN',
    ruleName: '스크린 제품 단가 계산',
    category: '단가계산',
    inputVariable: 'basePrice',
    ruleType: 'formula',
    formula: 'basePrice * 1.2',
    outputFormula: 'basePrice * 1.2',
    unit: '원',
    description: '스크린 제품 기본 단가에 20% 마진 적용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-24',
    updatedAt: '2025-11-24'
  },
  {
    id: 'RULE-PRICE-002',
    ruleCode: 'PRICE-STEEL',
    ruleName: '철재 제품 단가 계산',
    category: '단가계산',
    inputVariable: 'basePrice',
    ruleType: 'formula',
    formula: 'basePrice * 1.25',
    outputFormula: 'basePrice * 1.25',
    unit: '원',
    description: '철재 제품 기본 단가에 25% 마진 적용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-24',
    updatedAt: '2025-11-24'
  },
  {
    id: 'RULE-PRICE-003',
    ruleCode: 'PRICE-ELECTRIC',
    ruleName: '전기 부품 단가 계산',
    category: '단가계산',
    inputVariable: 'basePrice',
    ruleType: 'formula',
    formula: 'basePrice * 1.15',
    outputFormula: 'basePrice * 1.15',
    unit: '원',
    description: '전기 부품 기본 단가에 15% 마진 적용',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-24',
    updatedAt: '2025-11-24'
  },
  
  // === BOM 구성 수식 (품목 수량 계산) ===
  {
    id: 'RULE-BOM-001',
    ruleCode: 'BOM-GUIDERAIL-SCREEN',
    ruleName: '가이드레일 수량 - 스크린',
    category: '스크린',
    inputVariable: 'height',
    ruleType: 'formula',
    formula: 'Math.ceil(height / 2438) * 2',
    outputFormula: 'Math.ceil(height / 2438) * 2',
    resultFormula: 'Math.ceil(height / 2438) * 2',
    unit: 'EA',
    description: '스크린 제품의 가이드레일 수량 (높이 기준, 좌우 2개)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-24',
    updatedAt: '2025-11-24'
  },
  {
    id: 'RULE-BOM-002',
    ruleCode: 'BOM-CASE-SCREEN',
    ruleName: '케이스 수량 - 스크린',
    category: '스크린',
    inputVariable: 'width',
    ruleType: 'formula',
    formula: 'Math.ceil(width / 1000)',
    outputFormula: 'Math.ceil(width / 1000)',
    resultFormula: 'Math.ceil(width / 1000)',
    unit: 'EA',
    description: '스크린 제품의 케이스 수량 (폭 1m당 1개)',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-24',
    updatedAt: '2025-11-24'
  },
  {
    id: 'RULE-BOM-003',
    ruleCode: 'BOM-MOTOR',
    ruleName: '모터 수량',
    category: '공통',
    inputVariable: 'quantity',
    ruleType: 'formula',
    formula: '1',
    outputFormula: '1',
    resultFormula: '1',
    unit: 'EA',
    description: '제품 1세트당 모터 1개',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-24',
    updatedAt: '2025-11-24'
  },
  {
    id: 'RULE-BOM-004',
    ruleCode: 'BOM-CONTROLLER',
    ruleName: '제어기 수량',
    category: '공통',
    inputVariable: 'quantity',
    ruleType: 'formula',
    formula: '1',
    outputFormula: '1',
    resultFormula: '1',
    unit: 'EA',
    description: '제품 1세트당 제어기 1개',
    status: 'active',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-11-24',
    updatedAt: '2025-11-24'
  }
];

// 2단계 매핑 초기 데이터
const initialStage2Mappings: Stage2Mapping[] = [
  {
    id: 'MAPPING-001',
    stage1RuleId: 'RULE-058', // 감기샤프트 철재
    stage1RuleName: '감기샤프트 규격 - 철재',
    mappingName: '감기샤프트 철재 → 품목 선택',
    conditions: [
      {
        id: 'MAP-COND-1',
        conditionType: 'exact',
        exactValue: '4인치',
        stage2RuleId: 'RULE-059', // 추후 생성될 2단계 규칙
        useStage1Result: true,
        stage2InputVariable: 'diameter',
        description: '4인치 샤프트 품목 선택'
      },
      {
        id: 'MAP-COND-2',
        conditionType: 'exact',
        exactValue: '5인치',
        stage2RuleId: 'RULE-060',
        useStage1Result: true,
        stage2InputVariable: 'diameter',
        description: '5인치 샤프트 품목 선택'
      },
      {
        id: 'MAP-COND-3',
        conditionType: 'exact',
        exactValue: '6인치',
        stage2RuleId: 'RULE-061',
        useStage1Result: true,
        stage2InputVariable: 'diameter',
        description: '6인치 샤프트 품목 선택'
      },
      {
        id: 'MAP-COND-4',
        conditionType: 'exact',
        exactValue: '8인치',
        stage2RuleId: 'RULE-062',
        useStage1Result: true,
        stage2InputVariable: 'diameter',
        description: '8인치 샤프트 품목 선택'
      }
    ],
    description: '감기샤프트 철재 규격에 따른 품목 선택 매핑',
    status: 'active',
    createdAt: '2025-11-17',
    updatedAt: '2025-11-17'
  },
  
  // 케이스 1단계 → 2단계 매핑 (스크린)
  {
    id: 'MAPPING-CASE-001',
    stage1RuleId: 'RULE-CASE-001',
    stage1RuleName: '케이스 사이즈(S) - 스크린',
    mappingName: '케이스 S값 → 스크린 품목 선택',
    conditions: [
      {
        id: 'MAP-CASE-COND-1',
        conditionType: 'range',
        minValue: 0,
        maxValue: 10000,
        stage2RuleId: 'RULE-CASE-STAGE2-001',
        useStage1Result: true,
        stage2InputVariable: 'S',
        description: '모든 범위에서 2단계 규칙 실행 (S값 전달)'
      }
    ],
    description: '스크린 케이스 사이즈 → 품목 선택 매핑',
    status: 'active',
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // 케이스 1단계 → 2단계 매핑 (철재)
  {
    id: 'MAPPING-CASE-002',
    stage1RuleId: 'RULE-CASE-002',
    stage1RuleName: '케이스 사이즈(S) - 철재',
    mappingName: '케이스 S값 → 철재 품목 선택',
    conditions: [
      {
        id: 'MAP-CASE-COND-2',
        conditionType: 'range',
        minValue: 0,
        maxValue: 10000,
        stage2RuleId: 'RULE-CASE-STAGE2-002',
        useStage1Result: true,
        stage2InputVariable: 'S',
        description: '모든 범위에서 2단계 규칙 실행 (S값 전달)'
      }
    ],
    description: '철재 케이스 사이즈 → 품목 선택 매핑',
    status: 'active',
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  },

  // 케이스 2단계 → 3단계 매핑 예시
  {
    id: 'MAPPING-CASE-STAGE2-TO-3',
    stage1RuleId: 'RULE-CASE-STAGE2-001',
    stage1RuleName: '케이스 품목 선택 - 스크린 (2단계)',
    mappingName: '케이스 품목 → 수량 세분화',
    conditions: [
      {
        id: 'MAP-CASE-S2-COND-1',
        conditionType: 'contains',
        containsText: '케이스',
        stage2RuleId: 'RULE-CASE-STAGE3-001',
        useStage1Result: false,
        description: '케이스 품목이 선택되면 3단계 수량 세분화 실행'
      }
    ],
    description: '케이스 품목 선택 후 수량 세분화 (2→3단계)',
    status: 'active',
    createdAt: '2025-11-18',
    updatedAt: '2025-11-18'
  }
];

// 견적산출용 샘플 제품 단가 데이터
const initialPricing: PricingData[] = [
  {
    id: 'PRICE-SAMPLE-001',
    itemId: 'SAMPLE-001',
    itemCode: '견적산출용 샘플1',
    itemName: '견적산출용 샘플1',
    itemType: 'FG',
    unit: 'SET',
    effectiveDate: '2025-10-31',
    purchasePrice: 285000,
    processingCost: 65000,
    marginRate: 30,
    salesPrice: 450000,
    supplier: '제조사',
    note: '스크린 셔터 견적산출용 샘플',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-10-31',
    createdBy: '시스템'
  },
  {
    id: 'PRICE-SAMPLE-002',
    itemId: 'SAMPLE-002',
    itemCode: '견적산출용 샘플2',
    itemName: '견적산출용 샘플2',
    itemType: 'FG',
    unit: 'SET',
    effectiveDate: '2025-10-31',
    purchasePrice: 320000,
    processingCost: 72000,
    marginRate: 32,
    salesPrice: 520000,
    supplier: '제조사',
    note: '스크린 셔터 견적산출용 샘플',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-10-31',
    createdBy: '시스템'
  },
  {
    id: 'PRICE-SAMPLE-003',
    itemId: 'SAMPLE-003',
    itemCode: '견적산출용 샘플3',
    itemName: '견적산출용 샘플3',
    itemType: 'FG',
    unit: 'SET',
    effectiveDate: '2025-10-31',
    purchasePrice: 380000,
    processingCost: 90000,
    marginRate: 35,
    salesPrice: 600000,
    supplier: '제조사',
    note: '철재 셔터 견적산출용 샘플',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-10-31',
    createdBy: '시스템'
  },
  {
    id: 'PRICE-SAMPLE-004',
    itemId: 'SAMPLE-004',
    itemCode: '견적산출용 샘플4',
    itemName: '견적산출용 샘플4',
    itemType: 'FG',
    unit: 'SET',
    effectiveDate: '2025-10-31',
    purchasePrice: 465000,
    processingCost: 115000,
    marginRate: 38,
    salesPrice: 750000,
    supplier: '제조사',
    note: '철재 셔터 견적산출용 샘플',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-10-31',
    createdBy: '시스템'
  },
  {
    id: 'PRICE-SAMPLE-005',
    itemId: 'SAMPLE-005',
    itemCode: '견적산출용 샘플5',
    itemName: '견적산출용 샘플5',
    itemType: 'FG',
    unit: 'SET',
    effectiveDate: '2025-10-31',
    purchasePrice: 295000,
    processingCost: 70000,
    marginRate: 30,
    salesPrice: 480000,
    supplier: '제조사',
    note: '스크린 셔터 견적산출용 샘플',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-10-31',
    createdBy: '시스템'
  },
  // 부품 단가 샘플 데이터
  {
    id: 'PRICE-PART-001',
    itemId: 'PART-001',
    itemCode: 'GR-001',
    itemName: '가이드레일 130×80',
    itemType: 'PT',
    unit: 'EA',
    effectiveDate: '2025-11-24',
    purchasePrice: 45000,
    processingCost: 5000,
    marginRate: 20,
    salesPrice: 60000,
    unitPrice: 60000,
    supplier: '가이드레일 공급사',
    note: '스크린용 가이드레일',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-11-24',
    createdBy: '시스템'
  },
  {
    id: 'PRICE-PART-002',
    itemId: 'PART-002',
    itemCode: 'CASE-001',
    itemName: '케이스 철재',
    itemType: 'PT',
    unit: 'EA',
    effectiveDate: '2025-11-24',
    purchasePrice: 35000,
    processingCost: 10000,
    marginRate: 25,
    salesPrice: 56250,
    unitPrice: 56250,
    supplier: '철재 공급사',
    note: '케이스용 철재',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-11-24',
    createdBy: '시스템'
  },
  {
    id: 'PRICE-PART-003',
    itemId: 'PART-003',
    itemCode: 'MOTOR-001',
    itemName: '모터 0.4KW',
    itemType: 'PT',
    unit: 'EA',
    effectiveDate: '2025-11-24',
    purchasePrice: 120000,
    processingCost: 10000,
    marginRate: 15,
    salesPrice: 149500,
    unitPrice: 149500,
    supplier: '모터 공급사',
    note: '0.4KW 모터',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-11-24',
    createdBy: '시스템'
  },
  {
    id: 'PRICE-PART-004',
    itemId: 'PART-004',
    itemCode: 'CTL-001',
    itemName: '제어기 기본형',
    itemType: 'PT',
    unit: 'EA',
    effectiveDate: '2025-11-24',
    purchasePrice: 80000,
    processingCost: 5000,
    marginRate: 20,
    salesPrice: 102000,
    unitPrice: 102000,
    supplier: '제어기 공급사',
    note: '기본형 제어기',
    currentRevision: 0,
    isFinal: false,
    status: 'active',
    createdAt: '2025-11-24',
    createdBy: '시스템'
  }
];

const initialClients: Client[] = [
  {
    id: "CLI-001",
    code: "2083",
    businessNumber: "1378627566",
    name: "오정건설주식회사",
    type: "매출",
    representative: "이정민",
    address: "경기도 김포시 통진읍 김포대로2462번길 8 1층",
    businessType: "건설업",
    businessCategory: "종합건설",
    phone: "031-1234-5678",
    mobile: "010-8755-4335",
    fax: "031-1234-5679",
    email: "ojc@example.com",
    managerName: "이담당",
    managerTel: "010-1111-2222",
    memo: "주요 거래처",
    status: "활성",
    createdAt: "2025-01-15"
  },
  {
    id: "CLI-002",
    code: "2084",
    businessNumber: "2234567890",
    name: "(주)한국건설",
    type: "매출",
    representative: "김철수",
    address: "서울시 강남구 테헤란로 123",
    businessType: "건설업",
    businessCategory: "건축공사",
    phone: "02-1234-5678",
    mobile: "010-2222-3333",
    fax: "02-1234-5679",
    email: "hankook@example.com",
    managerName: "박담당",
    managerTel: "010-3333-4444",
    memo: "강남 오피스빌딩 주거래처",
    status: "활성",
    createdAt: "2025-01-15"
  },
  {
    id: "CLI-003",
    code: "2085",
    businessNumber: "3345678901",
    name: "부산건설",
    type: "매출",
    representative: "최영희",
    address: "부산시 해운대구 해운대로 567",
    businessType: "건설업",
    businessCategory: "토목공사",
    phone: "051-1234-5678",
    mobile: "010-4444-5555",
    fax: "051-1234-5679",
    email: "busan@example.com",
    managerName: "김부산",
    managerTel: "010-5555-6666",
    memo: "",
    status: "활성",
    createdAt: "2025-01-20"
  },
  {
    id: "CLI-004",
    code: "2086",
    businessNumber: "4456789012",
    name: "인천건설",
    type: "매출",
    representative: "송인천",
    address: "인천시 연수구 송도대로 100",
    businessType: "건설업",
    businessCategory: "종합건설",
    phone: "032-1234-5678",
    mobile: "010-6666-7777",
    fax: "032-1234-5679",
    email: "incheon@example.com",
    managerName: "최담당",
    managerTel: "010-7777-8888",
    memo: "송도 오피스텔 프로젝트",
    status: "활성",
    createdAt: "2025-01-20"
  },
  {
    id: "CLI-005",
    code: "1001",
    businessNumber: "5567890123",
    name: "서진TNS",
    type: "매입",
    representative: "서진우",
    address: "경기도 안산시 단원구 산단로 456",
    businessType: "제조업",
    businessCategory: "알루미늄 압출",
    phone: "031-5555-6666",
    mobile: "010-8888-9999",
    fax: "031-5555-6667",
    email: "seojin@example.com",
    managerName: "이자재",
    managerTel: "010-9999-0000",
    memo: "알루미늄 압출재 주거래처",
    status: "활성",
    createdAt: "2025-01-10"
  },
  {
    id: "CLI-006",
    code: "1002",
    businessNumber: "6678901234",
    name: "대한철강",
    type: "매입",
    representative: "대한수",
    address: "경기도 시흥시 공단대로 789",
    businessType: "제조업",
    businessCategory: "철강 제조",
    phone: "031-6666-7777",
    mobile: "010-1111-3333",
    fax: "031-6666-7778",
    email: "daehan@example.com",
    managerName: "강철수",
    managerTel: "010-2222-4444",
    memo: "SUS, EGI 강판 공급",
    status: "활성",
    createdAt: "2025-01-10"
  }
];

// 초기 사용자 데이터 (데모 계정 + 회원가입 사용자)
const initialUsers: User[] = [
  {
    id: "USER-001",
    username: "ceo",
    email: "ceo@demo.com",
    password: "ceo123",
    name: "김대표",
    role: "CEO",
    companyName: "데모 기업",
    position: "대표이사",
    isActive: true,
    createdAt: "2025-01-01"
  },
  {
    id: "USER-002",
    username: "manager",
    email: "manager@demo.com",
    password: "manager123",
    name: "박관리",
    role: "ProductionManager",
    companyName: "데모 기업",
    position: "생산관리자",
    isActive: true,
    createdAt: "2025-01-01"
  },
  {
    id: "USER-003",
    username: "worker",
    email: "worker@demo.com",
    password: "worker123",
    name: "이생산",
    role: "Worker",
    companyName: "데모 기업",
    position: "생산직",
    isActive: true,
    createdAt: "2025-01-01"
  },
  {
    id: "USER-004",
    username: "admin",
    email: "admin@demo.com",
    password: "admin123",
    name: "최시스템",
    role: "SystemAdmin",
    companyName: "데모 기업",
    position: "시스템관리자",
    isActive: true,
    createdAt: "2025-01-01"
  },
  {
    id: "USER-005",
    username: "sales",
    email: "sales@demo.com",
    password: "sales123",
    name: "박영업",
    role: "Sales",
    companyName: "데모 기업",
    position: "영업사원",
    isActive: true,
    createdAt: "2025-01-01"
  }
];

// ===== Context 생성 =====
const DataContext = createContext<DataContextType | undefined>(undefined);

// ===== Provider 컴포넌트 =====
export function DataProvider({ children }: { children: ReactNode }) {
  // 상태 관리
  const [salesOrders, setSalesOrders] = useState<SalesOrder[]>(() => {
    const saved = localStorage.getItem('mes-salesOrders');
    return saved ? JSON.parse(saved) : initialSalesOrders;
  });

  const [quotes, setQuotes] = useState<Quote[]>(() => {
    const saved = localStorage.getItem('mes-quotes');
    return saved ? JSON.parse(saved) : initialQuotes;
  });

  const [productionOrders, setProductionOrders] = useState<ProductionOrder[]>(() => {
    const saved = localStorage.getItem('mes-productionOrders');
    return saved ? JSON.parse(saved) : initialProductionOrders;
  });

  const [qualityInspections, setQualityInspections] = useState<QualityInspection[]>(() => {
    const saved = localStorage.getItem('mes-qualityInspections');
    return saved ? JSON.parse(saved) : initialQualityInspections;
  });

  const [inventoryItems, setInventoryItems] = useState<InventoryItem[]>(() => {
    const saved = localStorage.getItem('mes-inventoryItems');
    return saved ? JSON.parse(saved) : initialInventoryItems;
  });

  const [purchaseOrders, setPurchaseOrders] = useState<PurchaseOrder[]>(() => {
    const saved = localStorage.getItem('mes-purchaseOrders');
    return saved ? JSON.parse(saved) : initialPurchaseOrders;
  });

  const [employees, setEmployees] = useState<Employee[]>(() => {
    const saved = localStorage.getItem('mes-employees');
    return saved ? JSON.parse(saved) : initialEmployees;
  });

  const [attendances, setAttendances] = useState<Attendance[]>(() => {
    const saved = localStorage.getItem('mes-attendances');
    return saved ? JSON.parse(saved) : initialAttendances;
  });

  const [approvals, setApprovals] = useState<Approval[]>(() => {
    const saved = localStorage.getItem('mes-approvals');
    return saved ? JSON.parse(saved) : initialApprovals;
  });

  const [vehicles, setVehicles] = useState<Vehicle[]>(() => {
    const saved = localStorage.getItem('mes-vehicles');
    return saved ? JSON.parse(saved) : initialVehicles;
  });

  const [accountingTransactions, setAccountingTransactions] = useState<AccountingTransaction[]>(() => {
    const saved = localStorage.getItem('mes-accountingTransactions');
    return saved ? JSON.parse(saved) : initialAccountingTransactions;
  });

  const [sites, setSites] = useState<Site[]>(() => {
    const saved = localStorage.getItem('mes-sites');
    return saved ? JSON.parse(saved) : initialSites;
  });

  const [clients, setClients] = useState<Client[]>(() => {
    const saved = localStorage.getItem('mes-clients');
    return saved ? JSON.parse(saved) : initialClients;
  });

  const [receivables, setReceivables] = useState<Receivable[]>(() => {
    const saved = localStorage.getItem('mes-receivables');
    return saved ? JSON.parse(saved) : initialReceivables;
  });

  const [itemMasters, setItemMasters] = useState<ItemMaster[]>(() => {
    const saved = localStorage.getItem('mes-itemMasters');
    const version = localStorage.getItem('mes-itemMasters-version');
    const currentVersion = '1.1'; // 샘플 제품 데이터 포함
    
    // 버전이 다르거나 저장된 데이터가 없으면 샘플 데이터로 초기화
    if (version !== currentVersion || !saved) {
      localStorage.setItem('mes-itemMasters-version', currentVersion);
      
      // 샘플 제품 데이터
      return [
        {
          id: 'FG-001',
          itemCode: 'SCREEN-001',
          itemName: '스크린 셔터 기본형',
          itemType: 'FG',
          itemCategory: '스크린',
          category1: '스크린',
          unit: 'SET',
          specification: '표준형',
          description: '스크린 셔터 기본 제품',
          status: 'active',
          isActive: true,
          createdAt: new Date().toISOString()
        },
        {
          id: 'FG-002',
          itemCode: 'SCREEN-002',
          itemName: '스크린 셔터 오픈형',
          itemType: 'FG',
          itemCategory: '오픈사이즈',
          category1: '스크린',
          unit: 'SET',
          specification: '오픈형',
          description: '스크린 셔터 오픈 사이즈',
          status: 'active',
          isActive: true,
          createdAt: new Date().toISOString()
        },
        {
          id: 'FG-003',
          itemCode: 'STEEL-001',
          itemName: '철재 셔터 기본형',
          itemType: 'FG',
          itemCategory: '철재',
          category1: '철재',
          unit: 'SET',
          specification: '표준형',
          description: '철재 셔터 기본 제품',
          status: 'active',
          isActive: true,
          createdAt: new Date().toISOString()
        },
        {
          id: 'PT-001',
          itemCode: 'GR-001',
          itemName: '가이드레일 130×80',
          itemType: 'PT',
          itemCategory: '가이드레일',
          category1: '철재',
          unit: 'EA',
          specification: '130×80×2438',
          description: '스크린용 가이드레일',
          status: 'active',
          isActive: true,
          createdAt: new Date().toISOString()
        },
        {
          id: 'PT-002',
          itemCode: 'CASE-001',
          itemName: '케이스 철재',
          itemType: 'PT',
          itemCategory: '케이스',
          category1: '철재',
          unit: 'EA',
          specification: '표준형',
          description: '케이스용 철재',
          status: 'active',
          isActive: true,
          createdAt: new Date().toISOString()
        },
        {
          id: 'PT-003',
          itemCode: 'MOTOR-001',
          itemName: '모터 0.4KW',
          itemType: 'PT',
          itemCategory: '모터',
          category1: '전기',
          unit: 'EA',
          specification: '0.4KW',
          description: '0.4KW 모터',
          status: 'active',
          isActive: true,
          createdAt: new Date().toISOString()
        },
        {
          id: 'PT-004',
          itemCode: 'CTL-001',
          itemName: '제어기 기본형',
          itemType: 'PT',
          itemCategory: '제어기',
          category1: '전기',
          unit: 'EA',
          specification: '기본형',
          description: '기본형 제어기',
          status: 'active',
          isActive: true,
          createdAt: new Date().toISOString()
        }
      ];
    }
    
    return JSON.parse(saved);
  });

  const [specificationMasters, setSpecificationMasters] = useState<SpecificationMaster[]>(() => {
    const saved = localStorage.getItem('mes-specificationMasters');
    const version = localStorage.getItem('mes-specificationMasters-version');
    const currentVersion = '1.0'; // 품목명별 규격 버전
    
    // 버전이 다르면 초기 데이터로 재설정
    if (saved && version === currentVersion) {
      return JSON.parse(saved);
    }
    
    // 버전 업데이트 시 새 버전 저장
    localStorage.setItem('mes-specificationMasters-version', currentVersion);
    
    // 초기 규격 데이터 (품목명별)
    const initialSpecs: SpecificationMaster[] = [
      // SPHC-SD 규격
      { id: 'spec-001', specificationCode: '1219*1200', itemType: 'RM', itemName: 'SPHC-SD', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '1200', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-002', specificationCode: '1219*2438', itemType: 'RM', itemName: 'SPHC-SD', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '2438', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-003', specificationCode: '1219*3000', itemType: 'RM', itemName: 'SPHC-SD', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '3000', isActive: true, createdAt: new Date().toISOString() },
      
      // SPCC-SD 규격
      { id: 'spec-004', specificationCode: '1219*1200', itemType: 'RM', itemName: 'SPCC-SD', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '1200', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-005', specificationCode: '1219*2438', itemType: 'RM', itemName: 'SPCC-SD', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '2438', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-006', specificationCode: '1219*3000', itemType: 'RM', itemName: 'SPCC-SD', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '3000', isActive: true, createdAt: new Date().toISOString() },
      
      // SECC 규격
      { id: 'spec-007', specificationCode: '1219*1200', itemType: 'RM', itemName: 'SECC', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '1200', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-008', specificationCode: '1219*2438', itemType: 'RM', itemName: 'SECC', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '2438', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-009', specificationCode: '1219*3000', itemType: 'RM', itemName: 'SECC', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '3000', isActive: true, createdAt: new Date().toISOString() },
      
      // SGCC 규격
      { id: 'spec-010', specificationCode: '1219*1200', itemType: 'RM', itemName: 'SGCC', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '1200', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-011', specificationCode: '1219*2438', itemType: 'RM', itemName: 'SGCC', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '2438', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-012', specificationCode: '1219*3000', itemType: 'RM', itemName: 'SGCC', fieldCount: '1', thickness: '1.6', widthA: '1219', length: '3000', isActive: true, createdAt: new Date().toISOString() },
      
      // SPHD 규격
      { id: 'spec-013', specificationCode: '1219*1200', itemType: 'RM', itemName: 'SPHD', fieldCount: '1', thickness: '2.0', widthA: '1219', length: '1200', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-014', specificationCode: '1219*2438', itemType: 'RM', itemName: 'SPHD', fieldCount: '1', thickness: '2.0', widthA: '1219', length: '2438', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-015', specificationCode: '1219*3000', itemType: 'RM', itemName: 'SPHD', fieldCount: '1', thickness: '2.0', widthA: '1219', length: '3000', isActive: true, createdAt: new Date().toISOString() },
      
      // SS330 규격
      { id: 'spec-016', specificationCode: '1219*1200', itemType: 'RM', itemName: 'SS330', fieldCount: '1', thickness: '2.3', widthA: '1219', length: '1200', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-017', specificationCode: '1219*2438', itemType: 'RM', itemName: 'SS330', fieldCount: '1', thickness: '2.3', widthA: '1219', length: '2438', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-018', specificationCode: '1219*3000', itemType: 'RM', itemName: 'SS330', fieldCount: '1', thickness: '2.3', widthA: '1219', length: '3000', isActive: true, createdAt: new Date().toISOString() },
      
      // SS400 규격
      { id: 'spec-019', specificationCode: '1219*1200', itemType: 'RM', itemName: 'SS400', fieldCount: '1', thickness: '2.3', widthA: '1219', length: '1200', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-020', specificationCode: '1219*2438', itemType: 'RM', itemName: 'SS400', fieldCount: '1', thickness: '2.3', widthA: '1219', length: '2438', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-021', specificationCode: '1219*3000', itemType: 'RM', itemName: 'SS400', fieldCount: '1', thickness: '2.3', widthA: '1219', length: '3000', isActive: true, createdAt: new Date().toISOString() },
      
      // STS304 규격
      { id: 'spec-022', specificationCode: '1219*1200', itemType: 'RM', itemName: 'STS304', fieldCount: '1', thickness: '1.5', widthA: '1219', length: '1200', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-023', specificationCode: '1219*2438', itemType: 'RM', itemName: 'STS304', fieldCount: '1', thickness: '1.5', widthA: '1219', length: '2438', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-024', specificationCode: '1219*3000', itemType: 'RM', itemName: 'STS304', fieldCount: '1', thickness: '1.5', widthA: '1219', length: '3000', isActive: true, createdAt: new Date().toISOString() },
      
      // STS430 규격
      { id: 'spec-025', specificationCode: '1219*1200', itemType: 'RM', itemName: 'STS430', fieldCount: '1', thickness: '1.5', widthA: '1219', length: '1200', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-026', specificationCode: '1219*2438', itemType: 'RM', itemName: 'STS430', fieldCount: '1', thickness: '1.5', widthA: '1219', length: '2438', isActive: true, createdAt: new Date().toISOString() },
      { id: 'spec-027', specificationCode: '1219*3000', itemType: 'RM', itemName: 'STS430', fieldCount: '1', thickness: '1.5', widthA: '1219', length: '3000', isActive: true, createdAt: new Date().toISOString() },
    ];
    
    return initialSpecs;
  });

  const [materialItemNames, setMaterialItemNames] = useState<MaterialItemName[]>(() => {
    const saved = localStorage.getItem('mes-materialItemNames');
    const version = localStorage.getItem('mes-materialItemNames-version');
    const currentVersion = '1.1'; // 품목명 확장 버전 (89개 품목)
    
    // 버전이 다르면 초기 데이터로 재설정
    if (saved && version === currentVersion) {
      return JSON.parse(saved);
    }
    
    // 버전 업데이트 시 새 버전 저장
    localStorage.setItem('mes-materialItemNames-version', currentVersion);
    
    // 초기 품목명 데이터
    const initialMaterialItems: MaterialItemName[] = [
      // 원자재 (RM) - 철판/강판류
      { id: 'mat-001', itemType: 'RM', itemName: 'SPHC-SD', category: '냉연강판', description: '일반냉연강판', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-002', itemType: 'RM', itemName: 'SPCC-SD', category: '냉연강판', description: '냉연강판', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-003', itemType: 'RM', itemName: 'SECC', category: '냉연강판', description: '전기아연도금강판', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-004', itemType: 'RM', itemName: 'SGCC', category: '냉연강판', description: '용융아연도금강판', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-005', itemType: 'RM', itemName: 'SPHD', category: '열연강판', description: '열연강판', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-006', itemType: 'RM', itemName: 'SS330', category: '일반구조용강', description: '일반구조용강재', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-007', itemType: 'RM', itemName: 'SS400', category: '일반구조용강', description: '일반구조용강재', isActive: true, createdAt: new Date().toISOString() },
      
      // 원자재 (RM) - 스테인리스
      { id: 'mat-008', itemType: 'RM', itemName: 'STS304', category: '스테인리스', description: '스테인리스강판 304', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-009', itemType: 'RM', itemName: 'STS430', category: '스테인리스', description: '스테인리스강판 430', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-010', itemType: 'RM', itemName: 'STS316', category: '스테인리스', description: '스테인리스강판 316', isActive: true, createdAt: new Date().toISOString() },
      
      // 원자재 (RM) - 알루미늄
      { id: 'mat-011', itemType: 'RM', itemName: 'AL5052', category: '알루미늄', description: '알루미늄합금 5052', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-012', itemType: 'RM', itemName: 'AL6063', category: '알루미늄', description: '알루미늄합금 6063', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-013', itemType: 'RM', itemName: 'AL1050', category: '알루미늄', description: '알루미늄 1050', isActive: true, createdAt: new Date().toISOString() },
      
      // 원자재 (RM) - 파이프/각관
      { id: 'mat-014', itemType: 'RM', itemName: '각파이프', category: '파이프류', description: '각형강관', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-015', itemType: 'RM', itemName: '원형파이프', category: '파이프류', description: '원형강관', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-016', itemType: 'RM', itemName: 'STS파이프', category: '파이프류', description: '스테인리스파이프', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-017', itemType: 'RM', itemName: '앵글', category: '형강류', description: '등변앵글', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-018', itemType: 'RM', itemName: '채널', category: '형강류', description: 'C형강', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-019', itemType: 'RM', itemName: 'H빔', category: '형강류', description: 'H형강', isActive: true, createdAt: new Date().toISOString() },
      
      // 원자재 (RM) - 기타 금속
      { id: 'mat-020', itemType: 'RM', itemName: '황동판', category: '비철금속', description: '황동', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-021', itemType: 'RM', itemName: '구리판', category: '비철금속', description: '구리', isActive: true, createdAt: new Date().toISOString() },
      
      // 부자재 (SM) - 체결부품
      { id: 'mat-101', itemType: 'SM', itemName: '육각볼트', category: '체결부품', description: '육각머리볼트', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-102', itemType: 'SM', itemName: '육각너트', category: '체결부품', description: '육각너트', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-103', itemType: 'SM', itemName: '평와셔', category: '체결부품', description: '평와셔', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-104', itemType: 'SM', itemName: '스프링와셔', category: '체결부품', description: '스프링와셔', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-105', itemType: 'SM', itemName: '십자나사', category: '체결부품', description: '십자머리나사', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-106', itemType: 'SM', itemName: '접시나사', category: '체결부품', description: '접시머리나사', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-107', itemType: 'SM', itemName: '렌치볼트', category: '체결부품', description: '육각구멍붙이볼트', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-108', itemType: 'SM', itemName: '탭핑나사', category: '체결부품', description: '태핑나사', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-109', itemType: 'SM', itemName: '리벳', category: '체결부품', description: '리벳', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-110', itemType: 'SM', itemName: '앵커볼트', category: '체결부품', description: '앵커볼트', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-111', itemType: 'SM', itemName: '케미컬앵커', category: '체결부품', description: '케미컬앵커', isActive: true, createdAt: new Date().toISOString() },
      
      // 부자재 (SM) - 용접/접착
      { id: 'mat-201', itemType: 'SM', itemName: '용접봉', category: '용접재료', description: '용접봉', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-202', itemType: 'SM', itemName: '용접와이어', category: '용접재료', description: '용접와이어', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-203', itemType: 'SM', itemName: '실리콘', category: '접착/실링', description: '실리콘실란트', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-204', itemType: 'SM', itemName: '우레탄', category: '접착/실링', description: '우레탄실란트', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-205', itemType: 'SM', itemName: '에폭시', category: '접착/실링', description: '에폭시접착제', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-206', itemType: 'SM', itemName: '순간접착제', category: '접착/실링', description: '순간접착제', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-207', itemType: 'SM', itemName: '양면테이프', category: '접착/실링', description: '양면테이프', isActive: true, createdAt: new Date().toISOString() },
      
      // 부자재 (SM) - 도장/표면처리
      { id: 'mat-301', itemType: 'SM', itemName: '도료(백색)', category: '도장재료', description: '백색도료', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-302', itemType: 'SM', itemName: '도료(흑색)', category: '도장재료', description: '흑색도료', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-303', itemType: 'SM', itemName: '도료(회색)', category: '도장재료', description: '회색도료', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-304', itemType: 'SM', itemName: '신나', category: '도장재료', description: '희석제', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-305', itemType: 'SM', itemName: '프라이머', category: '도장재료', description: '방청프라이머', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-306', itemType: 'SM', itemName: '분체도료', category: '도장재료', description: '분체도료', isActive: true, createdAt: new Date().toISOString() },
      
      // 부자재 (SM) - 연마/연삭
      { id: 'mat-401', itemType: 'SM', itemName: '연마지', category: '연마재', description: '샌드페이퍼', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-402', itemType: 'SM', itemName: '연마석', category: '연마재', description: '연마석', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-403', itemType: 'SM', itemName: '절단석', category: '연마재', description: '절단석', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-404', itemType: 'SM', itemName: '와이어브러쉬', category: '연마재', description: '와이어브러쉬', isActive: true, createdAt: new Date().toISOString() },
      
      // 부자재 (SM) - 기타 부자재
      { id: 'mat-501', itemType: 'SM', itemName: '고무패��', category: '패킹/가스켓', description: '고무패킹', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-502', itemType: 'SM', itemName: '우레탄폼', category: '충진재', description: '우레탄폼', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-503', itemType: 'SM', itemName: '보양테이프', category: '보양재', description: '마스킹테이프', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-504', itemType: 'SM', itemName: '보호필름', category: '보양재', description: '표면보호필름', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-505', itemType: 'SM', itemName: '윤활유', category: '유류', description: '윤활유', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-506', itemType: 'SM', itemName: '절삭유', category: '유류', description: '절삭유', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-507', itemType: 'SM', itemName: '방청유', category: '유류', description: '방청유', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-508', itemType: 'SM', itemName: '탈지제', category: '세정제', description: '탈지제', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-509', itemType: 'SM', itemName: '감기샤프트', category: '샤프트/축', description: '감기샤프트', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-510', itemType: 'SM', itemName: '개폐암', category: '구동부품', description: '개폐암', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-511', itemType: 'SM', itemName: '경첩', category: '체결부품', description: '경첩', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-512', itemType: 'SM', itemName: '고정핀', category: '체결부품', description: '고정핀', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-513', itemType: 'SM', itemName: '고정클램프', category: '체결부품', description: '고정클램프', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-514', itemType: 'SM', itemName: '구동모터', category: '모터/동력', description: '구동모터', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-515', itemType: 'SM', itemName: '기어모터', category: '모터/동력', description: '기어모터', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-516', itemType: 'SM', itemName: '너클', category: '구동부품', description: '너클', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-517', itemType: 'SM', itemName: '드럼', category: '구동부품', description: '드럼', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-518', itemType: 'SM', itemName: '롤러', category: '구동부품', description: '롤러', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-519', itemType: 'SM', itemName: '브라켓', category: '구조부품', description: '브라켓', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-520', itemType: 'SM', itemName: '베어링', category: '베어링류', description: '베어링', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-521', itemType: 'SM', itemName: '볼트', category: '체결부품', description: '볼트', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-522', itemType: 'SM', itemName: '부싱', category: '베어링류', description: '부싱', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-523', itemType: 'SM', itemName: '샤프트', category: '샤프트/축', description: '샤프트', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-524', itemType: 'SM', itemName: '스냅링', category: '체결부품', description: '스냅링', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-525', itemType: 'SM', itemName: '스프링', category: '스프링류', description: '스프링', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-526', itemType: 'SM', itemName: '스프로킷', category: '구동부품', description: '스프로킷', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-527', itemType: 'SM', itemName: '스프링와셔', category: '체결부품', description: '스프링와셔', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-528', itemType: 'SM', itemName: '실', category: '패킹/가스켓', description: '실', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-529', itemType: 'SM', itemName: '안전키', category: '체결부품', description: '안전키', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-530', itemType: 'SM', itemName: '연결핀', category: '체결부품', description: '연결핀', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-531', itemType: 'SM', itemName: '와셔', category: '체결부품', description: '와셔', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-532', itemType: 'SM', itemName: '와이어로프', category: '와이어/체인', description: '와이어로프', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-533', itemType: 'SM', itemName: '체인', category: '와이어/체인', description: '체인', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-534', itemType: 'SM', itemName: '축', category: '샤프트/축', description: '축', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-535', itemType: 'SM', itemName: '커플링', category: '구동부품', description: '커플링', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-536', itemType: 'SM', itemName: '턴버클', category: '체결부품', description: '턴버클', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-537', itemType: 'SM', itemName: '플렌지', category: '구조부품', description: '플렌지', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-538', itemType: 'SM', itemName: '풀리', category: '구동부품', description: '풀리', isActive: true, createdAt: new Date().toISOString() },
      { id: 'mat-539', itemType: 'SM', itemName: '핀', category: '체결부품', description: '핀', isActive: true, createdAt: new Date().toISOString() },
      
      // 원자재 (RM) - 추가 품목
      { id: 'mat-022', itemType: 'RM', itemName: 'EGI0.8T', category: '냉연강판', description: '전기아연도금강판 0.8T', isActive: true, createdAt: new Date().toISOString() },
    ];
    
    return initialMaterialItems;
  });

  const [shippingOrders, setShippingOrders] = useState<ShippingOrder[]>(() => {
    const saved = localStorage.getItem('mes-shippingOrders');
    return saved ? JSON.parse(saved) : initialShippingOrders;
  });

  const [formulas, setFormulas] = useState<CalculationFormula[]>(() => {
    const saved = localStorage.getItem('mes-formulas');
    return saved ? JSON.parse(saved) : initialFormulas;
  });

  const [formulaRules, setFormulaRules] = useState<FormulaRule[]>(() => {
    const saved = localStorage.getItem('mes-formulaRules');
    const version = localStorage.getItem('mes-formulaRules-version');
    const currentVersion = '2.4'; // 1단계 결과 타입 지원
    
    // 버전이 다르면 초기 데이터로 재설정
    if (version !== currentVersion) {
      localStorage.setItem('mes-formulaRules-version', currentVersion);
      return initialFormulaRules;
    }
    
    return saved ? JSON.parse(saved) : initialFormulaRules;
  });

  const [stage2Mappings, setStage2Mappings] = useState<Stage2Mapping[]>(() => {
    const saved = localStorage.getItem('mes-stage2Mappings');
    return saved ? JSON.parse(saved) : initialStage2Mappings;
  });

  const [pricing, setPricing] = useState<PricingData[]>(() => {
    const saved = localStorage.getItem('mes-pricing');
    const version = localStorage.getItem('mes-pricing-version');
    const currentVersion = '1.1'; // 기존 SAM_PRICINGS 마이그레이션
    
    // 기존 SAM_PRICINGS 데이터가 있는지 확인하고 마이그레이션
    const oldPricings = localStorage.getItem('SAM_PRICINGS');
    
    // 버전이 다르거나 저장된 데이터가 없을 때
    if (version !== currentVersion || !saved) {
      localStorage.setItem('mes-pricing-version', currentVersion);
      
      // 기존 SAM_PRICINGS 데이터가 있으면 마이그레이션
      if (oldPricings) {
        try {
          const oldData = JSON.parse(oldPricings);
          if (Array.isArray(oldData) && oldData.length > 0) {
            console.log(`✅ ${oldData.length}개의 단가 데이터를 SAM_PRICINGS에서 마이그레이션했습니다.`);
            return oldData;
          }
        } catch (e) {
          console.error('SAM_PRICINGS 마이그레이션 실패:', e);
        }
      }
      
      // 마이그레이션할 데이터가 없으면 초기 데이터 사용
      return initialPricing;
    }
    
    return saved ? JSON.parse(saved) : initialPricing;
  });

  const [calculationHistories, setCalculationHistories] = useState<CalculationHistory[]>(() => {
    const saved = localStorage.getItem('mes-calculationHistories');
    return saved ? JSON.parse(saved) : [];
  });

  // 검사기준 상태 관리
  const [inspectionStandards, setInspectionStandards] = useState<InspectionStandard[]>(() => {
    const saved = localStorage.getItem('mes-inspectionStandards');
    return saved ? JSON.parse(saved) : [];
  });

  // 검사기준 localStorage 저장
  useEffect(() => {
    localStorage.setItem('mes-inspectionStandards', JSON.stringify(inspectionStandards));
  }, [inspectionStandards]);

  // LOT번호 규칙 초기 데이터
  const initialLotNumberRules: LotNumberRule[] = [
    {
      id: 'lot-rule-001',
      ruleName: '견적번호 기준',
      applyTo: ['quote'],
      prefix: 'KD-PR',
      useDate: true,
      dateFormat: 'YYMMDD',
      sequenceDigits: 2,
      separator: '-',
      example: 'KD-PR-251119-01',
      description: '견적번호 생성 규칙',
      isActive: true,
      createdAt: new Date().toISOString(),
    },
    {
      id: 'lot-rule-002',
      ruleName: '수주번호 기준',
      applyTo: ['salesOrder'],
      prefix: 'KD-SO',
      useDate: true,
      dateFormat: 'YYMMDD',
      sequenceDigits: 2,
      separator: '-',
      example: 'KD-SO-251119-01',
      description: '수주번호 생성 규칙',
      isActive: true,
      createdAt: new Date().toISOString(),
    },
    {
      id: 'lot-rule-003',
      ruleName: '생산지시번호 기준',
      applyTo: ['production'],
      prefix: 'KD-MO',
      useDate: true,
      dateFormat: 'YYMMDD',
      sequenceDigits: 2,
      separator: '-',
      example: 'KD-MO-251119-01',
      description: '생산지시번호 생성 규칙',
      isActive: true,
      createdAt: new Date().toISOString(),
    },
    {
      id: 'lot-rule-004',
      ruleName: '출하지시번호 기준',
      applyTo: ['shipping'],
      prefix: 'KD-OT',
      useDate: true,
      dateFormat: 'YYMMDD',
      sequenceDigits: 2,
      separator: '-',
      example: 'KD-OT-251119-01',
      description: '출하지시번호 생성 규칙',
      isActive: true,
      createdAt: new Date().toISOString(),
    },
    {
      id: 'lot-rule-005',
      ruleName: '발주번호 기준',
      applyTo: ['purchase'],
      prefix: 'KD-PO',
      useDate: true,
      dateFormat: 'YYMMDD',
      sequenceDigits: 2,
      separator: '-',
      example: 'KD-PO-251119-01',
      description: '발주번호 생성 규칙',
      isActive: true,
      createdAt: new Date().toISOString(),
    }
  ];

  const [lotNumberRules, setLotNumberRules] = useState<LotNumberRule[]>(() => {
    const saved = localStorage.getItem('mes-lotNumberRules');
    return saved ? JSON.parse(saved) : initialLotNumberRules;
  });

  // 품목 기준정보 마스터 데이터 상태
  const [itemCategories, setItemCategories] = useState<ItemCategory[]>(() => {
    const saved = localStorage.getItem('mes-itemCategories');
    if (!saved) {
      // 초기 데이터 생성
      const initialData: ItemCategory[] = [
        { id: 'CAT-001', categoryType: 'PRODUCT', category1: '스크린', code: 'SC', description: '스크린 셔터', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-002', categoryType: 'PRODUCT', category1: '철재문', code: 'SD', description: '철재 방화문', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-003', categoryType: 'PRODUCT', category1: '블라인드', code: 'BL', description: '블라인드', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-101', categoryType: 'PART', category1: '가이드레일', code: 'GR', description: '가이드레일 부품', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-102', categoryType: 'PART', category1: '하단마감재', code: 'BF', description: '하단마감재', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-103', categoryType: 'PART', category1: '케이스', code: 'CS', description: '케이스 부품', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-104', categoryType: 'PART', category1: '도어', code: 'DR', description: '도어 부품', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-105', categoryType: 'PART', category1: '브라켓', code: 'BR', description: '브라켓 부품', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-201', categoryType: 'MATERIAL', category1: '강판', code: 'SP', description: '강판 원자재', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-202', categoryType: 'MATERIAL', category1: '알루미늄', code: 'AL', description: '알루미늄 원��재', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-203', categoryType: 'MATERIAL', category1: '플라스틱', code: 'PL', description: '플라스틱 원자재', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-301', categoryType: 'SUB_MATERIAL', category1: '볼트너트', code: 'BN', description: '볼트/너트', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-302', categoryType: 'SUB_MATERIAL', category1: '나사', code: 'SC', description: '나사류', isActive: true, createdAt: '2025-01-01' },
        { id: 'CAT-303', categoryType: 'SUB_MATERIAL', category1: '페인트', code: 'PT', description: '도료', isActive: true, createdAt: '2025-01-01' },
      ];
      return initialData;
    }
    return JSON.parse(saved);
  });

  const [itemUnits, setItemUnits] = useState<ItemUnit[]>(() => {
    const saved = localStorage.getItem('mes-itemUnits');
    if (!saved) {
      const initialData: ItemUnit[] = [
        { id: 'UNIT-001', unitCode: 'EA', unitName: 'EA (개)', description: '낱개 단위', isActive: true, createdAt: '2025-01-01' },
        { id: 'UNIT-002', unitCode: 'SET', unitName: 'SET (세트)', description: '세트 단위', isActive: true, createdAt: '2025-01-01' },
        { id: 'UNIT-003', unitCode: 'M', unitName: 'M (미터)', description: '길이 단위', isActive: true, createdAt: '2025-01-01' },
        { id: 'UNIT-004', unitCode: 'KG', unitName: 'KG (킬로그램)', description: '무게 단위', isActive: true, createdAt: '2025-01-01' },
        { id: 'UNIT-005', unitCode: 'L', unitName: 'L (리터)', description: '부피 단위', isActive: true, createdAt: '2025-01-01' },
        { id: 'UNIT-006', unitCode: 'M2', unitName: '㎡ (제곱미터)', description: '면적 단위', isActive: true, createdAt: '2025-01-01' },
        { id: 'UNIT-007', unitCode: 'BOX', unitName: 'BOX (박스)', description: '박스 단위', isActive: true, createdAt: '2025-01-01' },
      ];
      return initialData;
    }
    return JSON.parse(saved);
  });

  const [itemMaterials, setItemMaterials] = useState<ItemMaterial[]>(() => {
    const saved = localStorage.getItem('mes-itemMaterials');
    if (!saved) {
      const initialData: ItemMaterial[] = [
        { id: 'MAT-001', materialCode: 'EGI-1.2T', materialName: 'EGI 1.2T', materialType: 'STEEL', thickness: '1.2T', description: '전기아연도금강판', isActive: true, createdAt: '2025-01-01' },
        { id: 'MAT-002', materialCode: 'EGI-1.55T', materialName: 'EGI 1.55T', materialType: 'STEEL', thickness: '1.55T', description: '전기아연도금강판', isActive: true, createdAt: '2025-01-01' },
        { id: 'MAT-003', materialCode: 'EGI-2.0T', materialName: 'EGI 2.0T', materialType: 'STEEL', thickness: '2.0T', description: '전기아연도금강판', isActive: true, createdAt: '2025-01-01' },
        { id: 'MAT-004', materialCode: 'SUS-1.2T', materialName: 'SUS 1.2T', materialType: 'STEEL', thickness: '1.2T', description: '스테인리스 강판', isActive: true, createdAt: '2025-01-01' },
        { id: 'MAT-005', materialCode: 'SUS-1.5T', materialName: 'SUS 1.5T', materialType: 'STEEL', thickness: '1.5T', description: '스테인리스 강판', isActive: true, createdAt: '2025-01-01' },
        { id: 'MAT-006', materialCode: 'AL-6063', materialName: '알루미늄 6063', materialType: 'ALUMINUM', description: '알루미늄 압출재', isActive: true, createdAt: '2025-01-01' },
        { id: 'MAT-007', materialCode: 'AL-6061', materialName: '알루미늄 6061', materialType: 'ALUMINUM', description: '알루미늄 압출재', isActive: true, createdAt: '2025-01-01' },
      ];
      return initialData;
    }
    return JSON.parse(saved);
  });

  const [surfaceTreatments, setSurfaceTreatments] = useState<SurfaceTreatment[]>(() => {
    const saved = localStorage.getItem('mes-surfaceTreatments');
    if (!saved) {
      const initialData: SurfaceTreatment[] = [
        { id: 'TREAT-001', treatmentCode: 'NONE', treatmentName: '무도장', treatmentType: 'NONE', description: '표면처리 없음', isActive: true, createdAt: '2025-01-01' },
        { id: 'TREAT-002', treatmentCode: 'POWDER', treatmentName: '파우더도장', treatmentType: 'PAINTING', description: '분체도장', isActive: true, createdAt: '2025-01-01' },
        { id: 'TREAT-003', treatmentCode: 'ANODIZING', treatmentName: '아노다이징', treatmentType: 'COATING', description: '알루미늄 양극산화처리', isActive: true, createdAt: '2025-01-01' },
        { id: 'TREAT-004', treatmentCode: 'ZINC', treatmentName: '아연도금', treatmentType: 'PLATING', description: '아연 도금처리', isActive: true, createdAt: '2025-01-01' },
        { id: 'TREAT-005', treatmentCode: 'CHROME', treatmentName: '크롬도금', treatmentType: 'PLATING', description: '크롬 도금처리', isActive: true, createdAt: '2025-01-01' },
      ];
      return initialData;
    }
    return JSON.parse(saved);
  });

  const [partTypeOptions, setPartTypeOptions] = useState<PartTypeOption[]>(() => {
    const saved = localStorage.getItem('mes-partTypeOptions');
    if (!saved) {
      const initialData: PartTypeOption[] = [
        { id: 'PTYPE-001', partType: 'ASSEMBLY', optionCode: 'ASSY', optionName: '조립품', description: '여러 부품을 조립하는 부품', isActive: true, createdAt: '2025-01-01' },
        { id: 'PTYPE-002', partType: 'BENDING', optionCode: 'BEND', optionName: '절곡품', description: '절곡 가공 부품', isActive: true, createdAt: '2025-01-01' },
        { id: 'PTYPE-003', partType: 'PURCHASED', optionCode: 'PURCH', optionName: '구매품', description: '외부에서 구매하는 부품', isActive: true, createdAt: '2025-01-01' },
      ];
      return initialData;
    }
    return JSON.parse(saved);
  });

  const [partUsageOptions, setPartUsageOptions] = useState<PartUsageOption[]>(() => {
    const saved = localStorage.getItem('mes-partUsageOptions');
    if (!saved) {
      const initialData: PartUsageOption[] = [
        { id: 'USAGE-001', usageCode: 'GUIDE_RAIL', usageName: '가이드레일', description: '가이드레일용 부품', isActive: true, createdAt: '2025-01-01' },
        { id: 'USAGE-002', usageCode: 'BOTTOM_FINISH', usageName: '하단마감재', description: '하단마감재용 부품', isActive: true, createdAt: '2025-01-01' },
        { id: 'USAGE-003', usageCode: 'CASE', usageName: '케이스', description: '케이스용 부품', isActive: true, createdAt: '2025-01-01' },
        { id: 'USAGE-004', usageCode: 'DOOR', usageName: '도어', description: '도어용 부품', isActive: true, createdAt: '2025-01-01' },
        { id: 'USAGE-005', usageCode: 'BRACKET', usageName: '브라켓', description: '브라켓 부품', isActive: true, createdAt: '2025-01-01' },
        { id: 'USAGE-006', usageCode: 'GENERAL', usageName: '일반', description: '일반 부품', isActive: true, createdAt: '2025-01-01' },
      ];
      return initialData;
    }
    return JSON.parse(saved);
  });

  const [guideRailOptions, setGuideRailOptions] = useState<GuideRailOption[]>(() => {
    const saved = localStorage.getItem('mes-guideRailOptions');
    if (!saved) {
      const initialData: GuideRailOption[] = [
        { id: 'GR-001', optionType: 'MODEL_TYPE', optionCode: 'SCREEN', optionName: '스크린용', description: '스크린 셔터용 가이드레일', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-002', optionType: 'MODEL_TYPE', optionCode: 'STEEL', optionName: '철재용', description: '철재문용 가이드레일', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-011', optionType: 'MODEL', optionCode: 'T40', optionName: 'T40', parentOption: 'SCREEN', description: 'T40 모델', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-012', optionType: 'MODEL', optionCode: 'T60', optionName: 'T60', parentOption: 'SCREEN', description: 'T60 모델', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-013', optionType: 'MODEL', optionCode: 'PREMIUM', optionName: '프리미엄', parentOption: 'STEEL', description: '프리미엄 모델', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-021', optionType: 'CERTIFICATION', optionCode: 'KFI', optionName: 'KFI인증', description: 'KFI 인증', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-022', optionType: 'CERTIFICATION', optionCode: 'NONE', optionName: '미인증', description: '인증 없음', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-031', optionType: 'SHAPE', optionCode: 'ROUND', optionName: 'R형', description: '라운드형', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-032', optionType: 'SHAPE', optionCode: 'SQUARE', optionName: 'ㄱ형', description: '사각형', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-041', optionType: 'FINISH', optionCode: 'POWDER', optionName: '파우더도장', description: '파우더 도장 마감', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-042', optionType: 'FINISH', optionCode: 'ANODIZING', optionName: '아노다이징', description: '아노다이징 마감', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-051', optionType: 'LENGTH', optionCode: '3000', optionName: '3000mm', description: '3미터', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-052', optionType: 'LENGTH', optionCode: '4000', optionName: '4000mm', description: '4미터', isActive: true, createdAt: '2025-01-01' },
        { id: 'GR-053', optionType: 'LENGTH', optionCode: '5000', optionName: '5000mm', description: '5미터', isActive: true, createdAt: '2025-01-01' },
      ];
      return initialData;
    }
    return JSON.parse(saved);
  });

  // 품목기준관리 섹션 템플릿
  const [sectionTemplates, setSectionTemplates] = useState<SectionTemplate[]>(() => {
    const saved = localStorage.getItem('mes-sectionTemplates');
    if (!saved) return [];
    return JSON.parse(saved);
  });

  useEffect(() => {
    localStorage.setItem('mes-sectionTemplates', JSON.stringify(sectionTemplates));
  }, [sectionTemplates]);

  // 카테고리 그룹
  const [categoryGroups, setCategoryGroups] = useState<CategoryGroup[]>(() => {
    const saved = localStorage.getItem('mes-categoryGroups');
    if (!saved) {
      // 샘플 데이터
      return [
        {
          id: 'CG-001',
          name: '스크린 제품',
          description: '스크린 관련 모든 제품',
          categories: ['스크린', '오픈사이즈', '제작사이즈', '실리카', '와이어'],
          createdAt: new Date().toISOString()
        },
        {
          id: 'CG-002',
          name: '철재 제품',
          description: '철재 관련 모든 제품',
          categories: ['철재', '가이드레일', '케이스', '프레임'],
          createdAt: new Date().toISOString()
        },
        {
          id: 'CG-003',
          name: '전기 부품',
          description: '전기/전자 관련 부품',
          categories: ['모터', '제어기', '센서', '스위치'],
          createdAt: new Date().toISOString()
        },
        {
          id: 'CG-004',
          name: '기타 부자재',
          description: '기타 부자재 및 소모품',
          categories: ['볼트', '너트', '와셔', '접착제', '테이프'],
          createdAt: new Date().toISOString()
        }
      ];
    }
    return JSON.parse(saved);
  });

  useEffect(() => {
    localStorage.setItem('mes-categoryGroups', JSON.stringify(categoryGroups));
  }, [categoryGroups]);

  // 품목기준관리 마스터 항목
  const [itemMasterFields, setItemMasterFields] = useState<ItemMasterField[]>(() => {
    const saved = localStorage.getItem('mes-itemMasterFields');
    if (!saved) {
      const initialData: ItemMasterField[] = [
        // 공통 필드
        {
          id: 'MASTER-001',
          name: '품목코드',
          fieldKey: 'itemCode',
          property: {
            inputType: 'textbox',
            required: true,
            row: 1,
            col: 1
          },
          category: '공통',
          description: '품목의 고유 코드',
          isActive: true,
          createdAt: '2025-01-01'
        },
        {
          id: 'MASTER-002',
          name: '품목명',
          fieldKey: 'itemName',
          property: {
            inputType: 'textbox',
            required: true,
            row: 1,
            col: 1
          },
          category: '공통',
          description: '품목의 이름',
          isActive: true,
          createdAt: '2025-01-01'
        },
        {
          id: 'MASTER-003',
          name: '품목유형',
          fieldKey: 'itemType',
          property: {
            inputType: 'dropdown',
            required: true,
            row: 1,
            col: 1,
            options: ['제품 (Finished Goods)', '부품 (Part)', '부자재 (Sub Material)', '원자재 (Raw Material)', '소모품 (Consumables)'],
            optionMapping: {
              'FG': '제품 (Finished Goods)',
              'PT': '부품 (Part)',
              'SM': '부자재 (Sub Material)',
              'RM': '원자재 (Raw Material)',
              'CS': '소모품 (Consumables)'
            }
          },
          category: '공통',
          description: '품목의 유형 (제품/부품/부자재/원자재/소모품)',
          isActive: true,
          createdAt: '2025-01-01'
        },
        {
          id: 'MASTER-004',
          name: '단위',
          fieldKey: 'unit',
          property: {
            inputType: 'dropdown',
            required: true,
            row: 1,
            col: 1,
            options: ['M', 'mm', 'EA', 'SET', 'KG', 'T', 'BOX', 'L', 'M2', 'M3', 'ROLL', 'SHEET', 'PACK']
          },
          category: '공통',
          description: '품목의 단위',
          isActive: true,
          createdAt: '2025-01-01'
        },
        // 부품 - 절곡품 재질
        {
          id: 'MASTER-005',
          name: '재질',
          fieldKey: 'material',
          property: {
            inputType: 'dropdown',
            required: false,
            row: 1,
            col: 1,
            options: ['EGI 1.15T', 'EGI 1.55T', 'SUS 1.2T', 'SUS 1.5T']
          },
          category: '부품-절곡',
          description: '절곡 부품의 재질',
          isActive: true,
          createdAt: '2025-01-01'
        },
        // 부품 - 절곡품 모양&길이
        {
          id: 'MASTER-006',
          name: '모양&길이',
          fieldKey: 'bendingLength',
          property: {
            inputType: 'dropdown',
            required: false,
            row: 1,
            col: 1,
            options: ['W50x3000', 'W50x4000', 'W80x3000', 'W80x4000', '1219', '2438', '3000', '3500', '4000', '4150', '4200', '4300']
          },
          category: '부품-절곡',
          description: '절곡 부품의 모양과 길이',
          isActive: true,
          createdAt: '2025-01-01'
        },
        // 부품 - 조립품 설치유형
        {
          id: 'MASTER-007',
          name: '설치유형',
          fieldKey: 'installationType',
          property: {
            inputType: 'dropdown',
            required: false,
            row: 1,
            col: 1,
            options: ['표준형 (C)']
          },
          category: '부품-조립',
          description: '조립 부품의 설치 유형',
          isActive: true,
          createdAt: '2025-01-01'
        },
        // 부품 - 조립품 길이
        {
          id: 'MASTER-008',
          name: '조립길이',
          fieldKey: 'assemblyLength',
          property: {
            inputType: 'dropdown',
            required: false,
            row: 1,
            col: 1,
            options: ['1219', '2438', '3000', '3500']
          },
          category: '부품-조립',
          description: '조립 부품의 길이',
          isActive: true,
          createdAt: '2025-01-01'
        },
        // 부품 - 조립품 마감처리
        {
          id: 'MASTER-009',
          name: '마감처리',
          fieldKey: 'finishing',
          property: {
            inputType: 'dropdown',
            required: false,
            row: 1,
            col: 1,
            options: ['SUS마감', 'EGI마감']
          },
          category: '부품-조립',
          description: '조립 부품의 마감 처리',
          isActive: true,
          createdAt: '2025-01-01'
        },
        // 제품 품목 상태
        {
          id: 'MASTER-010',
          name: '품목상태',
          fieldKey: 'isActive',
          property: {
            inputType: 'dropdown',
            required: false,
            row: 1,
            col: 1,
            options: ['활성', '비활성']
          },
          category: '제품',
          description: '품목의 활성화 상태',
          isActive: true,
          createdAt: '2025-01-01'
        }
      ];
      return initialData;
    }
    return JSON.parse(saved);
  });

  // 품목기준관리 페이지 구조
  const [itemPages, setItemPages] = useState<ItemPage[]>(() => {
    const saved = localStorage.getItem('mes-itemPages');
    if (!saved) {
      const initialData: ItemPage[] = [
        {
          id: 'PAGE-FG-001',
          pageName: '품목 등록',
          itemType: 'FG',
          isActive: true,
          createdAt: '2025-01-01',
          sections: [
            {
              id: 'SECTION-001',
              title: '기본정보',
              order: 1,
              isCollapsible: true,
              isCollapsed: false,
              createdAt: '2025-01-01',
              fields: [
                {
                  id: 'FIELD-001',
                  name: '품목코드',
                  fieldKey: 'itemCode',
                  property: {
                    inputType: 'textbox',
                    required: true,
                    row: 1,
                    col: 1,
                  },
                  createdAt: '2025-01-01',
                },
                {
                  id: 'FIELD-002',
                  name: '품목명',
                  fieldKey: 'itemName',
                  property: {
                    inputType: 'textbox',
                    required: true,
                    row: 2,
                    col: 1,
                  },
                  createdAt: '2025-01-01',
                },
                {
                  id: 'FIELD-003',
                  name: '분류',
                  fieldKey: 'category',
                  property: {
                    inputType: 'dropdown',
                    required: false,
                    row: 3,
                    col: 1,
                    options: ['제품', '부품', '원자재'],
                  },
                  createdAt: '2025-01-01',
                },
              ],
            },
            {
              id: 'SECTION-002',
              title: 'BOM',
              order: 2,
              isCollapsible: true,
              isCollapsed: false,
              category: ['제품'],
              createdAt: '2025-01-01',
              fields: [
                {
                  id: 'FIELD-004',
                  name: 'BOM 필요',
                  fieldKey: 'bomRequired',
                  property: {
                    inputType: 'checkbox',
                    required: false,
                    row: 1,
                    col: 1,
                  },
                  category: ['제품'],
                  createdAt: '2025-01-01',
                },
              ],
            },
          ],
        },
      ];
      return initialData;
    }
    return JSON.parse(saved);
  });

  // localStorage 동기화
  useEffect(() => {
    localStorage.setItem('mes-salesOrders', JSON.stringify(salesOrders));
  }, [salesOrders]);

  useEffect(() => {
    console.log("💾 localStorage 저장 - quotes:", quotes.length, "개");
    if (quotes.length > 0) {
      console.log("💾 마지막 견적:", quotes[quotes.length - 1]);
      console.log("💾 마지막 견적 BOM:", quotes[quotes.length - 1]?.bomCalculations?.length || 0, "개");
    }
    localStorage.setItem('mes-quotes', JSON.stringify(quotes));
  }, [quotes]);

  useEffect(() => {
    localStorage.setItem('mes-productionOrders', JSON.stringify(productionOrders));
  }, [productionOrders]);

  useEffect(() => {
    localStorage.setItem('mes-qualityInspections', JSON.stringify(qualityInspections));
  }, [qualityInspections]);

  useEffect(() => {
    localStorage.setItem('mes-inventoryItems', JSON.stringify(inventoryItems));
  }, [inventoryItems]);

  useEffect(() => {
    localStorage.setItem('mes-purchaseOrders', JSON.stringify(purchaseOrders));
  }, [purchaseOrders]);

  useEffect(() => {
    localStorage.setItem('mes-employees', JSON.stringify(employees));
  }, [employees]);

  useEffect(() => {
    localStorage.setItem('mes-attendances', JSON.stringify(attendances));
  }, [attendances]);

  useEffect(() => {
    localStorage.setItem('mes-approvals', JSON.stringify(approvals));
  }, [approvals]);

  useEffect(() => {
    localStorage.setItem('mes-vehicles', JSON.stringify(vehicles));
  }, [vehicles]);

  useEffect(() => {
    localStorage.setItem('mes-accountingTransactions', JSON.stringify(accountingTransactions));
  }, [accountingTransactions]);

  useEffect(() => {
    localStorage.setItem('mes-receivables', JSON.stringify(receivables));
  }, [receivables]);

  // useEffect(() => {
  //   localStorage.setItem('mes-itemMasters', JSON.stringify(itemMasters));
  // }, [itemMasters]);

  useEffect(() => {
    localStorage.setItem('mes-specificationMasters', JSON.stringify(specificationMasters));
  }, [specificationMasters]);

  useEffect(() => {
    localStorage.setItem('mes-materialItemNames', JSON.stringify(materialItemNames));
  }, [materialItemNames]);

  useEffect(() => {
    localStorage.setItem('mes-shippingOrders', JSON.stringify(shippingOrders));
  }, [shippingOrders]);

  useEffect(() => {
    localStorage.setItem('mes-sites', JSON.stringify(sites));
  }, [sites]);

  useEffect(() => {
    localStorage.setItem('mes-clients', JSON.stringify(clients));
  }, [clients]);

  useEffect(() => {
    localStorage.setItem('mes-formulas', JSON.stringify(formulas));
  }, [formulas]);

  useEffect(() => {
    localStorage.setItem('mes-formulaRules', JSON.stringify(formulaRules));
  }, [formulaRules]);

  useEffect(() => {
    localStorage.setItem('mes-pricing', JSON.stringify(pricing));
  }, [pricing]);

  useEffect(() => {
    localStorage.setItem('mes-calculationHistories', JSON.stringify(calculationHistories));
  }, [calculationHistories]);

  useEffect(() => {
    localStorage.setItem('mes-lotNumberRules', JSON.stringify(lotNumberRules));
  }, [lotNumberRules]);

  useEffect(() => {
    localStorage.setItem('mes-itemCategories', JSON.stringify(itemCategories));
  }, [itemCategories]);

  useEffect(() => {
    localStorage.setItem('mes-itemUnits', JSON.stringify(itemUnits));
  }, [itemUnits]);

  useEffect(() => {
    localStorage.setItem('mes-itemMaterials', JSON.stringify(itemMaterials));
  }, [itemMaterials]);

  useEffect(() => {
    localStorage.setItem('mes-surfaceTreatments', JSON.stringify(surfaceTreatments));
  }, [surfaceTreatments]);

  useEffect(() => {
    localStorage.setItem('mes-partTypeOptions', JSON.stringify(partTypeOptions));
  }, [partTypeOptions]);

  useEffect(() => {
    localStorage.setItem('mes-partUsageOptions', JSON.stringify(partUsageOptions));
  }, [partUsageOptions]);

  useEffect(() => {
    localStorage.setItem('mes-guideRailOptions', JSON.stringify(guideRailOptions));
  }, [guideRailOptions]);

  useEffect(() => {
    localStorage.setItem('mes-itemMasterFields', JSON.stringify(itemMasterFields));
  }, [itemMasterFields]);

  useEffect(() => {
    localStorage.setItem('mes-itemPages', JSON.stringify(itemPages));
  }, [itemPages]);

  const [users, setUsers] = useState<User[]>(() => {
    const saved = localStorage.getItem('mes-users');
    return saved ? JSON.parse(saved) : initialUsers;
  });

  // 현재 로그인한 사용자 (기본값: Sales 사용자)
  const [currentUser, setCurrentUser] = useState<User | null>(() => {
    const saved = localStorage.getItem('mes-currentUser');
    if (saved) {
      return JSON.parse(saved);
    }
    // 기본값으로 Sales 사용자 설정
    return initialUsers.find(u => u.username === 'sales') || initialUsers[0];
  });

  useEffect(() => {
    localStorage.setItem('mes-users', JSON.stringify(users));
  }, [users]);

  useEffect(() => {
    if (currentUser) {
      localStorage.setItem('mes-currentUser', JSON.stringify(currentUser));
    }
  }, [currentUser]);

  // pricing 데이터를 localStorage에 저장
  useEffect(() => {
    localStorage.setItem('mes-pricing', JSON.stringify(pricing));
  }, [pricing]);

  // 주요 상태들을 localStorage에 저장
  useEffect(() => {
    localStorage.setItem('mes-salesOrders', JSON.stringify(salesOrders));
  }, [salesOrders]);

  useEffect(() => {
    localStorage.setItem('mes-quotes', JSON.stringify(quotes));
  }, [quotes]);

  useEffect(() => {
    localStorage.setItem('mes-productionOrders', JSON.stringify(productionOrders));
  }, [productionOrders]);

  useEffect(() => {
    localStorage.setItem('mes-qualityInspections', JSON.stringify(qualityInspections));
  }, [qualityInspections]);

  useEffect(() => {
    localStorage.setItem('mes-inventoryItems', JSON.stringify(inventoryItems));
  }, [inventoryItems]);

  useEffect(() => {
    localStorage.setItem('mes-purchaseOrders', JSON.stringify(purchaseOrders));
  }, [purchaseOrders]);

  useEffect(() => {
    localStorage.setItem('mes-employees', JSON.stringify(employees));
  }, [employees]);

  useEffect(() => {
    localStorage.setItem('mes-attendances', JSON.stringify(attendances));
  }, [attendances]);

  useEffect(() => {
    localStorage.setItem('mes-approvals', JSON.stringify(approvals));
  }, [approvals]);

  useEffect(() => {
    localStorage.setItem('mes-vehicles', JSON.stringify(vehicles));
  }, [vehicles]);

  useEffect(() => {
    localStorage.setItem('mes-accountingTransactions', JSON.stringify(accountingTransactions));
  }, [accountingTransactions]);

  useEffect(() => {
    localStorage.setItem('mes-sites', JSON.stringify(sites));
  }, [sites]);

  useEffect(() => {
    localStorage.setItem('mes-clients', JSON.stringify(clients));
  }, [clients]);

  useEffect(() => {
    localStorage.setItem('mes-receivables', JSON.stringify(receivables));
  }, [receivables]);

  // useEffect(() => {
  //   localStorage.setItem('mes-itemMasters', JSON.stringify(itemMasters));
  // }, [itemMasters]);

  useEffect(() => {
    localStorage.setItem('mes-specificationMasters', JSON.stringify(specificationMasters));
  }, [specificationMasters]);

  useEffect(() => {
    localStorage.setItem('mes-materialItemNames', JSON.stringify(materialItemNames));
  }, [materialItemNames]);

  useEffect(() => {
    localStorage.setItem('mes-shippingOrders', JSON.stringify(shippingOrders));
  }, [shippingOrders]);

  useEffect(() => {
    localStorage.setItem('mes-formulas', JSON.stringify(formulas));
  }, [formulas]);

  useEffect(() => {
    localStorage.setItem('mes-formulaRules', JSON.stringify(formulaRules));
  }, [formulaRules]);

  useEffect(() => {
    localStorage.setItem('mes-stage2Mappings', JSON.stringify(stage2Mappings));
  }, [stage2Mappings]);

  // CRUD 함수들
  const value: DataContextType = {
    // 판매
    salesOrders,
    quotes,
    addSalesOrder: (order) => setSalesOrders(prev => [...prev, order]),
    updateSalesOrder: (id, updates) => setSalesOrders(prev => 
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    deleteSalesOrder: (id) => setSalesOrders(prev => prev.filter(item => item.id !== id)),
    addQuote: (quote) => {
      console.log("✨ DataContext addQuote 호출:", quote);
      console.log("✨ 추가할 견적:", { id: quote.id, quoteNumber: quote.quoteNumber, bomCount: quote.bomCalculations?.length });
      setQuotes(prev => {
        const newQuotes = [...prev, quote];
        console.log("✅ 견적 추가 완료 - 전체 견적 수:", newQuotes.length);
        return newQuotes;
      });
    },
    updateQuote: (id, updates) => setQuotes(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    reviseQuote: (id, updates, revisionReason, revisionBy) => {
      console.log("📝 reviseQuote 호출:", { id, revisionReason, revisionBy });
      setQuotes(prev => {
        const updatedQuotes = prev.map(item => {
          if (item.id === id) {
            // 현재 데이터를 이력에 저장
            const revision: QuoteRevision = {
              revisionNumber: item.currentRevision + 1,
              revisionDate: new Date().toISOString().split('T')[0],
              revisionBy: revisionBy || '시스템',
              revisionReason: revisionReason,
              previousData: { ...item }
            };
            
            const revisions = item.revisions || [];
            const newRevisions = [...revisions, revision];
            
            console.log("✅ 견적 수정 완료:", {
              id,
              oldRevision: item.currentRevision,
              newRevision: item.currentRevision + 1,
              revisionsCount: newRevisions.length,
              revisionReason
            });
            
            return {
              ...item,
              ...updates,
              currentRevision: item.currentRevision + 1,
              revisions: newRevisions
            };
          }
          return item;
        });
        
        console.log("🔍 업데이트된 견적 목록:", updatedQuotes.map(q => ({
          id: q.id,
          quoteNumber: q.quoteNumber,
          currentRevision: q.currentRevision,
          revisionsLength: q.revisions?.length || 0
        })));
        
        return updatedQuotes;
      });
    },
    finalizeQuote: (id, finalizedBy) => {
      setQuotes(prev => prev.map(item => 
        item.id === id 
          ? { 
              ...item, 
              isFinal: true, 
              status: 'finalized',
              finalizedDate: new Date().toISOString().split('T')[0],
              finalizedBy: finalizedBy || '시스템'
            } 
          : item
      ));
    },
    deleteQuote: (id) => setQuotes(prev => prev.filter(item => item.id !== id)),
    
    // 출하
    shippingOrders,
    addShippingOrder: (order) => setShippingOrders(prev => [...prev, order]),
    updateShippingOrder: (id, updates) => setShippingOrders(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),

    // 생산
    productionOrders,
    addProductionOrder: (order) => setProductionOrders(prev => [...prev, order]),
    updateProductionOrder: (id, updates) => setProductionOrders(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),

    // 품질
    qualityInspections,
    addQualityInspection: (inspection) => setQualityInspections(prev => [...prev, inspection]),
    updateQualityInspection: (id, updates) => setQualityInspections(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),

    // 재고
    inventoryItems,
    addInventoryItem: (item) => setInventoryItems(prev => [...prev, item]),
    updateInventoryItem: (id, updates) => setInventoryItems(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),

    // 구매
    purchaseOrders,
    addPurchaseOrder: (order) => setPurchaseOrders(prev => [...prev, order]),
    updatePurchaseOrder: (id, updates) => setPurchaseOrders(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),

    // 인사
    employees,
    attendances,
    addEmployee: (employee) => setEmployees(prev => [...prev, employee]),
    updateEmployee: (id, updates) => setEmployees(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    addAttendance: (attendance) => setAttendances(prev => [...prev, attendance]),

    // 결재
    approvals,
    addApproval: (approval) => setApprovals(prev => [...prev, approval]),
    updateApproval: (id, updates) => setApprovals(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),

    // 차량
    vehicles,
    addVehicle: (vehicle) => setVehicles(prev => [...prev, vehicle]),
    updateVehicle: (id, updates) => setVehicles(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),

    // 회계
    accountingTransactions,
    receivables,
    addAccountingTransaction: (transaction) => setAccountingTransactions(prev => [...prev, transaction]),
    addReceivable: (receivable) => setReceivables(prev => [...prev, receivable]),
    updateReceivable: (id, updates) => setReceivables(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),

    // 품목 마스터
    itemMasters,
    setItemMasters,
    addItemMaster: (item) => setItemMasters(prev => [...prev, item]),
    updateItemMaster: (id, updates) => setItemMasters(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    deleteItemMaster: (id) => setItemMasters(prev => prev.filter(item => item.id !== id)),

    // 규격 마스터
    specificationMasters,
    addSpecificationMaster: (spec) => setSpecificationMasters(prev => [...prev, spec]),
    updateSpecificationMaster: (id, updates) => setSpecificationMasters(prev =>
      prev.map(spec => spec.id === id ? { ...spec, ...updates } : spec)
    ),
    deleteSpecificationMaster: (id) => setSpecificationMasters(prev => prev.filter(spec => spec.id !== id)),

    // 원자재/부자재 품목명 마스터
    materialItemNames,
    addMaterialItemName: (item) => setMaterialItemNames(prev => [...prev, item]),
    updateMaterialItemName: (id, updates) => setMaterialItemNames(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates, updatedAt: new Date().toISOString() } : item)
    ),
    deleteMaterialItemName: (id) => setMaterialItemNames(prev => prev.filter(item => item.id !== id)),

    // 현장
    sites,
    addSite: (site) => setSites(prev => [...prev, site]),
    updateSite: (id, updates) => setSites(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    deleteSite: (id) => setSites(prev => prev.filter(item => item.id !== id)),

    // 거래처
    clients,
    addClient: (client) => setClients(prev => [...prev, client]),
    updateClient: (id, updates) => setClients(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    deleteClient: (id) => setClients(prev => prev.filter(item => item.id !== id)),

    // 계산식 관리
    formulas,
    addFormula: (formula) => setFormulas(prev => [...prev, formula]),
    updateFormula: (id, updates) => setFormulas(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    reviseFormula: (id, updates, revisionReason, revisionBy) => {
      setFormulas(prev => {
        return prev.map(item => {
          if (item.id === id) {
            // 현재 데이터를 이력에 저장
            const revision: FormulaRevision = {
              revisionNumber: item.currentRevision + 1,
              revisionDate: new Date().toISOString().split('T')[0],
              revisionBy: revisionBy || '시스템',
              revisionReason: revisionReason,
              previousData: { ...item }
            };
            
            const revisions = item.revisions || [];
            const newRevisions = [...revisions, revision];
            
            return {
              ...item,
              ...updates,
              currentRevision: item.currentRevision + 1,
              revisions: newRevisions
            };
          }
          return item;
        });
      });
    },
    finalizeFormula: (id, finalizedBy) => {
      setFormulas(prev => prev.map(item => 
        item.id === id 
          ? { 
              ...item, 
              isFinal: true, 
              status: 'finalized',
              finalizedDate: new Date().toISOString().split('T')[0],
              finalizedBy: finalizedBy || '시스템'
            } 
          : item
      ));
    },
    deleteFormula: (id) => setFormulas(prev => prev.filter(item => item.id !== id)),

    // 수식 규칙 관리
    formulaRules,
    setFormulaRules,
    addFormulaRule: (rule) => setFormulaRules(prev => [...prev, { 
      ...rule, 
      id: rule.id || `RULE-${Date.now()}`,
      createdAt: rule.createdAt || new Date().toISOString().split('T')[0],
      updatedAt: rule.updatedAt || new Date().toISOString().split('T')[0]
    }]),
    updateFormulaRule: (id, updates) => setFormulaRules(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates, updatedAt: new Date().toISOString().split('T')[0] } : item)
    ),
    reviseFormulaRule: (id, updates, revisionReason, revisionBy) => {
      setFormulaRules(prev => {
        return prev.map(item => {
          if (item.id === id) {
            // 현재 데이터를 이력에 저장
            const revision: FormulaRuleRevision = {
              revisionNumber: (item.currentRevision || 0) + 1,
              revisionDate: new Date().toISOString().split('T')[0],
              revisionBy: revisionBy || '시스템',
              revisionReason: revisionReason,
              previousData: {
                ranges: item.ranges,
                formula: item.formula,
                fixedValue: item.fixedValue,
                unit: item.unit,
                description: item.description,
                status: item.status
              }
            };
            
            const revisions = item.revisions || [];
            const newRevisions = [...revisions, revision];
            
            return {
              ...item,
              ...updates,
              currentRevision: (item.currentRevision || 0) + 1,
              revisions: newRevisions,
              updatedAt: new Date().toISOString().split('T')[0],
              updatedBy: revisionBy || '시스템'
            };
          }
          return item;
        });
      });
    },
    finalizeFormulaRule: (id, finalizedBy) => {
      setFormulaRules(prev => prev.map(item => 
        item.id === id 
          ? { 
              ...item, 
              isFinal: true, 
              finalizedDate: new Date().toISOString().split('T')[0],
              finalizedBy: finalizedBy || '시스템'
            } 
          : item
      ));
    },
    deleteFormulaRule: (id) => setFormulaRules(prev => prev.filter(item => item.id !== id)),

    // 2단계 프로세스 매핑 관리
    stage2Mappings,
    addStage2Mapping: (mapping: Stage2Mapping) => {
      const newMappings = [...stage2Mappings, mapping];
      setStage2Mappings(newMappings);
      localStorage.setItem('mes-stage2Mappings', JSON.stringify(newMappings));
    },
    updateStage2Mapping: (id: string, updates: Partial<Stage2Mapping>) => {
      const newMappings = stage2Mappings.map(item => 
        item.id === id ? { ...item, ...updates, updatedAt: new Date().toISOString() } : item
      );
      setStage2Mappings(newMappings);
      localStorage.setItem('mes-stage2Mappings', JSON.stringify(newMappings));
    },
    deleteStage2Mapping: (id: string) => {
      const newMappings = stage2Mappings.filter(item => item.id !== id);
      setStage2Mappings(newMappings);
      localStorage.setItem('mes-stage2Mappings', JSON.stringify(newMappings));
    },
    getStage2MappingsByStage1Rule: (stage1RuleId: string) => {
      return stage2Mappings.filter(m => m.stage1RuleId === stage1RuleId);
    },

    // 단가 관리
    pricing,
    addPricing: (newPricing) => setPricing(prev => [...prev, { 
      ...newPricing, 
      id: newPricing.id || `PRICE-${Date.now()}`,
      createdAt: newPricing.createdAt || new Date().toISOString().split('T')[0],
      updatedAt: newPricing.updatedAt || new Date().toISOString().split('T')[0]
    }]),
    updatePricing: (id, updates) => setPricing(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates, updatedAt: new Date().toISOString().split('T')[0], updatedBy: '관리자' } : item)
    ),
    revisePricing: (id, updates, revisionReason, revisionBy) => {
      setPricing(prev => {
        return prev.map(item => {
          if (item.id === id) {
            // 현재 데이터를 이력에 저장
            const revision: PriceRevision = {
              revisionNumber: (item.currentRevision || 0) + 1,
              revisionDate: new Date().toISOString().split('T')[0],
              revisionBy: revisionBy || '시스템',
              revisionReason: revisionReason,
              previousData: { ...item }
            };
            
            const revisions = item.revisions || [];
            const newRevisions = [...revisions, revision];
            
            return {
              ...item,
              ...updates,
              currentRevision: (item.currentRevision || 0) + 1,
              revisions: newRevisions,
              updatedAt: new Date().toISOString().split('T')[0],
              updatedBy: revisionBy || '시스템'
            };
          }
          return item;
        });
      });
    },
    finalizePricing: (id, finalizedBy) => {
      setPricing(prev => prev.map(item => 
        item.id === id 
          ? { 
              ...item, 
              isFinal: true, 
              status: 'finalized',
              finalizedDate: new Date().toISOString().split('T')[0],
              finalizedBy: finalizedBy || '시스템'
            } 
          : item
      ));
    },
    deletePricing: (id) => setPricing(prev => prev.filter(item => item.id !== id)),

    // 견적 자동 산출 내역 관리
    addCalculationHistory: (history) => {
      setCalculationHistories(prev => [...prev, history]);
    },
    updateCalculationHistory: (id, updates) => {
      setCalculationHistories(prev => prev.map(item =>
        item.id === id ? { ...item, ...updates } : item
      ));
    },
    deleteCalculationHistory: (id) => {
      setCalculationHistories(prev => prev.filter(item => item.id !== id));
    },

    // 품목 기준정보 관리
    itemCategories,
    itemUnits,
    itemMaterials,
    surfaceTreatments,
    partTypeOptions,
    partUsageOptions,
    guideRailOptions,

    addItemCategory: (category) => setItemCategories(prev => [...prev, category]),
    updateItemCategory: (id, updates) => setItemCategories(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    deleteItemCategory: (id) => setItemCategories(prev => prev.filter(item => item.id !== id)),

    addItemUnit: (unit) => setItemUnits(prev => [...prev, unit]),
    updateItemUnit: (id, updates) => setItemUnits(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    deleteItemUnit: (id) => setItemUnits(prev => prev.filter(item => item.id !== id)),

    addItemMaterial: (material) => setItemMaterials(prev => [...prev, material]),
    updateItemMaterial: (id, updates) => setItemMaterials(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    deleteItemMaterial: (id) => setItemMaterials(prev => prev.filter(item => item.id !== id)),

    addSurfaceTreatment: (treatment) => setSurfaceTreatments(prev => [...prev, treatment]),
    updateSurfaceTreatment: (id, updates) => setSurfaceTreatments(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    deleteSurfaceTreatment: (id) => setSurfaceTreatments(prev => prev.filter(item => item.id !== id)),

    addPartTypeOption: (option) => setPartTypeOptions(prev => [...prev, option]),
    updatePartTypeOption: (id, updates) => setPartTypeOptions(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    deletePartTypeOption: (id) => setPartTypeOptions(prev => prev.filter(item => item.id !== id)),

    addPartUsageOption: (option) => setPartUsageOptions(prev => [...prev, option]),
    updatePartUsageOption: (id, updates) => setPartUsageOptions(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    deletePartUsageOption: (id) => setPartUsageOptions(prev => prev.filter(item => item.id !== id)),

    addGuideRailOption: (option) => setGuideRailOptions(prev => [...prev, option]),
    updateGuideRailOption: (id, updates) => setGuideRailOptions(prev =>
      prev.map(item => item.id === id ? { ...item, ...updates } : item)
    ),
    deleteGuideRailOption: (id) => setGuideRailOptions(prev => prev.filter(item => item.id !== id)),

    // 품목기준관리 - 마스터 항목
    itemMasterFields,
    addItemMasterField: (field: ItemMasterField) => setItemMasterFields(prev => [...prev, field]),
    updateItemMasterField: (id: string, updates: Partial<ItemMasterField>) => setItemMasterFields(prev =>
      prev.map(field => field.id === id ? { ...field, ...updates } : field)
    ),
    deleteItemMasterField: (id: string) => setItemMasterFields(prev => prev.filter(field => field.id !== id)),
    
    // LOT번호 규칙 관리
    lotNumberRules,
    addLotNumberRule: (rule: LotNumberRule) => setLotNumberRules(prev => [...prev, rule]),
    updateLotNumberRule: (id: string, updates: Partial<LotNumberRule>) => setLotNumberRules(prev =>
      prev.map(rule => rule.id === id ? { ...rule, ...updates, updatedAt: new Date().toISOString() } : rule)
    ),
    deleteLotNumberRule: (id: string) => setLotNumberRules(prev => prev.filter(rule => rule.id !== id)),
    
    // 번호기준 생성 함수
    generateLotNumber: (documentType: 'quote' | 'salesOrder' | 'production' | 'shipping' | 'purchase') => {
      // 견적(quote)의 경우 KD-PR-YYYYMMDD-NN 형식 고정
      if (documentType === 'quote') {
        const today = new Date();
        const yyyy = String(today.getFullYear());
        const mm = String(today.getMonth() + 1).padStart(2, '0');
        const dd = String(today.getDate()).padStart(2, '0');
        const dateStr = `${yyyy}${mm}${dd}`;
        
        // 오늘 날짜의 기존 견적번호들 조회
        const existingNumbers = quotes
          .filter(q => q.quoteNumber?.startsWith(`KD-PR-${dateStr}`))
          .map(q => q.quoteNumber || '');
        
        // 순번 생성 (01부터 시작)
        const sequenceNum = String(existingNumbers.length + 1).padStart(2, '0');
        
        return `KD-PR-${dateStr}-${sequenceNum}`;
      }
      
      // 해당 문서 유형에 적용된 활성화된 규칙 찾기
      const rule = lotNumberRules.find(r => r.applyTo && r.applyTo.includes(documentType) && r.isActive);
      
      if (!rule) {
        // 규칙이 없으면 기본 형식 사용
        const today = new Date();
        const yy = String(today.getFullYear()).slice(-2);
        const mm = String(today.getMonth() + 1).padStart(2, '0');
        const dd = String(today.getDate()).padStart(2, '0');
        return `${documentType.toUpperCase()}-${yy}${mm}${dd}-01`;
      }
      
      // 날짜 형식 생성
      let dateStr = '';
      if (rule.useDate) {
        const today = new Date();
        const yyyy = String(today.getFullYear());
        const yy = String(today.getFullYear()).slice(-2);
        const mm = String(today.getMonth() + 1).padStart(2, '0');
        const dd = String(today.getDate()).padStart(2, '0');
        
        switch (rule.dateFormat) {
          case 'YYMMDD':
            dateStr = `${yy}${mm}${dd}`;
            break;
          case 'YYYYMMDD':
            dateStr = `${yyyy}${mm}${dd}`;
            break;
          case 'YYMM':
            dateStr = `${yy}${mm}`;
            break;
          case 'YYYYMM':
            dateStr = `${yyyy}${mm}`;
            break;
        }
      }
      
      // 오늘 날짜의 기존 번호들 조회
      let existingNumbers: string[] = [];
      
      switch (documentType) {
        case 'quote':
          existingNumbers = quotes
            .filter(q => q.quoteNumber?.startsWith(`${rule.prefix}${rule.separator}${dateStr}`))
            .map(q => q.quoteNumber || '');
          break;
        case 'salesOrder':
          existingNumbers = salesOrders
            .filter(o => o.orderNumber?.startsWith(`${rule.prefix}${rule.separator}${dateStr}`))
            .map(o => o.orderNumber);
          break;
        case 'production':
          existingNumbers = productionOrders
            .filter(o => o.productionNumber?.startsWith(`${rule.prefix}${rule.separator}${dateStr}`))
            .map(o => o.productionNumber);
          break;
        case 'shipping':
          existingNumbers = shippingOrders
            .filter(o => o.shippingNumber?.startsWith(`${rule.prefix}${rule.separator}${dateStr}`))
            .map(o => o.shippingNumber);
          break;
        case 'purchase':
          existingNumbers = purchaseOrders
            .filter(o => o.purchaseNumber?.startsWith(`${rule.prefix}${rule.separator}${dateStr}`))
            .map(o => o.purchaseNumber);
          break;
      }
      
      // 순번 생성
      const sequenceNum = String(existingNumbers.length + 1).padStart(rule.sequenceDigits, '0');
      
      // 최종 번호 조합
      const separator = rule.separator === '없음' ? '' : rule.separator;
      let lotNumber = rule.prefix;
      
      if (dateStr) {
        lotNumber += `${separator}${dateStr}`;
      }
      
      lotNumber += `${separator}${sequenceNum}`;
      
      return lotNumber;
    },
    
    // 품목기준관리 - 섹션 템플릿
    sectionTemplates,
    addSectionTemplate: (template: SectionTemplate) => {
      console.log('DataContext: Adding template', template);
      setSectionTemplates(prev => {
        const newTemplates = [...prev, template];
        console.log('DataContext: New templates array', newTemplates);
        return newTemplates;
      });
    },
    updateSectionTemplate: (id: string, updates: Partial<SectionTemplate>) => setSectionTemplates(prev =>
      prev.map(t => t.id === id ? { ...t, ...updates, updatedAt: new Date().toISOString().split('T')[0] } : t)
    ),
    deleteSectionTemplate: (id: string) => setSectionTemplates(prev => prev.filter(t => t.id !== id)),
    
    // 카테고리 그룹
    categoryGroups,
    addCategoryGroup: (group: CategoryGroup) => {
      setCategoryGroups(prev => [...prev, { 
        ...group, 
        id: group.id || `CG-${Date.now()}`,
        createdAt: group.createdAt || new Date().toISOString()
      }]);
    },
    updateCategoryGroup: (id: string, updates: Partial<CategoryGroup>) => {
      setCategoryGroups(prev => 
        prev.map(g => g.id === id ? { ...g, ...updates, updatedAt: new Date().toISOString() } : g)
      );
    },
    deleteCategoryGroup: (id: string) => {
      setCategoryGroups(prev => prev.filter(g => g.id !== id));
    },
    
    // 품목기준관리 계층구조
    itemPages,
    addItemPage: (page) => setItemPages(prev => [...prev, page]),
    updateItemPage: (id, updates) => setItemPages(prev =>
      prev.map(page => page.id === id ? { ...page, ...updates, updatedAt: new Date().toISOString().split('T')[0] } : page)
    ),
    deleteItemPage: (id) => setItemPages(prev => prev.filter(page => page.id !== id)),
    
    addSectionToPage: (pageId, section) => setItemPages(prev =>
      prev.map(page => 
        page.id === pageId 
          ? { ...page, sections: [...page.sections, section], updatedAt: new Date().toISOString().split('T')[0] }
          : page
      )
    ),
    updateSection: (pageId, sectionId, updates) => setItemPages(prev =>
      prev.map(page =>
        page.id === pageId
          ? {
              ...page,
              sections: page.sections.map(section =>
                section.id === sectionId ? { ...section, ...updates } : section
              ),
              updatedAt: new Date().toISOString().split('T')[0]
            }
          : page
      )
    ),
    deleteSection: (pageId, sectionId) => setItemPages(prev =>
      prev.map(page =>
        page.id === pageId
          ? {
              ...page,
              sections: page.sections.filter(section => section.id !== sectionId),
              updatedAt: new Date().toISOString().split('T')[0]
            }
          : page
      )
    ),
    
    addFieldToSection: (pageId, sectionId, field) => setItemPages(prev =>
      prev.map(page =>
        page.id === pageId
          ? {
              ...page,
              sections: page.sections.map(section =>
                section.id === sectionId
                  ? { ...section, fields: [...section.fields, field] }
                  : section
              ),
              updatedAt: new Date().toISOString().split('T')[0]
            }
          : page
      )
    ),
    updateField: (pageId, sectionId, fieldId, updates) => setItemPages(prev =>
      prev.map(page =>
        page.id === pageId
          ? {
              ...page,
              sections: page.sections.map(section =>
                section.id === sectionId
                  ? {
                      ...section,
                      fields: section.fields.map(field =>
                        field.id === fieldId ? { ...field, ...updates } : field
                      )
                    }
                  : section
              ),
              updatedAt: new Date().toISOString().split('T')[0]
            }
          : page
      )
    ),
    deleteField: (pageId, sectionId, fieldId) => setItemPages(prev =>
      prev.map(page =>
        page.id === pageId
          ? {
              ...page,
              sections: page.sections.map(section =>
                section.id === sectionId
                  ? { ...section, fields: section.fields.filter(field => field.id !== fieldId) }
                  : section
              ),
              updatedAt: new Date().toISOString().split('T')[0]
            }
          : page
      )
    ),
    reorderFields: (pageId, sectionId, fieldIds) => setItemPages(prev =>
      prev.map(page =>
        page.id === pageId
          ? {
              ...page,
              sections: page.sections.map(section =>
                section.id === sectionId
                  ? {
                      ...section,
                      fields: fieldIds.map((id, index) => {
                        const field = section.fields.find(f => f.id === id);
                        return field ? { ...field, order: index } : null;
                      }).filter(Boolean) as ItemField[]
                    }
                  : section
              ),
              updatedAt: new Date().toISOString().split('T')[0]
            }
          : page
      )
    ),
    reorderSections: (pageId, sectionIds) => setItemPages(prev =>
      prev.map(page =>
        page.id === pageId
          ? {
              ...page,
              sections: sectionIds.map((id, index) => {
                const section = page.sections.find(s => s.id === id);
                return section ? { ...section, order: index + 1 } : null;
              }).filter(Boolean) as ItemSection[],
              updatedAt: new Date().toISOString().split('T')[0]
            }
          : page
      )
    ),

    // 검사기준 관리
    inspectionStandards,
    addInspectionStandard: (standard) => {
      setInspectionStandards(prev => [...prev, standard]);
      toast.success('검사기준이 추가되었습니다.');
    },
    updateInspectionStandard: (id, updates) => {
      setInspectionStandards(prev =>
        prev.map(standard => standard.id === id ? { ...standard, ...updates, updatedAt: new Date().toISOString() } : standard)
      );
      toast.success('검사기준이 수정되었습니다.');
    },
    reviseInspectionStandard: (id, updates, revisionReason = '', revisionBy = '관리자') => {
      setInspectionStandards(prev =>
        prev.map(standard => {
          if (standard.id === id) {
            const newRevisionNumber = standard.currentRevision + 1;
            const newRevision = {
              revisionNumber: newRevisionNumber,
              revisionDate: new Date().toISOString(),
              revisionBy,
              revisionReason,
              previousData: { ...standard }
            };
            return {
              ...standard,
              ...updates,
              currentRevision: newRevisionNumber,
              revisions: [...(standard.revisions || []), newRevision],
              updatedAt: new Date().toISOString(),
              updatedBy: revisionBy
            };
          }
          return standard;
        })
      );
      toast.success(`검사기준이 ${updates.currentRevision || 1}차 수정되었습니다.`);
    },
    finalizeInspectionStandard: (id, finalizedBy = '관리자') => {
      setInspectionStandards(prev =>
        prev.map(standard =>
          standard.id === id
            ? {
                ...standard,
                isFinal: true,
                finalizedDate: new Date().toISOString(),
                finalizedBy,
                updatedAt: new Date().toISOString()
              }
            : standard
        )
      );
      toast.success('검사기준이 최종 확정되었습니다.');
    },
    deleteInspectionStandard: (id) => {
      setInspectionStandards(prev => prev.filter(standard => standard.id !== id));
      toast.success('검사기준이 삭제되었습니다.');
    },

    // 사용자 관리
    users,
    currentUser,
    setCurrentUser,
    addUser: (user) => setUsers(prev => [...prev, user]),
    updateUser: (id, updates) => setUsers(prev =>
      prev.map(user => user.id === id ? { ...user, ...updates } : user)
    ),
    deleteUser: (id) => setUsers(prev => prev.filter(user => user.id !== id)),
    getUserByUsername: (username) => users.find(user => user.username === username),

    // 초기화
    resetAllData: () => {
      setSalesOrders(initialSalesOrders);
      setQuotes(initialQuotes);
      setProductionOrders(initialProductionOrders);
      setQualityInspections(initialQualityInspections);
      setInventoryItems(initialInventoryItems);
      setPurchaseOrders(initialPurchaseOrders);
      setEmployees(initialEmployees);
      setAttendances(initialAttendances);
      setApprovals(initialApprovals);
      setVehicles(initialVehicles);
      setAccountingTransactions(initialAccountingTransactions);
      setReceivables(initialReceivables);
      setItemMasters(initialItemMasters);
      setSites(initialSites);
      setShippingOrders(initialShippingOrders);
      setClients(initialClients);
      setFormulas(initialFormulas);
      setFormulaRules(initialFormulaRules);
      setPricing(initialPricing);
      setUsers(initialUsers);
    },
    
    // 샘플 데이터 생성
    generateSampleQuoteData: () => {
      // 새로운 유틸리티 함수 사용
      const { items: newItems, itemCount } = generateCompleteSampleQuoteData();
      
      // 완제품 BOM 구조 추가
      const itemsWithBoms = addProductBoms(newItems);
      
      // ===== 1. 완제품 (FG) - 스크린 5종 =====
      const screenProducts = [
        { code: 'FG-SCR-001', name: '방화 스크린 셔터 (소형)', width: 1000, height: 2000, laborCost: 150000, installCost: 100000, category: 'SCREEN' },
        { code: 'FG-SCR-002', name: '방화 스크린 셔터 (중형)', width: 2000, height: 3000, laborCost: 200000, installCost: 150000, category: 'SCREEN' },
        { code: 'FG-SCR-003', name: '방화 스크린 셔터 (대형)', width: 3000, height: 4000, laborCost: 300000, installCost: 200000, category: 'SCREEN' },
        { code: 'FG-SCR-004', name: '방화 스크린 셔터 (특대)', width: 4000, height: 5000, laborCost: 400000, installCost: 300000, category: 'SCREEN' },
        { code: 'FG-SCR-005', name: '방화 스크린 셔터 (맞춤형)', width: 0, height: 0, laborCost: 250000, installCost: 180000, category: 'SCREEN' },
      ];
      
      screenProducts.forEach((prod, idx) => {
        newItems.push({
          id: `FG-SCR-${timestamp}-${idx}`,
          itemCode: prod.code,
          itemName: prod.name,
          itemType: 'FG',
          productCategory: prod.category as 'SCREEN',
          unit: 'EA',
          salesPrice: prod.laborCost + prod.installCost + 500000, // 인건비 + 설치비 + 자재비 기본값
          purchasePrice: 0,
          laborCost: prod.laborCost,
          installCost: prod.installCost,
          specification: `${prod.width}W x ${prod.height}H`,
          bom: [], // 아래에서 추가
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          status: '활성'
        });
      });
      
      // ===== 2. 완제품 (FG) - 철재 5종 =====
      const steelProducts = [
        { code: 'FG-STL-001', name: '철재 방화문 (소형)', width: 900, height: 2100, laborCost: 180000, installCost: 120000, category: 'STEEL' },
        { code: 'FG-STL-002', name: '철재 방화문 (중형)', width: 1800, height: 2400, laborCost: 250000, installCost: 170000, category: 'STEEL' },
        { code: 'FG-STL-003', name: '철재 방화문 (대형)', width: 2400, height: 3000, laborCost: 350000, installCost: 230000, category: 'STEEL' },
        { code: 'FG-STL-004', name: '철재 방화문 (양개)', width: 1800, height: 2400, laborCost: 300000, installCost: 200000, category: 'STEEL' },
        { code: 'FG-STL-005', name: '철재 방화문 (특수)', width: 0, height: 0, laborCost: 280000, installCost: 190000, category: 'STEEL' },
      ];
      
      steelProducts.forEach((prod, idx) => {
        newItems.push({
          id: `FG-STL-${timestamp}-${idx}`,
          itemCode: prod.code,
          itemName: prod.name,
          itemType: 'FG',
          productCategory: prod.category as 'STEEL',
          unit: 'EA',
          salesPrice: prod.laborCost + prod.installCost + 450000, // 인건비 + 설치비 + 자재비 기본값
          purchasePrice: 0,
          laborCost: prod.laborCost,
          installCost: prod.installCost,
          specification: `${prod.width}W x ${prod.height}H`,
          bom: [],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          status: '활성'
        });
      });
      
      // ===== 3. 반제품 (SF) - 스크린 부품 15종 =====
      const screenParts = [
        { code: 'SF-SCR-F01', name: '스크린 원단', unit: 'M2', price: 25000, formula: 'W*H/1000000' },
        { code: 'SF-SCR-F02', name: '가이드레일 (좌)', unit: 'M', price: 35000, formula: 'H/1000' },
        { code: 'SF-SCR-F03', name: '가이드레일 (우)', unit: 'M', price: 35000, formula: 'H/1000' },
        { code: 'SF-SCR-F04', name: '상부 케이스', unit: 'EA', price: 120000, formula: '' },
        { code: 'SF-SCR-F05', name: '하부 바텀바', unit: 'EA', price: 45000, formula: '' },
        { code: 'SF-SCR-M01', name: '모터 (0.75KW)', unit: 'EA', price: 350000, formula: '' },
        { code: 'SF-SCR-M02', name: '모터 (1.5KW)', unit: 'EA', price: 480000, formula: '' },
        { code: 'SF-SCR-M03', name: '모터 (2.2KW)', unit: 'EA', price: 620000, formula: '' },
        { code: 'SF-SCR-C01', name: '제어반 (표준)', unit: 'EA', price: 280000, formula: '' },
        { code: 'SF-SCR-C02', name: '제어반 (고급)', unit: 'EA', price: 450000, formula: '' },
        { code: 'SF-SCR-S01', name: '감지기 세트', unit: 'SET', price: 180000, formula: '' },
        { code: 'SF-SCR-W01', name: '권취축', unit: 'EA', price: 95000, formula: '' },
        { code: 'SF-SCR-B01', name: '브라켓 세트', unit: 'SET', price: 65000, formula: '' },
        { code: 'SF-SCR-E01', name: '엣지윙 (좌)', unit: 'M', price: 12000, formula: 'H/1000' },
        { code: 'SF-SCR-E02', name: '엣지윙 (우)', unit: 'M', price: 12000, formula: 'H/1000' },
      ];
      
      screenParts.forEach((part, idx) => {
        newItems.push({
          id: `SF-SCR-${timestamp}-${idx}`,
          itemCode: part.code,
          itemName: part.name,
          itemType: 'SF',
          productCategory: 'SCREEN',
          unit: part.unit,
          salesPrice: part.price,
          purchasePrice: Math.round(part.price * 0.7),
          specification: '스크린용 반제품',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          status: '활성'
        });
      });
      
      // ===== 4. 반제품 (SF) - 철재 부품 15종 =====
      const steelParts = [
        { code: 'SF-STL-D01', name: '철재 도어', unit: 'EA', price: 280000, formula: '' },
        { code: 'SF-STL-F01', name: '철재 프레임', unit: 'M', price: 45000, formula: '(W+H)*2/1000' },
        { code: 'SF-STL-P01', name: '철재 패널', unit: 'M2', price: 55000, formula: 'W*H/1000000' },
        { code: 'SF-STL-H01', name: '경첩 세트', unit: 'SET', price: 35000, formula: '' },
        { code: 'SF-STL-L01', name: '도어락', unit: 'EA', price: 85000, formula: '' },
        { code: 'SF-STL-L02', name: '도어락 (전자식)', unit: 'EA', price: 350000, formula: '' },
        { code: 'SF-STL-C01', name: '도어클로저', unit: 'EA', price: 95000, formula: '' },
        { code: 'SF-STL-S01', name: '실링재', unit: 'M', price: 8000, formula: '(W+H)*2/1000' },
        { code: 'SF-STL-G01', name: '유리 (방화)', unit: 'M2', price: 180000, formula: '' },
        { code: 'SF-STL-T01', name: '문턱', unit: 'EA', price: 45000, formula: '' },
        { code: 'SF-STL-V01', name: '환기구', unit: 'EA', price: 65000, formula: '' },
        { code: 'SF-STL-K01', name: '킥플레이트', unit: 'EA', price: 38000, formula: '' },
        { code: 'SF-STL-W01', name: '창틀', unit: 'M', price: 28000, formula: '' },
        { code: 'SF-STL-B01', name: '볼트/너트 세트', unit: 'SET', price: 15000, formula: '' },
        { code: 'SF-STL-P02', name: '파우더 도장', unit: 'M2', price: 25000, formula: 'W*H/1000000' },
      ];
      
      steelParts.forEach((part, idx) => {
        newItems.push({
          id: `SF-STL-${timestamp}-${idx}`,
          itemCode: part.code,
          itemName: part.name,
          itemType: 'SF',
          productCategory: 'STEEL',
          unit: part.unit,
          salesPrice: part.price,
          purchasePrice: Math.round(part.price * 0.7),
          specification: '철재용 반제품',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          status: '활성'
        });
      });
      
      // ===== 5. 부자재 (SM) 20종 =====
      const subMaterials = [
        { code: 'SM-B001', name: '볼트 M8x30', unit: 'EA', price: 150 },
        { code: 'SM-B002', name: '볼트 M10x40', unit: 'EA', price: 200 },
        { code: 'SM-N001', name: '너트 M8', unit: 'EA', price: 80 },
        { code: 'SM-N002', name: '너트 M10', unit: 'EA', price: 100 },
        { code: 'SM-W001', name: '와셔 M8', unit: 'EA', price: 50 },
        { code: 'SM-W002', name: '와셔 M10', unit: 'EA', price: 60 },
        { code: 'SM-R001', name: '리벳 4x10', unit: 'EA', price: 40 },
        { code: 'SM-R002', name: '리벳 5x12', unit: 'EA', price: 50 },
        { code: 'SM-A001', name: '앵커볼트 M10', unit: 'EA', price: 350 },
        { code: 'SM-A002', name: '앵커볼트 M12', unit: 'EA', price: 450 },
        { code: 'SM-S001', name: '실리콘 (투명)', unit: 'EA', price: 8500 },
        { code: 'SM-S002', name: '실리콘 (백색)', unit: 'EA', price: 8500 },
        { code: 'SM-T001', name: '양면테이프', unit: 'M', price: 1200 },
        { code: 'SM-C001', name: '케이블타이', unit: 'EA', price: 100 },
        { code: 'SM-P001', name: '보호필름', unit: 'M', price: 2500 },
        { code: 'SM-G001', name: '그리스', unit: 'EA', price: 12000 },
        { code: 'SM-O001', name: '윤활유', unit: 'L', price: 15000 },
        { code: 'SM-E001', name: '전선 2.5SQ', unit: 'M', price: 1800 },
        { code: 'SM-E002', name: '전선 4.0SQ', unit: 'M', price: 2500 },
        { code: 'SM-L001', name: 'LED 표시등', unit: 'EA', price: 5500 },
      ];
      
      subMaterials.forEach((mat, idx) => {
        newItems.push({
          id: `SM-${timestamp}-${idx}`,
          itemCode: mat.code,
          itemName: mat.name,
          itemType: 'SM',
          unit: mat.unit,
          salesPrice: mat.price,
          purchasePrice: Math.round(mat.price * 0.8),
          specification: '공용 부자재',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          status: '활성'
        });
      });
      
      // ===== 6. 원자재 (RM) 15종 =====
      const rawMaterials = [
        { code: 'RM-S001', name: '강판 1.2T', unit: 'KG', price: 3500 },
        { code: 'RM-S002', name: '강판 1.6T', unit: 'KG', price: 3800 },
        { code: 'RM-S003', name: '강판 2.0T', unit: 'KG', price: 4200 },
        { code: 'RM-A001', name: '알루미늄 프로파일', unit: 'M', price: 15000 },
        { code: 'RM-A002', name: '알루미늄 판재', unit: 'KG', price: 8500 },
        { code: 'RM-P001', name: '파우더 도료 (흰색)', unit: 'KG', price: 12000 },
        { code: 'RM-P002', name: '파우더 도료 (검정)', unit: 'KG', price: 12000 },
        { code: 'RM-P003', name: '파우더 도료 (회색)', unit: 'KG', price: 12000 },
        { code: 'RM-F001', name: '방화원단 A급', unit: 'M', price: 18000 },
        { code: 'RM-F002', name: '방화원단 B급', unit: 'M', price: 22000 },
        { code: 'RM-R001', name: '고무 패킹', unit: 'M', price: 3500 },
        { code: 'RM-W001', name: '목재 (집성목)', unit: 'M', price: 25000 },
        { code: 'RM-G001', name: '유리섬유', unit: 'KG', price: 15000 },
        { code: 'RM-I001', name: '단열재', unit: 'M2', price: 12000 },
        { code: 'RM-C001', name: '케이블 피복재', unit: 'M', price: 2800 },
      ];
      
      rawMaterials.forEach((mat, idx) => {
        newItems.push({
          id: `RM-${timestamp}-${idx}`,
          itemCode: mat.code,
          itemName: mat.name,
          itemType: 'RM',
          unit: mat.unit,
          salesPrice: mat.price,
          purchasePrice: Math.round(mat.price * 0.75),
          specification: '원자재',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          status: '활성'
        });
      });
      
      // ===== 7. BOM 구조 추가 - 스크린 제품 =====
      // FG-SCR-001 (소형 스크린)
      newItems[0].bom = [
        { childItemCode: 'SF-SCR-F01', childItemName: '스크린 원단', quantity: 1, unit: 'M2', quantityFormula: 'W*H/1000000', note: '오픈사이즈 기준' },
        { childItemCode: 'SF-SCR-F02', childItemName: '가이드레일 (좌)', quantity: 1, unit: 'M', quantityFormula: 'H/1000', note: '높이 기준' },
        { childItemCode: 'SF-SCR-F03', childItemName: '가이드레일 (우)', quantity: 1, unit: 'M', quantityFormula: 'H/1000', note: '높이 기준' },
        { childItemCode: 'SF-SCR-F04', childItemName: '상부 케이스', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-F05', childItemName: '하부 바텀바', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-M01', childItemName: '모터 (0.75KW)', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-C01', childItemName: '제어반 (표준)', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-S01', childItemName: '감지기 세트', quantity: 1, unit: 'SET', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-W01', childItemName: '권취축', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-B01', childItemName: '브라켓 세트', quantity: 1, unit: 'SET', quantityFormula: '', note: '' },
        { childItemCode: 'SM-B002', childItemName: '볼트 M10x40', quantity: 20, unit: 'EA', quantityFormula: '', note: '조립용' },
        { childItemCode: 'SM-N002', childItemName: '너트 M10', quantity: 20, unit: 'EA', quantityFormula: '', note: '조립용' },
      ];
      
      // FG-SCR-002 (중형 스크린)
      newItems[1].bom = [
        { childItemCode: 'SF-SCR-F01', childItemName: '스크린 원단', quantity: 1, unit: 'M2', quantityFormula: 'W*H/1000000', note: '오픈사이즈 기준' },
        { childItemCode: 'SF-SCR-F02', childItemName: '가이드레일 (좌)', quantity: 1, unit: 'M', quantityFormula: 'H/1000', note: '높이 기준' },
        { childItemCode: 'SF-SCR-F03', childItemName: '가이드레일 (우)', quantity: 1, unit: 'M', quantityFormula: 'H/1000', note: '높이 기준' },
        { childItemCode: 'SF-SCR-F04', childItemName: '상부 케이스', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-F05', childItemName: '하부 바텀바', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-M02', childItemName: '모터 (1.5KW)', quantity: 1, unit: 'EA', quantityFormula: '', note: '중형용' },
        { childItemCode: 'SF-SCR-C01', childItemName: '제어반 (표준)', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-S01', childItemName: '감지기 세트', quantity: 1, unit: 'SET', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-W01', childItemName: '권취축', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-B01', childItemName: '브라켓 세트', quantity: 2, unit: 'SET', quantityFormula: '', note: '중형용 2세트' },
        { childItemCode: 'SF-SCR-E01', childItemName: '엣지윙 (좌)', quantity: 1, unit: 'M', quantityFormula: 'H/1000', note: '높이 기준' },
        { childItemCode: 'SF-SCR-E02', childItemName: '엣지윙 (우)', quantity: 1, unit: 'M', quantityFormula: 'H/1000', note: '높이 기준' },
        { childItemCode: 'SM-B002', childItemName: '볼트 M10x40', quantity: 30, unit: 'EA', quantityFormula: '', note: '조립용' },
      ];
      
      // FG-SCR-003 (대형 스크린)
      newItems[2].bom = [
        { childItemCode: 'SF-SCR-F01', childItemName: '스크린 원단', quantity: 1, unit: 'M2', quantityFormula: 'W*H/1000000', note: '오픈사이즈 기준' },
        { childItemCode: 'SF-SCR-F02', childItemName: '가이드레일 (좌)', quantity: 1, unit: 'M', quantityFormula: 'H/1000', note: '높이 기준' },
        { childItemCode: 'SF-SCR-F03', childItemName: '가이드레일 (우)', quantity: 1, unit: 'M', quantityFormula: 'H/1000', note: '높이 기준' },
        { childItemCode: 'SF-SCR-F04', childItemName: '상부 케이스', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-F05', childItemName: '하부 바텀바', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-M03', childItemName: '모터 (2.2KW)', quantity: 1, unit: 'EA', quantityFormula: '', note: '대형용' },
        { childItemCode: 'SF-SCR-C02', childItemName: '제어반 (고급)', quantity: 1, unit: 'EA', quantityFormula: '', note: '고급형' },
        { childItemCode: 'SF-SCR-S01', childItemName: '감지기 세트', quantity: 1, unit: 'SET', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-W01', childItemName: '권취축', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-SCR-B01', childItemName: '브라켓 세트', quantity: 3, unit: 'SET', quantityFormula: '', note: '대형용 3세트' },
        { childItemCode: 'SF-SCR-E01', childItemName: '엣지윙 (좌)', quantity: 1, unit: 'M', quantityFormula: 'H/1000', note: '높이 기준' },
        { childItemCode: 'SF-SCR-E02', childItemName: '엣지윙 (우)', quantity: 1, unit: 'M', quantityFormula: 'H/1000', note: '높이 기준' },
        { childItemCode: 'SM-B002', childItemName: '볼트 M10x40', quantity: 40, unit: 'EA', quantityFormula: '', note: '조립용' },
      ];
      
      // ===== 8. BOM 구조 추가 - 철재 제품 =====
      // FG-STL-001 (소형 철재문)
      newItems[5].bom = [
        { childItemCode: 'SF-STL-D01', childItemName: '철재 도어', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-STL-F01', childItemName: '철재 프레임', quantity: 1, unit: 'M', quantityFormula: '(W+H)*2/1000', note: '둘레 기준' },
        { childItemCode: 'SF-STL-P01', childItemName: '철재 패널', quantity: 1, unit: 'M2', quantityFormula: 'W*H/1000000', note: '면적 기준' },
        { childItemCode: 'SF-STL-H01', childItemName: '경첩 세트', quantity: 1, unit: 'SET', quantityFormula: '', note: '' },
        { childItemCode: 'SF-STL-L01', childItemName: '도어락', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-STL-C01', childItemName: '도어클로저', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-STL-S01', childItemName: '실링재', quantity: 1, unit: 'M', quantityFormula: '(W+H)*2/1000', note: '둘레 기준' },
        { childItemCode: 'SF-STL-T01', childItemName: '문턱', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-STL-B01', childItemName: '볼트/너트 세트', quantity: 2, unit: 'SET', quantityFormula: '', note: '' },
        { childItemCode: 'SM-A001', childItemName: '앵커볼트 M10', quantity: 8, unit: 'EA', quantityFormula: '', note: '고정용' },
      ];
      
      // FG-STL-002 (중형 철재문)
      newItems[6].bom = [
        { childItemCode: 'SF-STL-D01', childItemName: '철재 도어', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-STL-F01', childItemName: '철재 프레임', quantity: 1, unit: 'M', quantityFormula: '(W+H)*2/1000', note: '둘레 기준' },
        { childItemCode: 'SF-STL-P01', childItemName: '철재 패널', quantity: 1, unit: 'M2', quantityFormula: 'W*H/1000000', note: '면적 기준' },
        { childItemCode: 'SF-STL-H01', childItemName: '경첩 세트', quantity: 2, unit: 'SET', quantityFormula: '', note: '중형용 2세트' },
        { childItemCode: 'SF-STL-L02', childItemName: '도어락 (전자식)', quantity: 1, unit: 'EA', quantityFormula: '', note: '전자식' },
        { childItemCode: 'SF-STL-C01', childItemName: '도어클로저', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-STL-S01', childItemName: '실링재', quantity: 1, unit: 'M', quantityFormula: '(W+H)*2/1000', note: '둘레 기준' },
        { childItemCode: 'SF-STL-G01', childItemName: '유리 (방화)', quantity: 1, unit: 'M2', quantityFormula: '', note: '창 부분' },
        { childItemCode: 'SF-STL-T01', childItemName: '문턱', quantity: 1, unit: 'EA', quantityFormula: '', note: '' },
        { childItemCode: 'SF-STL-B01', childItemName: '볼트/너트 세트', quantity: 3, unit: 'SET', quantityFormula: '', note: '' },
        { childItemCode: 'SF-STL-P02', childItemName: '파우더 도장', quantity: 1, unit: 'M2', quantityFormula: 'W*H/1000000', note: '표면처리' },
        { childItemCode: 'SM-A002', childItemName: '앵커볼트 M12', quantity: 10, unit: 'EA', quantityFormula: '', note: '고정용' },
      ];
      
      // 모든 품목 추가
      setItemMasters(prev => [...prev, ...newItems]);
      
      // ===== 9. 단가 데이터 생성 =====
      const newPricingData: PricingData[] = [];
      const today = new Date().toISOString().split('T')[0];
      
      newItems.forEach((item) => {
        newPricingData.push({
          id: `PRICE-${item.id}`,
          itemId: item.id,
          itemCode: item.itemCode,
          itemName: item.itemName,
          itemType: item.itemType,
          specification: item.specification,
          unit: item.unit,
          effectiveDate: today,
          purchasePrice: item.purchasePrice || 0,
          processingCost: 0, // 가공비는 0으로 초기화
          loss: 0, // LOSS는 0으로 초기화
          roundingRule: 'round',
          roundingUnit: 1,
          marginRate: item.itemType === 'FG' ? 30 : 20, // 완제품 30%, 나머지 20%
          salesPrice: item.salesPrice || 0,
          supplier: item.itemType === 'FG' ? '자사 제조' : '협력업체',
          note: `${item.itemName} 샘플 단가`,
          currentRevision: 0,
          isFinal: false,
          status: 'active',
          createdAt: today,
          createdBy: '시스템'
        });
      });
      
      // 단가 데이터 추가
      setPricing(prev => [...prev, ...newPricingData]);
      
      toast.success(`샘플 데이터가 생성되었습니다!`, {
        description: `완제품 10개(판매단가 포함), 부품 30개, 부자재 20개, 원자재 15개 총 75개 품목 + 단가 데이터가 추가되었습니다.`
      });
      
      console.log('✅ 샘플 데이터 생성 완료:', newItems.length, '개 품목');
      console.log('✅ 단가 데이터 생성 완료:', newPricingData.length, '개 단가');
      console.log('✅ 완제품 판매단가 설정됨 - 즉시 견적 산출 가능');
    }
  };

  return <DataContext.Provider value={value}>{children}</DataContext.Provider>;
}

// ===== Custom Hook =====
export function useData() {
  const context = useContext(DataContext);
  if (context === undefined) {
    throw new Error('useData must be used within a DataProvider');
  }
  return context;
}
