'use client';

import { createContext, useContext, useState, useEffect, ReactNode } from 'react';

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

// 출하 계획 (분할 출고)
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 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; // 이전 버전의 전체 데이터
}

// 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; // 최종 확정자
  
  // 상세 정보 (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[];
}

// 생산 관련
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 RangeRule {
  id: string;
  minValue: number; // 최소값 (초과)
  maxValue: number; // 최대값 (이하)
  result: string | number; // 결과값 (표시용)
  itemCode?: string; // 연결된 품목 코드
  itemName?: string; // 연결된 품목명
  quantity?: number; // 수량
  description?: string;
}

// 수식 규칙 수정 이력
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 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; // 확정자
  
  createdAt: string;
  createdBy?: string;
  updatedAt: string;
  updatedBy?: 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; // 가공비
  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; // 이전 버전의 전체 데이터
}

// 품목 기준정보 관리 (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;
}

// 항목 속성
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일 경우)
  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;
}

// ===== 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;
  
  // 규격 마스터 데이터 (원자재/부자재)
  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;
  
  // 단가 관리
  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;
  
  // 품목기준관리 - 마스터 항목
  itemMasterFields: ItemMasterField[];
  addItemMasterField: (field: ItemMasterField) => void;
  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;
  
  // 품목기준관리 계층구조
  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;
}

// ===== 초기 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: '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: '절단 및 절곡 가공'
      }
    ]
  },
  {
    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'
  }
];

// 견적산출용 샘플 제품 단가 데이터
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: '시스템'
  }
];

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[]>(() => {
    if (typeof window === 'undefined') return initialSalesOrders;
    const saved = localStorage.getItem('mes-salesOrders');
    return saved ? JSON.parse(saved) : initialSalesOrders;
  });

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

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

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

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

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

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

  const [attendances, setAttendances] = useState<Attendance[]>(() => {
    if (typeof window === 'undefined') return initialAttendances;
    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 = '3.1-reset'; // 데이터 초기화 (부품 538개 제거)
    
    // 버전이 3.1-reset가 아니면 초기화
    if (version !== currentVersion) {
      localStorage.setItem('mes-itemMasters-version', currentVersion);
      localStorage.removeItem('mes-itemMasters'); // 기존 데이터 제거
      return []; // 빈 배열로 시작
    }
    
    if (saved) {
      const parsed = JSON.parse(saved);
      // 마이그레이션: productCategory가 없는 FG 품목에 기본값 설정
      const migrated = parsed.map((item: ItemMaster) => {
        if (item.itemType === 'FG' && !item.productCategory) {
          return { ...item, productCategory: 'STEEL' as const };
        }
        return item;
      });
      return migrated;
    }
    return [];
  });

  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.3'; // 제작사이즈/면적/중량 기준 카테고리 분리
    
    // 버전이 다르면 초기 데이터로 재설정
    if (version !== currentVersion) {
      localStorage.setItem('mes-formulaRules-version', currentVersion);
      return initialFormulaRules;
    }
    
    return saved ? JSON.parse(saved) : initialFormulaRules;
  });

  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 [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 [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: 'unit',
          property: {
            inputType: 'dropdown',
            required: true,
            row: 1,
            col: 1,
            options: ['EA', 'SET', 'KG', 'M', 'BOX']
          },
          category: '공통',
          description: '품목의 단위',
          isActive: true,
          createdAt: '2025-01-01'
        },
        {
          id: 'MASTER-004',
          name: '재질',
          fieldKey: 'material',
          property: {
            inputType: 'dropdown',
            required: false,
            row: 1,
            col: 1,
            options: ['EGI 1.2T', 'SUS 1.2T', 'AL 1.5T']
          },
          category: '부품',
          description: '부품의 재질',
          isActive: true,
          createdAt: '2025-01-01'
        },
        {
          id: 'MASTER-005',
          name: '표면처리',
          fieldKey: 'surfaceTreatment',
          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(() => {
    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-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]);

  // 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) => setQuotes(prev => [...prev, quote]),
    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,
    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,
    addFormulaRule: (rule) => setFormulaRules(prev => [...prev, rule]),
    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)),

    // 단가 관리
    pricing,
    addPricing: (newPricing) => setPricing(prev => [...prev, newPricing]),
    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)),

    // 품목 기준정보 관리
    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)),
    
    // 품목기준관리 - 섹션 템플릿
    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)),
    
    // 품목기준관리 계층구조
    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
      )
    ),

    // 사용자 관리
    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);
    }
  };

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