import React, { useState, useEffect } from 'react';
import {
  Search, Plus, FileText, Package, Truck, Factory, Users, DollarSign,
  ChevronDown, ChevronRight, ChevronLeft, ChevronsLeft, ChevronsRight, ChevronUp, MoreHorizontal, Edit, Edit2, Edit3, Trash2, Eye, Printer,
  CheckCircle, Clock, AlertCircle, AlertTriangle, X, Calendar, Building, Phone, MapPin,
  ArrowLeft, ArrowUpCircle, ArrowDownCircle, Copy, Send, Download, Check, XCircle, Settings, BarChart3,
  ClipboardList, Box, Warehouse, ShieldCheck, Clipboard, CreditCard, GitBranch,
  Play, Pause, PlayCircle, Bell, User, ShoppingCart, Zap, Layers, Home, Menu, Sun, Calculator,
  GripVertical, HelpCircle, Save, TrendingUp, TrendingDown, Database, RefreshCw,
  Key, Hash, Mail, MousePointer, MoreVertical, RotateCcw, Activity, Upload, FileCode, Zap as ZapIcon,
  Award, Shield, BookOpen, MessageCircle, List, ArrowRight, Link, Eraser
} from 'lucide-react';

// Master Config imports
import { masterConfigs } from './configs';
import documentTemplateConfig from './configs/documentTemplateConfig';
import DocumentTemplateManager from './components/DocumentTemplateManager';
import InspectionTemplateManager, { TemplateList, TemplateRegister, TemplateDetail, TemplateEdit } from './components/InspectionTemplateManager';
import InspectionManagement, { InspectionList, InspectionRegister, InspectionDetail, InspectionEdit } from './components/InspectionManagement';
import featureDefinitions, { getFeatureDefinition, generateDefaultBadges, screenKeyMapping, getAllScreenIds } from './configs/featureDefinitions';
import { getScreenFeatureTemplate } from './configs/screenFeatureTemplates';
import { screenActionDefinitions, getScreenActions, convertActionsToBadges, ACTION_TYPES, getBadgeColorByActionType } from './configs/screenActionDefinitions';
import {
  itemCodeRules,
  subMaterialCodeMapping,
  rawMaterialCodeMapping,
  purchasedPartCodeMapping,
  productTypeAbbreviations,
  assemblyPartAbbreviations,
  bendingPartAbbreviations,
  generateItemCode,
  findItemCodeRule,
  getAllCodeRules,
  lotProductCodes,
  lotTypeCodes,
  lotSizeCodes,
  lotDateCodeRules,
  generateBendingItemCode,
  generateLotNo,
} from './configs/codeRuleConfig';
import {
  generateE2ETestData,
  generateTestDataSummary,
  validateE2EDataIntegrity,
  productProcessMapping,
  bomItemProcessMapping,
} from './configs/e2eTestDataConfig';
import processMasterConfigModule from './configs/processMasterConfig';
import {
  loadNumberRules,
  saveNumberRules,
  generateNumber,
  targetTemplates as numberTargetTemplates,
  dateFormats as numberDateFormats,
  resetCycleOptions,
} from './configs/numberRuleConfig';

// Component imports
import ProcessFlowChart from './components/ProcessFlowChart';
import BusinessFlowChart from './components/BusinessFlowChart';
import UserFlowNavigator from './components/UserFlowNavigator';
import UserFlowPanel from './components/UserFlowPanel';
import UserFlowChartViewer from './components/UserFlowChartViewer';
import DetailedFlowDiagram from './components/DetailedFlowDiagram';
import PriceListSimple from './components/PriceListSimple';
import PolicyGuide from './components/PolicyGuide';
import { QuoteSheetDialog, CalculationSheetDialog, PurchaseOrderDialog, DeliveryConfirmDialog, InboundSlipDialog } from './components/QuoteDocumentDialogs';
import QuoteDetailNew from './components/QuoteDetailNew';
import CommonUXGuide from './components/CommonUXGuide';
import DetailedProcessFlowChart from './components/DetailedProcessFlowChart';
import FeatureDocPanel from './components/FeatureDocPanel';
import FeatureDocBadgeOverlay from './components/FeatureBadgeOverlay';
import { getFeaturesByCurrentScreen } from './configs/screenFeatureDefinitions';
import { getScreenFeatureDocument, screenFeatureDocuments } from './configs/screenFeatureDocuments';
import CompleteIntegrationTestTab from './components/CompleteIntegrationTestTab';
import ProcessIntegrationTestTab from './components/ProcessIntegrationTestTab';
import ComprehensiveFlowPanel from './components/ComprehensiveFlowPanel';
import AllMenuFeatureDocPanel from './components/AllMenuFeatureDocPanel';
import AllFeatureBadgesViewer from './components/AllFeatureBadgesViewer';

// E2E 테스트 유틸리티
import { processClassificationRules, classifyItemToProcess, e2eDebugLog, runE2EScenario } from './e2eTestUtils';

// 기능정의서 로컬 파일 저장 유틸리티
import {
  loadFeatureBadges,
  saveFeatureBadges,
  filterAdminBadges,
  createBackup,
  importFromFile,
  extractBadgesByFilter,
  generateBadgeStatistics
} from './utils/featureBadgeStorage';

// MES 통합 유틸리티 (채번관리, BOM 자동계산, 공정관리 연동)
import {
  generateDocumentNumber,
  previewDocumentNumber,
  getNumberingRules,
  calculateProductionSize,
  calculateAreaWeight,
  lookupMotorCapacity,
  calculateBOM,
  processSteps,
  processAssignees,
  initializeStepStatus,
  createWorkOrderFromOrder,
  analyzeRequiredProcesses,
  createAllWorkOrdersFromOrder,
  createInspectionFromWorkOrder,
  createShipmentFromInspection,
  simulateFullWorkflow,
} from './utils/mesIntegrationUtils';

// MES 전체 시스템 통합 테스트 (5건 실데이터)
import {
  testCustomers,
  testSites,
  testProducts,
  testParts,
  testRawMaterials,
  testConsumables,
  getAllMasterData,
  runFullProcessTest,
  runAllIntegrationTests,
} from './utils/mesFullIntegrationTest';

// MES 완전 통합 시스템 (10건 실데이터 + 채번/공통코드 완전 분리)
import {
  generateDocNo,
  generateIncomingLotNo,
  generateProductionLotNo,
  generateItemCodeAuto,
  createMaterialReceipt,
  createMaterialIssue,
  calculateFullBOM,
  processWorkflows,
  getWorkLogTemplate,
  createWorkLogData,
  getInspectionTemplate,
  createInspectionData,
  runCompleteProcess,
  runAllTests as runCompleteTests,
  masterData as completeMasterData,
} from './utils/mesCompleteIntegration';

/*
 * ============================================================
 * SAM MES 시스템 - 번호 및 LOT 체계
 * ============================================================
 * 
 * 📌 용어 정의
 * ----------------------------------------------------------------
 * "번호(Number)" = 문서/거래 식별자 (추상적)
 * "LOT"          = 실물/물리적 묶음 단위
 * 
 * 예시:
 *   - 견적 = 문서 → "견적번호"
 *   - 수주 = 거래 → "수주번호"  
 *   - 생산 = 실물 → "생산 LOT"
 *   - 자재 = 실물 → "입고 LOT"
 * 
 * ============================================================
 * 📋 문서/거래 번호 (Number) - 추상적 식별자
 * ============================================================
 * 
 * 견적번호 (quotationNumber)
 * ----------------------------------------------------------------
 * 형식: KD-PR-YYMMDD-순번
 * 예시: KD-PR-250717-02
 * 
 * ⭐ 수주번호 = 로트번호 (salesOrderNumber) - 모든 추적의 기준!
 * ----------------------------------------------------------------
 * 형식: KD-SO-YYMMDD-순번
 * 예시: KD-SO-250805-03
 * 추가분: KD-SO-250805-03-A, -B, -C...
 * 용도: 생산/출하/정산 모두 수주번호로 연결
 * UI표시: "로트번호" (실무에서 사용하는 용어)
 * 
 * 분할번호 (splitNumber)
 * ----------------------------------------------------------------
 * 형식: 수주번호-분할순번
 * 예시: KD-SO-250805-03-01
 * 용도: 출하 단위, 납품 단위
 * 참고: 같은 수주건이라도 출고일이 다를 수 있음 → 분할로 관리
 * 
 * 출하번호
 * ----------------------------------------------------------------
 * 없음 - 분할번호로 식별
 * 
 * ============================================================
 * 📦 LOT (실물/물리적 묶음)
 * ============================================================
 * 
 * 입고 LOT (incomingLot)
 * ----------------------------------------------------------------
 * 형식: YYMMDD-순번
 * 예시: 240927-06
 * 속성: 공급업체 LOT 포함 (예: 2402944)
 * 용도: 모터, PART, PO부자재 등 입고 자재 묶음
 * 참고: 입고검사 LOT와 동일한 체계
 * 
 * 생산 LOT (productionLot)
 * ----------------------------------------------------------------
 * 형식: KD-PL-YYMMDD-순번
 * 예시: KD-PL-250810-01
 * 용도: 분할번호와 연결되어 생산 추적
 * 
 * 재고생산 LOT (stockProductionLot)
 * ----------------------------------------------------------------
 * 형식: 제품코드
 * 예시: TS4B19-40
 * 용도: 재고 제품 식별
 * 
 * 완제품 LOT (finishedProductLot)
 * ----------------------------------------------------------------
 * 형식: KD-공장코드-YYMMDD-순번-분할순번
 * 예시: KD-TS-250717-02-01
 * 발급시점: 제품검사 직전에 부여
 * 참고: 출하 전까지는 층/부호로 관리 (예: FSS-01, FST-01)
 *       → 발주처 도면상 위치 이름, 제품(셔터)에서만 의미 있음
 * 
 * 부품 LOT (partsLot)
 * ----------------------------------------------------------------
 * 완제품 LOT와 동일
 * 
 * 설치 LOT (installationLot)
 * ----------------------------------------------------------------
 * 제품검사 LOT와 동일
 * 
 * ============================================================
 * 🔍 검사 LOT (inspectionLot)
 * ============================================================
 * 
 * 입고검사 LOT (incomingInspectionLot)
 * ----------------------------------------------------------------
 * 형식: YYMMDD-순번
 * 예시: 250715-02
 * 참고: 입고 LOT와 동일한 체계
 * 
 * 중간검사 LOT (processInspectionLot)
 * ----------------------------------------------------------------
 * 형식: KD-공정코드-YYMMDD-순번-(공정단계)
 * 예시: KD-SC-250209-01-(3)  ← 스크린 공정 3단계
 *       KD-SL-250220-01-(2)  ← 슬랫 공정 2단계
 * 용도: 공정별 중간 품질 검사
 * 
 * 제품검사 LOT (productInspectionLot)
 * ----------------------------------------------------------------
 * 형식: KD-SA-YYMMDD-순번
 * 예시: KD-SA-250604-01
 * 특징: 같은 현장의 모든 수주 내용을 한꺼번에 검사
 *       → 현장 단위 그룹 검사
 * 
 * ============================================================
 * 🏭 공장/공정 코드
 * ============================================================
 * TS : 메인 공장 (스크린 등)
 * SC : 스크린 공정
 * SL : 슬랫 공정
 * BD : 절곡 공정
 * SA : 제품검사
 * 
 * ============================================================
 * 🔗 추적 구조
 * ============================================================
 * 
 * [문서 흐름]
 * 견적번호 → 수주번호 → 분할번호 → 출하 (분할번호로 식별)
 *                ↓
 *            거래명세서/세금계산서
 * 
 * [실물 흐름]
 * 입고 LOT → 생산 LOT → 완제품 LOT → 설치 LOT
 *    ↓           ↓           ↓
 * 입고검사   중간검사    제품검사
 *   LOT        LOT        LOT
 * 
 * [연결 관계]
 * 수주번호 ─┬─ 분할번호 ─── 생산 LOT ─── 완제품 LOT
 *           │                              ↓
 *           └───────────────────────── 제품검사 LOT
 *                                    (현장 단위 그룹)
 * 
 * ============================================================
 * 📝 필드명 규칙 (코드용)
 * ============================================================
 * quotationNumber    : 견적번호     (예: KD-PR-250717-02)
 * salesOrderNumber   : 수주번호     (예: KD-SO-250805-03)
 * splitNumber        : 분할번호     (예: KD-SO-250805-03-01)
 * productionLot      : 생산 LOT     (예: KD-PL-250810-01)
 * incomingLot        : 입고 LOT     (예: 240927-06)
 * finishedProductLot : 완제품 LOT   (예: KD-TS-250717-02-01)
 * inspectionLot      : 검사 LOT     (예: KD-SA-250604-01)
 * 
 * ============================================================
 */

/*
 * ============================================================
 * 회계 프로세스 규칙
 * ============================================================
 * 
 * 📊 거래처 신용등급 (3단계)
 * ============================================================
 * 
 * A등급 (우량) - 정상거래처
 * ----------------------------------------------------------------
 * 특징: 입금지연 거의 없음, 거래이력 안정적
 * 프로세스:
 *   ✅ 수주확정 → 생산지시 → 출고 자동 진행
 *   ✅ 세금계산서 자동 발행
 * 
 * B등급 (일반/관리) - 관리대상거래처
 * ----------------------------------------------------------------
 * 특징: 가끔 입금 지연 또는 할인 요청 발생
 * 프로세스:
 *   ✅ 수주확정 후 생산 가능
 *   🚫 입금 확인 후에만 출고 가능
 *   ✅ 할인 적용 후 세금계산서 발행 가능
 * 
 * C등급 (위험/승인필요) - 경리승인 거래처
 * ----------------------------------------------------------------
 * 특징: 입금약속 미이행, 신용불량 이력
 * 프로세스:
 *   ✅ 생산지시는 가능 (납기 준수 위해)
 *   🚫 입금 확인 후 출고 가능
 *   🚫 경리 승인 후 출고 가능
 *   🚫 입금 후 발행 또는 경리 승인 필요
 *
 * 등급별 프로세스 흐름
 * ----------------------------------------------------------------
 * 단계        | A (우량)    | B (관리)        | C (위험)
 * ------------|-------------|-----------------|------------------
 * 수주확정    | 자동 승인   | 자동 승인       | 자동 승인
 * 생산지시    | 자동        | 자동            | 자동 (납기 준수)
 * 출고        | 자동        | 입금 확인 후    | 입금+경리승인 후
 * 세금계산서  | 자동 발행   | 할인 적용 가능  | 입금 후/경리 승인 후
 * 
 * ============================================================
 * 💰 매출 프로세스
 * ============================================================
 * 
 * (1) 거래처관리
 * ----------------------------------------------------------------
 * - 기본정보: 거래처코드(사업자번호), 거래처명, 대표자명, 주소, 업태, 종목
 * - 판매정보: 발주담당자, 연락처, 매출 결제일
 * - 거래처그룹 설정 시 신용등급 관리
 * 
 * (2) 판매관리
 * ----------------------------------------------------------------
 * - 수주확정 → 생산지시 → 판매조회 리스트에 금액과 함께 표시
 * - 경리: 수주확정 금액으로 거래명세서/세금계산서 발행
 * - 할인요청 시 최종 금액 조정 후 경리 확정
 * - 신용불량 거래처: 수주확정 → 경리확인 → 생산지시
 * - 입금확인 필요 건: 입금확인 전까지 '출고보류'
 * 
 * 관리항목:
 * - 로트번호 / 현장명 / 출고일 / 거래명세서 발송여부 / 입금확인여부
 * - 로트번호 클릭 → 금액수정, 날짜변경, 거래명세표발송, 세금계산서발행
 * - 신용불량 해제 후 생산지시 설정 / 입금 후 출고 조건 생성
 * 
 * (3) 거래명세서 & 세금계산서 발행
 * ----------------------------------------------------------------
 * - 로트별 거래명세서 (수정 및 할인 적용 가능)
 * - 발행일자: 기본 수주일, 발주처 요청 시 수정 가능
 * - 거래처계정별 저장 (거래처번호 = 사업자번호)
 * - 부호별 사이즈(제작사이즈), 수량, 금액 표시
 * - 절삭/할인 자동 적용 기능
 * - 월별 결제 거래처: 월별 거래원장으로 송부
 * - 건별 입금 거래처: 거래명세서 + 세금계산서 동시 발행 (메일/문자/팩스)
 * - 발행여부 색깔 표시
 * - ⭐ 매출 인식 시점 = 세금계산서 발행 시점
 * 
 * (4) 원장발행 (경리 → 발주처)
 * ----------------------------------------------------------------
 * - 수주건별 또는 월간 거래원장 발행
 * - 외상매출처: 월말일 기준 거래처 이메일로 송부
 * - 내용: 현장명(로트번호)별 주문내역, 금액, 총금액
 * - 세금계산서: 총금액 발행 / 일부입금 시 미수금액으로 관리
 * - 말일 마감처리 후 잔액 차기월 이월
 * 
 * (5) 판매일괄회계반영
 * ----------------------------------------------------------------
 * - 기간 지정 조회 (예: 1일~말일)
 * - 월별 계산서 미발행분 매출건 조회
 * - 월별 계산서 발행 업체: 이 화면에서 바로 발행 가능
 * 
 * (6) 거래처별 채권
 * ----------------------------------------------------------------
 * - 거래처별 거래이력(원장) 확인
 * - 지정 기간 동안 채권, 수금, 잔액 확인
 * - 세금계산서 미발행 건: 빨간색 표시
 * 
 * ============================================================
 * 💸 매입 프로세스
 * ============================================================
 * 
 * (1) 구매관리 - 품의서
 * ----------------------------------------------------------------
 * 용도: 지출 전 결재용
 * 결재순서: 임직원 작성 → 경리 승인 → 대표 최종결재
 *          (10만원 미만은 경리가 최종결재)
 * 
 * 경리 승인 시 추가 입력:
 * - 부가세/공급가액, 매입계정, 출금계좌, 부가세유형, 결제집행일(필수)
 * - 매입원장 형태로 표시
 * 
 * 주요 내용:
 * - 자재구매, 공사비용 등 큰 금액 지출
 * - 지출관련 서류 첨부 증빙
 * - 최종결재 완료 → 지출예상내역서에 리스트업
 * 
 * ============================================================
 * 📤 지출 관리
 * ============================================================
 * 
 * (1) 지출결의서
 * ----------------------------------------------------------------
 * 용도: 선지출 후 결재 (주로 법인카드 사용 시)
 * 결재순서: 임직원 작성 → 경리 승인 → 대표 최종결재
 *          (10만원 미만은 결재 생략)
 * 
 * 입력내용: 지출내용, 카드종류, 지출일, 지출비용, 영수증 첨부
 * 카드명세금액(월별): 경리가 금전출납부에 수동 기입 (출금일 기준)
 * 
 * (2) 지출예상내역서
 * ----------------------------------------------------------------
 * - 지출결의서 + 품의서 결재승인완료 건 자동 리스트업
 * - 기본: 건별 표시
 * - 매입결제일 지정 거래처: 월별 총금액 합산 표시
 * - 세금계산서 발행여부 확인
 * - 경리가 전자결재 항목 지정 → 대표 최종승인 요청
 * - 대표 최종승인 → 경리 집행(지출)
 * - 품의서 결재 → 경리가 매입처코드 등 추가 입력 → 매입원장 저장
 * 
 * ============================================================
 * 📥 수입 관리
 * ============================================================
 * 
 * (1) 금전출납부
 * ----------------------------------------------------------------
 * 용도: 실제 수입/지출 완료 내역 관리
 * 
 * 자동 리스트업:
 * - 지출예상내역서 최종결재 완료 후 출금처리 건 (집행일 기준)
 * 
 * 수동 입력:
 * - 자동이체(지출)건
 * - 수입내역: 거래처수금, 예치금, 이자, 잡이익, 차입금 등
 * - 단일건/대량건 등록 기능, 첨부파일 기능
 * 
 * (2) 수금관리
 * ----------------------------------------------------------------
 * - 입금 시 원장등록
 * - 거래처별/월별: 수금액, 수금날짜, 거래기간, 거래량(건수/금액)
 * - 세금계산서 수령여부 체크
 * 
 * (3) 미수금관리
 * ----------------------------------------------------------------
 * - 거래처별 매출금액(월별/원장확인), 미수금액 확인
 * - 수금계획 등록/메모: 결제약속일, 결제금액, 미수사유메모
 * - 금전출납부에서 수금 등록 시 미수금액 반영 (잔고 변경)
 * 
 * 계산식:
 * 잔고(거래원장 잔액) - 당월매출 - 전월매출 = 미수금
 * (계산서 발행 후 결제일 넘기면 미수금)
 * 
 * (4) 어음관리
 * ----------------------------------------------------------------
 * - 금전출납부에 전자어음 등록
 * - 입력항목: 배서일자, 금액, 만기일자
 * - 현황리스트로 확인
 * - 거래처 어음 지급 시 미수금 내역에서 차감
 *   (계좌: 전자어음, 통장잔액에는 미반영)
 * 
 * ============================================================
 */

// ============ SAM 디자인 시스템 ============

// 색상 팔레트
const colors = {
  primary: '#2563EB',      // 메인 블루
  primaryLight: '#EFF6FF', // 연한 블루 배경
  success: '#10B981',      // 초록
  successLight: '#D1FAE5',
  warning: '#F59E0B',      // 노랑
  warningLight: '#FEF3C7',
  danger: '#EF4444',       // 빨강
  dangerLight: '#FEE2E2',
  purple: '#8B5CF6',
  purpleLight: '#EDE9FE',
  gray: '#6B7280',
  grayLight: '#F3F4F6',
};

// 상태 배지 색상 매핑
const statusColors = {
  // 견적 상태
  '최초작성': { bg: 'bg-gray-100', text: 'text-gray-700' },
  '수정중': { bg: 'bg-yellow-100', text: 'text-yellow-700' },
  '최종확정': { bg: 'bg-green-100', text: 'text-green-700' },
  '수주전환': { bg: 'bg-blue-100', text: 'text-blue-700' },
  // 수주 상태 (5개)
  '수주확정': { bg: 'bg-blue-100', text: 'text-blue-700' },
  '생산중': { bg: 'bg-indigo-100', text: 'text-indigo-700' },
  '생산완료': { bg: 'bg-cyan-100', text: 'text-cyan-700' },
  '출하완료': { bg: 'bg-green-100', text: 'text-green-700' },
  '취소': { bg: 'bg-red-100', text: 'text-red-700' },
  // 입금 상태 (별도 관리)
  '미입금': { bg: 'bg-red-100', text: 'text-red-700' },
  '입금완료': { bg: 'bg-green-100', text: 'text-green-700' },
  // 회계확인 상태
  '미확인': { bg: 'bg-gray-100', text: 'text-gray-700' },
  '입금확인': { bg: 'bg-yellow-100', text: 'text-yellow-700' },
  '세금계산서발행': { bg: 'bg-blue-100', text: 'text-blue-700' },
  '회계확인완료': { bg: 'bg-green-100', text: 'text-green-700' },
  // 생산(작업지시) 상태
  '작업대기': { bg: 'bg-gray-100', text: 'text-gray-700' },
  '작업중': { bg: 'bg-blue-100', text: 'text-blue-700' },
  '작업완료': { bg: 'bg-green-100', text: 'text-green-700' },
  '검사대기': { bg: 'bg-yellow-100', text: 'text-yellow-700' },
  '검사완료': { bg: 'bg-cyan-100', text: 'text-cyan-700' },
  '포장완료': { bg: 'bg-purple-100', text: 'text-purple-700' },
  '출고구역이동': { bg: 'bg-green-100', text: 'text-green-700' },
  // 출하 상태
  '출고지시': { bg: 'bg-gray-100', text: 'text-gray-700' },
  '출하준비': { bg: 'bg-blue-100', text: 'text-blue-700' },
  '상차완료': { bg: 'bg-yellow-100', text: 'text-yellow-700' },
  '배송중': { bg: 'bg-purple-100', text: 'text-purple-700' },
  '배송완료': { bg: 'bg-green-100', text: 'text-green-700' },
  '출하취소': { bg: 'bg-red-100', text: 'text-red-700' },
  // 우선순위
  '긴급': { bg: 'bg-red-100', text: 'text-red-700' },
  '높음': { bg: 'bg-orange-100', text: 'text-orange-700' },
  '일반': { bg: 'bg-gray-100', text: 'text-gray-700' },
  '낮음': { bg: 'bg-gray-50', text: 'text-gray-500' },
  // 품질검사 상태
  '검사신청': { bg: 'bg-yellow-100', text: 'text-yellow-700' },
  '검사예정': { bg: 'bg-blue-100', text: 'text-blue-700' },
  '검사중': { bg: 'bg-purple-100', text: 'text-purple-700' },
  '합격': { bg: 'bg-green-100', text: 'text-green-700' },
  '불합격': { bg: 'bg-red-100', text: 'text-red-700' },
  '결재대기': { bg: 'bg-yellow-100', text: 'text-yellow-700' },
  '결재완료': { bg: 'bg-green-100', text: 'text-green-700' },
  // 이슈 유형
  '불량품발생': { bg: 'bg-red-100', text: 'text-red-700' },
  '재고없음': { bg: 'bg-orange-100', text: 'text-orange-700' },
  '일정지연': { bg: 'bg-yellow-100', text: 'text-yellow-700' },
  // 수주 유형
  '최초': { bg: 'bg-blue-100', text: 'text-blue-700' },
  '추가': { bg: 'bg-yellow-100', text: 'text-yellow-700' },
  '직접': { bg: 'bg-gray-100', text: 'text-gray-600' },
};

// ============ LOT/번호 체계 정의 ============
/*
  [번호 체계 규칙 - 2025년 개정판]

  1. 견적번호: KD-PR-YYMMDD-순번
     예) KD-PR-250717-02

  2. 수주번호: KD-모델코드-YYMMDD-순번
     예) KD-TS-250717-02 (TS=스크린 모델약자 SA → 수주코드 TS)
     모델코드: TS(스크린/KSS), SL(슬랫), BD(절곡)

  3. 수주(발주)번호: KD-SO-YYMMDD-순번
     예) KD-SO-250805-03
     * 내부 발주용 번호 (외부 공급업체 발주 시)

  4. 생산 LOT: KD-PL-YYMMDD-순번
     예) KD-PL-250810-01

  5. 완제품/부품 LOT: 수주번호-분할순번
     예) KD-TS-250717-02-01 (제품검사 직전 발급)
     * 제품검사 시점에 발급
     * 설치 LOT와 동일

  6. 재고생산 LOT: 모델약자+규격코드
     예) TS4B19-40
     형식: {모델약자}{규격정보}

  7. 검사 LOT:
     - 입고검사: YYMMDD-순번 (예: 250715-02)
     - 중간검사: KD-WE-YYMMDD-순번-(공정단계) (예: KD-WE-251015-01-(3))
       WE: Work Execution (작업실행) 검사코드
     - 제품검사: KD-SA-YYMMDD-순번 (예: KD-SA-250604-01)
       SA: 모델명 KSS의 약자
     - 검사 LOT: KD-QC-YYMMDD-순번 (예: KD-QC-250815-01)
       QC: Quality Control

  8. 설치 LOT: 완제품 LOT와 동일
     예) KD-TS-250717-02-01

  9. 출하번호: 별도 체계 없음 (내부 관리용)
*/

// 공장/공정/모델 코드 매핑
const factoryCodes = {
  '스크린': 'TS',  // TS = 스크린 수주코드
  '슬랫': 'SL',
  '절곡': 'BD',
};

// 모델 약자 매핑 (KSS02 → SA)
const modelCodes = {
  'KSS': 'SA',      // 스크린 모델
  'KSS02': 'SA',
  'KSL': 'SL',      // 슬랫 모델
  'KBD': 'BD',      // 절곡 모델
};

// 중간검사용 공정코드 (WE: Work Execution)
const processInspectionCodes = {
  '스크린': 'WE',
  '슬랫': 'WE',
  '절곡': 'WE',
};

// 날짜를 YYMMDD 형식으로 변환
const formatDateCode = (date) => {
  const d = new Date(date);
  const yy = String(d.getFullYear()).slice(-2);
  const mm = String(d.getMonth() + 1).padStart(2, '0');
  const dd = String(d.getDate()).padStart(2, '0');
  return `${yy}${mm}${dd}`;
};

// ============ 번호 생성 함수들 (채번관리 규칙 연동) ============

// 1. 견적번호: 채번관리 규칙 적용
const generateQuoteNo = (date, seq) => {
  // 채번관리 규칙에서 생성 시도
  const generated = generateNumber('견적번호', null, [], date);
  if (generated) return generated;
  // 폴백: 기존 방식
  return `KD-PR-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
};

// 2. 수주번호: 채번관리 규칙 적용 (모델유형에 따라 스크린/슬랫/절곡 구분)
const generateOrderNo = (modelType, date, seq) => {
  // 채번관리 규칙에서 생성 시도
  const generated = generateNumber('수주번호', modelType, [], date);
  if (generated) return generated;
  // 폴백: 기존 방식
  const code = factoryCodes[modelType] || modelType || 'TS';
  return `KD-${code}-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
};

// 2-1. 발주번호: 채번관리 규칙 적용
const generatePurchaseOrderNo = (date, seq) => {
  const generated = generateNumber('발주번호', null, [], date);
  if (generated) return generated;
  return `KD-SO-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
};

// 3. 생산 LOT: 채번관리 규칙 적용
const generateProductionLot = (date, seq) => {
  const generated = generateNumber('생산LOT', null, [], date);
  if (generated) return generated;
  return `KD-PL-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
};

// 4. 완제품/부품 LOT: 수주번호-## (예: KD-TS-250717-02-01)
//    제품검사 직전에 발급
const generateProductLot = (orderNo, splitSeq = 1) =>
  `${orderNo}-${String(splitSeq).padStart(2, '0')}`;

// 4-1. 완제품 LOT (processType 기반, 레거시 호환용)
const generateProductLotLegacy = (processType, date, seq, splitSeq = 1) =>
  `KD-${factoryCodes[processType] || 'TS'}-${formatDateCode(date)}-${String(seq).padStart(2, '0')}-${String(splitSeq).padStart(2, '0')}`;

// 5. 재고생산 LOT: 모델약자+규격코드 (예: TS4B19-40)
const generateStockProductionLot = (modelAbbr, specCode) =>
  `${modelAbbr}${specCode}`;

// 6-1. 입고검사 LOT: 채번관리 규칙 적용
const generateIncomingInspectionLot = (date, seq) => {
  const generated = generateNumber('입고검사LOT', null, [], date);
  if (generated) return generated;
  return `${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
};

// 6-2. 중간검사 LOT: 채번관리 규칙 적용
const generateProcessInspectionLot = (date, seq, step) => {
  const generated = generateNumber('중간검사LOT', null, [], date);
  if (generated) return `${generated}-(${step})`;
  return `KD-WE-${formatDateCode(date)}-${String(seq).padStart(2, '0')}-(${step})`;
};

// 6-3. 제품검사 LOT: 채번관리 규칙 적용
const generateProductInspectionLot = (date, seq) => {
  const generated = generateNumber('제품검사LOT', null, [], date);
  if (generated) return generated;
  return `KD-SA-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
};

// 6-4. 검사 LOT (일반): 채번관리 규칙 적용
const generateQCLot = (date, seq) => {
  const generated = generateNumber('검사LOT', null, [], date);
  if (generated) return generated;
  return `KD-QC-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
};

// 7. 출하번호: 채번관리 규칙 적용
const generateShipmentNo = (date, seq) => {
  const generated = generateNumber('출하번호', null, [], date);
  if (generated) return generated;
  return `KD-SH-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
};

// 8. 작업지시번호: 채번관리 규칙 적용
const generateWorkOrderNo = (date, seq) => {
  const generated = generateNumber('작업지시번호', null, [], date);
  if (generated) return generated;
  return `KD-WO-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
};

// ============ 공통 컴포넌트 ============

// 상태 배지
// 대시보드 카드
const DashboardCard = ({ icon: Icon, title, value, subtitle, color = 'blue', onClick }) => {
  const iconColors = {
    blue: 'text-blue-500',
    green: 'text-green-500',
    yellow: 'text-yellow-500',
    purple: 'text-purple-500',
    red: 'text-red-500',
    orange: 'text-orange-500',
  };
  const iconBgColors = {
    blue: 'bg-blue-50',
    green: 'bg-green-50',
    yellow: 'bg-yellow-50',
    purple: 'bg-purple-50',
    red: 'bg-red-50',
    orange: 'bg-orange-50',
  };
  return (
    <div
      className={`bg-white rounded-xl p-5 border flex items-center justify-between ${onClick ? 'cursor-pointer hover:bg-gray-50 transition-colors' : ''}`}
      onClick={onClick}
    >
      <div>
        <p className="text-sm text-gray-500 mb-1">{title}</p>
        <p className="text-2xl font-bold text-gray-900">{value}</p>
        {subtitle && <p className="text-xs text-gray-400 mt-1">{subtitle}</p>}
      </div>
      {Icon && (
        <div className={`w-10 h-10 rounded-lg ${iconBgColors[color]} flex items-center justify-center`}>
          <Icon className={`w-5 h-5 ${iconColors[color]}`} />
        </div>
      )}
    </div>
  );
};

// 통계 카드 컴포넌트 (회계관리용)
const StatCard = ({ icon: Icon, label, value, color = 'blue' }) => {
  const colorClasses = {
    blue: 'bg-blue-50 text-blue-600',
    green: 'bg-green-50 text-green-600',
    red: 'bg-red-50 text-red-600',
    purple: 'bg-purple-50 text-purple-600',
    orange: 'bg-orange-50 text-orange-600',
    yellow: 'bg-yellow-50 text-yellow-600',
  };
  return (
    <div className={`${colorClasses[color]?.split(' ')[0] || 'bg-gray-50'} rounded-lg p-4`}>
      <div className="flex items-center gap-2 mb-2">
        <Icon className={`w-5 h-5 ${colorClasses[color]?.split(' ')[1] || 'text-gray-600'}`} />
        <span className="text-sm text-gray-600">{label}</span>
      </div>
      <p className="text-xl font-bold text-gray-900">{value}</p>
    </div>
  );
};

// ============================================================
// 목록 페이지 공통 UX 컴포넌트
// ============================================================

// 목록 페이지 공통 레이아웃 - UX 일관성 보장
const ListPageLayout = ({
  icon: Icon,
  title,
  stats = [], // [{ icon, label, value, color }]
  tabs = [], // [{ id, label, count }]
  activeTab,
  onTabChange,
  search,
  onSearchChange,
  searchPlaceholder = '검색...',
  dateRange, // { start, end }
  onDateChange,
  primaryAction, // { label, icon, onClick }
  secondaryActions = [], // [{ label, icon, onClick, variant }]
  children,
  emptyMessage = '데이터가 없습니다.',
  isEmpty = false
}) => {
  return (
    <div className="space-y-6">
      {/* 1. 페이지 헤더 - 타이틀/버튼 분리 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
          {Icon && <Icon className="w-6 h-6 text-blue-500" />}
          {title}
        </h1>
        <div className="flex items-center justify-end gap-2">
          {secondaryActions.map((action, idx) => (
            <button
              key={idx}
              onClick={action.onClick}
              className={`flex items-center gap-1.5 px-3 py-2 text-sm font-medium rounded-lg transition-colors ${action.variant === 'danger' ? 'bg-red-50 text-red-600 hover:bg-red-100' :
                  action.variant === 'success' ? 'bg-green-50 text-green-600 hover:bg-green-100' :
                    'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
            >
              {action.icon && <action.icon className="w-4 h-4" />}
              {action.label}
            </button>
          ))}
          {primaryAction && (
            <button
              onClick={primaryAction.onClick}
              className="flex items-center gap-1.5 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
            >
              {primaryAction.icon && <primaryAction.icon className="w-4 h-4" />}
              {primaryAction.label}
            </button>
          )}
        </div>
      </div>

      {/* 2. 통계 카드 (4열 그리드) */}
      {stats.length > 0 && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {stats.map((stat, idx) => (
            <StatCard key={idx} icon={stat.icon} label={stat.label} value={stat.value} color={stat.color} />
          ))}
        </div>
      )}

      {/* 3. 필터 영역 */}
      <div className="bg-white rounded-xl border border-gray-200 shadow-sm">
        <div className="p-4 border-b border-gray-100">
          <div className="flex flex-wrap items-center justify-between gap-4">
            {/* 탭 필터 (칩 스타일) */}
            {tabs.length > 0 && (
              <div className="flex flex-wrap gap-2">
                {tabs.map(tab => (
                  <button
                    key={tab.id}
                    onClick={() => onTabChange && onTabChange(tab.id)}
                    className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-full border transition-colors ${activeTab === tab.id
                        ? 'bg-gray-900 text-white border-gray-900'
                        : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                      }`}
                  >
                    {tab.label}
                    {tab.count !== undefined && (
                      <span className={`text-xs px-1.5 py-0.5 rounded-full ${activeTab === tab.id
                          ? 'bg-gray-700 text-white'
                          : 'bg-gray-100 text-gray-500'
                        }`}>
                        {tab.count}
                      </span>
                    )}
                  </button>
                ))}
              </div>
            )}

            {/* 검색 및 날짜 필터 */}
            <div className="flex items-center gap-3">
              {dateRange && (
                <div className="flex items-center gap-2">
                  <input
                    type="date"
                    value={dateRange.start}
                    onChange={(e) => onDateChange && onDateChange({ ...dateRange, start: e.target.value })}
                    className="px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                  <span className="text-gray-400">~</span>
                  <input
                    type="date"
                    value={dateRange.end}
                    onChange={(e) => onDateChange && onDateChange({ ...dateRange, end: e.target.value })}
                    className="px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              )}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  placeholder={searchPlaceholder}
                  value={search || ''}
                  onChange={(e) => onSearchChange && onSearchChange(e.target.value)}
                  className="pl-10 pr-4 py-2 border border-gray-200 rounded-lg text-sm w-64 focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
            </div>
          </div>
        </div>

        {/* 4. 테이블 컨텐츠 영역 */}
        <div className="p-4">
          {isEmpty ? (
            <div className="text-center py-12">
              <div className="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
                <Search className="w-8 h-8 text-gray-400" />
              </div>
              <p className="text-gray-500">{emptyMessage}</p>
            </div>
          ) : (
            children
          )}
        </div>
      </div>
    </div>
  );
};

// 테이블 공통 스타일 컴포넌트
const ListTable = ({ columns, data, onRowClick, emptyMessage = '데이터가 없습니다.' }) => {
  if (!data || data.length === 0) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500">{emptyMessage}</p>
      </div>
    );
  }

  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead className="bg-gray-50 border-y border-gray-200">
          <tr>
            {columns.map((col, idx) => (
              <th
                key={idx}
                className={`px-4 py-3 font-medium text-gray-600 ${col.align === 'right' ? 'text-right' :
                    col.align === 'center' ? 'text-center' : 'text-left'
                  }`}
                style={col.width ? { width: col.width } : {}}
              >
                {col.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-200">
          {data.map((row, rowIdx) => (
            <tr
              key={row.id || rowIdx}
              className={`hover:bg-gray-50 ${onRowClick ? 'cursor-pointer' : ''}`}
              onClick={() => onRowClick && onRowClick(row)}
            >
              {columns.map((col, colIdx) => (
                <td
                  key={colIdx}
                  className={`px-4 py-3 ${col.align === 'right' ? 'text-right' :
                      col.align === 'center' ? 'text-center' : 'text-left'
                    }`}
                >
                  {col.render ? col.render(row[col.key], row) : row[col.key]}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

// 페이지네이션 컴포넌트
const Pagination = ({ currentPage, totalPages, onPageChange, totalItems, pageSize }) => {
  const startItem = (currentPage - 1) * pageSize + 1;
  const endItem = Math.min(currentPage * pageSize, totalItems);

  return (
    <div className="flex items-center justify-between px-4 py-3 border-t border-gray-200">
      <div className="text-sm text-gray-500">
        전체 {totalItems}건 중 {startItem}-{endItem}건
      </div>
      <div className="flex items-center gap-1">
        <button
          onClick={() => onPageChange(currentPage - 1)}
          disabled={currentPage === 1}
          className="px-3 py-1 text-sm border border-gray-200 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          이전
        </button>
        {[...Array(Math.min(5, totalPages))].map((_, idx) => {
          const pageNum = idx + 1;
          return (
            <button
              key={pageNum}
              onClick={() => onPageChange(pageNum)}
              className={`px-3 py-1 text-sm rounded ${currentPage === pageNum
                  ? 'bg-blue-600 text-white'
                  : 'border border-gray-200 hover:bg-gray-50'
                }`}
            >
              {pageNum}
            </button>
          );
        })}
        <button
          onClick={() => onPageChange(currentPage + 1)}
          disabled={currentPage === totalPages}
          className="px-3 py-1 text-sm border border-gray-200 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          다음
        </button>
      </div>
    </div>
  );
};

// 상태 뱃지 컴포넌트 (공통)
const StatusBadge = ({ status, size = 'sm' }) => {
  const statusStyles = {
    // 긍정적 상태
    '완료': 'bg-green-100 text-green-700',
    '승인완료': 'bg-green-100 text-green-700',
    '수금완료': 'bg-green-100 text-green-700',
    '지급완료': 'bg-green-100 text-green-700',
    '발행완료': 'bg-green-100 text-green-700',
    '검수완료': 'bg-green-100 text-green-700',
    '활성': 'bg-green-100 text-green-700',
    '생산지시완료': 'bg-green-100 text-green-700',
    '출하완료': 'bg-green-100 text-green-700',
    // 진행중 상태
    '진행중': 'bg-blue-100 text-blue-700',
    '생산중': 'bg-blue-100 text-blue-700',
    '생산지시': 'bg-indigo-100 text-indigo-700',
    '검사중': 'bg-blue-100 text-blue-700',
    '배송중': 'bg-blue-100 text-blue-700',
    '수주확정': 'bg-blue-100 text-blue-700',
    // 대기 상태
    '대기': 'bg-yellow-100 text-yellow-700',
    '결재대기': 'bg-yellow-100 text-yellow-700',
    '승인대기': 'bg-yellow-100 text-yellow-700',
    '미수금': 'bg-yellow-100 text-yellow-700',
    '미발행': 'bg-gray-100 text-gray-600',
    '수주등록': 'bg-gray-100 text-gray-600',
    // 부정적 상태
    '반려': 'bg-red-100 text-red-700',
    '취소': 'bg-red-100 text-red-700',
    '지연': 'bg-red-100 text-red-700',
    '부적합': 'bg-red-100 text-red-700',
    // 기본 상태
    default: 'bg-gray-100 text-gray-600',
  };

  const sizeClasses = {
    xs: 'px-1.5 py-0.5 text-xs',
    sm: 'px-2 py-1 text-xs',
    md: 'px-2.5 py-1.5 text-sm',
  };

  return (
    <span className={`inline-flex items-center rounded-full font-medium ${statusStyles[status] || statusStyles.default} ${sizeClasses[size]}`}>
      {status}
    </span>
  );
};

// ============================================================
// 역할별 권한 시스템
// ============================================================
const ROLES = {
  CEO: { id: 'ceo', name: '대표이사', level: 10 },
  SALES: { id: 'sales', name: '판매팀', level: 5 },
  PRODUCTION: { id: 'production', name: '생산관리', level: 5 },
  QUALITY: { id: 'quality', name: '품질관리', level: 5 },
  ACCOUNTING: { id: 'accounting', name: '회계팀', level: 5 },
  PURCHASE: { id: 'purchase', name: '구매팀', level: 5 },
  WORKER: { id: 'worker', name: '생산담당자', level: 1 },
};

// 메뉴별 접근 권한 (✓=전체, △=조회만, -=불가)
const MENU_PERMISSIONS = {
  'dashboard': { ceo: '✓', sales: '✓', production: '✓', quality: '✓', accounting: '✓', purchase: '✓', worker: '✓' },
  'quote': { ceo: '✓', sales: '✓', production: '-', quality: '-', accounting: '△', purchase: '-', worker: '-' },
  'order': { ceo: '✓', sales: '✓', production: '△', quality: '-', accounting: '△', purchase: '-', worker: '-' },
  'shipment': { ceo: '✓', sales: '✓', production: '△', quality: '△', accounting: '-', purchase: '-', worker: '-' },
  'production-plan': { ceo: '✓', sales: '△', production: '✓', quality: '-', accounting: '-', purchase: '-', worker: '-' },
  'work-order': { ceo: '✓', sales: '-', production: '✓', quality: '-', accounting: '-', purchase: '-', worker: '△' },
  'work-log': { ceo: '✓', sales: '-', production: '✓', quality: '△', accounting: '-', purchase: '-', worker: '✓' },
  'inspection': { ceo: '✓', sales: '-', production: '△', quality: '✓', accounting: '-', purchase: '△', worker: '△' },
  'lot-tracking': { ceo: '✓', sales: '-', production: '△', quality: '✓', accounting: '-', purchase: '-', worker: '-' },
  'inventory': { ceo: '✓', sales: '△', production: '✓', quality: '△', accounting: '-', purchase: '✓', worker: '△' },
  'purchase-order': { ceo: '✓', sales: '-', production: '△', quality: '-', accounting: '△', purchase: '✓', worker: '-' },
  'sales-ledger': { ceo: '✓', sales: '△', production: '-', quality: '-', accounting: '✓', purchase: '-', worker: '-' },
  'collection': { ceo: '✓', sales: '△', production: '-', quality: '-', accounting: '✓', purchase: '-', worker: '-' },
  'purchase-ledger': { ceo: '✓', sales: '-', production: '-', quality: '-', accounting: '✓', purchase: '△', worker: '-' },
  'payment': { ceo: '✓', sales: '-', production: '-', quality: '-', accounting: '✓', purchase: '-', worker: '-' },
  'item-master': { ceo: '✓', sales: '△', production: '✓', quality: '△', accounting: '-', purchase: '△', worker: '-' },
  'bom': { ceo: '✓', sales: '-', production: '✓', quality: '-', accounting: '-', purchase: '-', worker: '-' },
  'price': { ceo: '✓', sales: '✓', production: '-', quality: '-', accounting: '✓', purchase: '✓', worker: '-' },
  'process': { ceo: '✓', sales: '-', production: '✓', quality: '△', accounting: '-', purchase: '-', worker: '-' },
  'user-management': { ceo: '✓', sales: '-', production: '-', quality: '-', accounting: '-', purchase: '-', worker: '-' },
  'system-settings': { ceo: '✓', sales: '-', production: '-', quality: '-', accounting: '-', purchase: '-', worker: '-' },
};

// ============================================================
// 대표이사 대시보드 - CEO Dashboard
// ============================================================
const CEODashboard = ({ userRole = 'ceo', onNavigate }) => {
  const [showWidgetManager, setShowWidgetManager] = useState(false);

  // 위젯 설정 상태
  const [widgetConfig, setWidgetConfig] = useState([
    { id: 'daily-metrics', name: '당일 핵심 지표', desc: '당일 출하매출, 이익률, 미수금', width: 'full', enabled: true, order: 0 },
    { id: 'process-pipeline', name: '모든 프로세스 현황', desc: '견적-수주-생산-검사-출고-완료', width: 'full', enabled: true, order: 1 },
    { id: 'sales-achievement', name: '일/월/연 매출 달성', desc: '일별/월별/연간 매출 목표 대비', width: 'full', enabled: true, order: 2 },
    { id: 'sales-trend', name: '매출 추이 차트', desc: '월별 매출/매입 트렌드 차트', width: 'half', enabled: true, order: 3 },
    { id: 'receivable-trend', name: '미수금 추이', desc: '월별 미수금 변동 추이', width: 'half', enabled: true, order: 4 },
    { id: 'top-customers', name: 'TOP 5 고객', desc: '주요 고객별 매출 현황', width: 'half', enabled: true, order: 5 },
    { id: 'production-status', name: '생산 현황', desc: '실시간 생산 진행 상태', width: 'half', enabled: true, order: 6 },
    { id: 'quality-status', name: '품질 현황', desc: '불량률 및 품질 지표', width: 'half', enabled: true, order: 7 },
    { id: 'receivable-top5', name: '미수금 관리', desc: '거래처별 미수금 TOP 5', width: 'half', enabled: true, order: 8 },
    { id: 'cashflow', name: '현금 흐름', desc: '현금 잔고 변동 및 주요 거래', width: 'half', enabled: true, order: 9 },
    { id: 'purchase-status', name: '매입 현황', desc: '월별 매입 및 주요 거래처', width: 'half', enabled: true, order: 10 },
    { id: 'inventory-status', name: '재고 현황', desc: '재고 수량 및 부족 알림', width: 'half', enabled: true, order: 11 },
    { id: 'hr-status', name: '인사 현황', desc: '총 인원, 출근율, 휴가 현황', width: 'half', enabled: true, order: 12 },
    { id: 'calendar', name: '일정 캘린더', desc: '주요 일정 및 회의', width: 'half', enabled: true, order: 13 },
  ]);

  // 샘플 데이터
  const dashboardData = {
    dailySales: 4580,
    dailySalesChange: 12.5,
    dailySalesMonthChange: 8.3,
    profitMargin: 28.5,
    operatingMargin: 15.2,
    totalReceivable: 125000,
    overdueReceivable: 18000,
    overdueRate: 14.4,
    dailyProfit: 850,

    // 프로세스 현황
    process: {
      quote: {
        count: 8, items: [
          { name: 'A전자', desc: 'LCD 패널', amount: 45, status: '검토중' },
          { name: 'B산업', desc: '금속 부품', amount: 32, status: '대기' },
        ]
      },
      order: {
        count: 12, items: [
          { name: 'C건설', desc: '철골 구조재', amount: 125, status: '승인' },
          { name: 'D제약', desc: '포장재', amount: 28, status: '계약중' },
        ]
      },
      production: {
        count: 15, items: [
          { name: 'E자동차', desc: '브레이크 패드', progress: 65, status: '진행중' },
          { name: 'F전기', desc: '배전반', progress: 40, status: '진행중' },
        ]
      },
      inspection: {
        count: 6, items: [
          { name: 'G식품', desc: '스테인레스 용기', progress: 80, status: '검사중' },
          { name: 'H화학', desc: '반응기', progress: 0, status: '대기' },
        ]
      },
      shipping: {
        count: 9, items: [
          { name: 'I물류', desc: '파레트', amount: 18, status: '포장중' },
          { name: 'J유통', desc: '진열대', amount: 0, status: '준비완료' },
        ]
      },
      completed: {
        count: 23, items: [
          { name: 'K건설', desc: '건자재', amount: 85, status: '납품완료' },
          { name: 'L전자', desc: '부품 세트', amount: 42, status: '납품완료' },
        ]
      },
    },

    // 매출 달성
    salesAchievement: {
      daily: { target: 50, actual: 46, rate: 91.6, collected: 38, receivable: 8 },
      monthly: { target: 1500, actual: 1280, rate: 85.3, collected: 950, receivable: 330 },
      yearly: { target: 18000, actual: 13200, rate: 69.4, collected: 900, receivable: 300 },
    },

    // 월별 매출 추이
    monthlySales: [
      { month: '01월', amount: 1200 }, { month: '02월', amount: 1350 },
      { month: '03월', amount: 1100 }, { month: '04월', amount: 1450 },
      { month: '05월', amount: 1300 }, { month: '06월', amount: 1500 },
      { month: '07월', amount: 1400 }, { month: '08월', amount: 1250 },
      { month: '09월', amount: 1600 }, { month: '10월', amount: 1380 },
      { month: '11월', amount: 1420 }, { month: '12월', amount: 1280 },
    ],

    // 월별 미수금 추이
    monthlyReceivable: [
      { month: '01월', amount: 450 }, { month: '02월', amount: 380 },
      { month: '03월', amount: 420 }, { month: '04월', amount: 390 },
      { month: '05월', amount: 460 }, { month: '06월', amount: 440 },
      { month: '07월', amount: 410 }, { month: '08월', amount: 380 },
      { month: '09월', amount: 420 }, { month: '10월', amount: 450 },
      { month: '11월', amount: 430 }, { month: '12월', amount: 417 },
    ],

    // TOP 5 고객
    topCustomers: [
      { rank: 1, name: '삼성전자', amount: 1200, change: 15.2 },
      { rank: 2, name: 'LG전자', amount: 850, change: -3.1 },
      { rank: 3, name: '현대자동차', amount: 720, change: 22.4 },
      { rank: 4, name: 'SK하이닉스', amount: 680, change: 8.7 },
      { rank: 5, name: '네이버', amount: 590, change: 12.3 },
    ],

    // 생산 현황
    productionStatus: {
      total: 30,
      completed: 4,
      rate: 13,
      utilization: 50,
      processes: [
        { name: '절단', status: '정상', completed: 1, total: 9, rate: 96 },
        { name: '벤딩', status: '정상', completed: 1, total: 9, rate: 93 },
        { name: '용접', status: '지연', completed: 0, total: 6, rate: 80 },
        { name: '도장', status: '지연', completed: 0, total: 4, rate: 70 },
      ],
    },

    // 품질 현황
    qualityStatus: {
      defectRate: 1.9,
      target: 3.0,
      inspected: 104,
      passed: 102,
      defects: 2,
      byProcess: [
        { name: '입고검사', rate: 2 },
        { name: '중간검사', rate: 0 },
        { name: '제품검사', rate: 0 },
      ],
    },

    // 미수금 TOP 5
    receivableTop5: [
      { name: 'A전자', amount: 8500, days: 45, status: '위험' },
      { name: 'B산업', amount: 6200, days: 38, status: '위험' },
      { name: 'C건설', amount: 4800, days: 25, status: '주의' },
      { name: 'D제약', amount: 3500, days: 52, status: '위험' },
      { name: 'E식품', amount: 2800, days: 18, status: '주의' },
    ],

    // 현금 흐름
    cashflow: {
      opening: 1800000000,
      closing: 2100000000,
      transactions: [
        { time: '10:30', desc: 'A전자 수금', amount: 85000000 },
        { time: '11:45', desc: 'B산업 원자재 매입', amount: -42000000 },
        { time: '14:20', desc: 'C건설 수금', amount: 125000000 },
        { time: '15:00', desc: '급여 지급', amount: -68000000 },
      ],
    },

    // 매입 현황
    purchaseStatus: {
      total: 90000,
      purchaseRate: 62.8,
      byCategory: [
        { name: '철강자재', amount: 28000, rate: 32.9 },
        { name: '전자부품', amount: 18500, rate: 21.8 },
        { name: '화학원료', amount: 14500, rate: 17.1 },
        { name: '포장재', amount: 12000, rate: 14.1 },
        { name: '기타자재', amount: 12000, rate: 14.1 },
      ],
    },

    // 재고 현황
    inventoryStatus: {
      total: 479,
      normal: 479,
      shortage: 0,
      items: [
        { name: '알루미늄 압출재', current: 450, min: 100, status: '정상' },
        { name: '셔터 세트', current: 15, min: 10, status: '정상' },
        { name: '스크린 셔터 (표준형)', current: 8, min: 5, status: '정상' },
        { name: '철재문 (표준형)', current: 6, min: 5, status: '정상' },
      ],
    },

    // 인사 현황
    hrStatus: {
      totalEmployees: 145,
      attendanceRate: 94.5,
      onLeave: 8,
      onTrip: 5,
      recentActivity: [
        { name: '김철수', type: '연차', period: '2024-10-28 ~ 10-29' },
        { name: '이영희', type: '출장', period: '2024-10-27 ~ 10-30' },
        { name: '박민수', type: '반차', period: '2024-10-28 오후' },
      ],
    },

    // 오늘 일정
    todaySchedule: [
      { time: '09:30', title: '일일 운영회의', location: '회의실B', attendees: 6, type: '필수' },
      { time: '11:00', title: '고객 컴플레인 대응', location: 'CS실', attendees: 4, type: '필수' },
      { time: '14:00', title: '생산성 향상 간담회', location: '생산부', attendees: 15, type: '보류' },
      { time: '16:00', title: '월말 실적 검토', location: '경영지원팀', attendees: 8, type: '보류' },
    ],
  };

  // 위젯 렌더링
  const renderWidget = (widget) => {
    if (!widget.enabled) return null;

    switch (widget.id) {
      case 'daily-metrics':
        return <DailyMetricsWidget data={dashboardData} />;
      case 'process-pipeline':
        return <ProcessPipelineWidget data={dashboardData.process} />;
      case 'sales-achievement':
        return <SalesAchievementWidget data={dashboardData.salesAchievement} />;
      case 'sales-trend':
        return <SalesTrendWidget data={dashboardData.monthlySales} />;
      case 'receivable-trend':
        return <ReceivableTrendWidget data={dashboardData.monthlyReceivable} />;
      case 'top-customers':
        return <TopCustomersWidget data={dashboardData.topCustomers} />;
      case 'production-status':
        return <ProductionStatusWidget data={dashboardData.productionStatus} />;
      case 'quality-status':
        return <QualityStatusWidget data={dashboardData.qualityStatus} />;
      case 'receivable-top5':
        return <ReceivableTop5Widget data={dashboardData.receivableTop5} />;
      case 'cashflow':
        return <CashflowWidget data={dashboardData.cashflow} />;
      case 'purchase-status':
        return <PurchaseStatusWidget data={dashboardData.purchaseStatus} />;
      case 'inventory-status':
        return <InventoryStatusWidget data={dashboardData.inventoryStatus} />;
      case 'hr-status':
        return <HRStatusWidget data={dashboardData.hrStatus} />;
      case 'calendar':
        return <CalendarWidget data={dashboardData.todaySchedule} />;
      default:
        return null;
    }
  };

  const enabledWidgets = widgetConfig.filter(w => w.enabled).sort((a, b) => a.order - b.order);

  return (
    <div className="space-y-4">
      {/* 헤더 */}
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-xl font-bold text-gray-900">대시보드</h2>
          <p className="text-sm text-gray-500">대표이사 대시보드</p>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => setWidgetConfig(prev => prev.map(w => ({ ...w, enabled: true, order: prev.indexOf(w) })))}
            className="text-sm text-gray-600 hover:text-gray-700 px-3 py-2"
          >
            초기화
          </button>
          <button
            onClick={() => setShowWidgetManager(true)}
            className="flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm"
          >
            <Settings className="w-4 h-4" /> 위젯 관리
          </button>
        </div>
      </div>

      {/* 위젯 그리드 */}
      <div className="grid grid-cols-2 gap-4">
        {enabledWidgets.map(widget => (
          <div key={widget.id} className={widget.width === 'full' ? 'col-span-2' : 'col-span-1'}>
            {renderWidget(widget)}
          </div>
        ))}
      </div>

      {/* 위젯 관리 모달 */}
      {showWidgetManager && (
        <WidgetManagerModal
          widgets={widgetConfig}
          onSave={(newConfig) => {
            setWidgetConfig(newConfig);
            setShowWidgetManager(false);
          }}
          onClose={() => setShowWidgetManager(false)}
        />
      )}
    </div>
  );
};

// ============================================================
// 위젯 컴포넌트들
// ============================================================

// 1. 당일 핵심 지표 위젯
const DailyMetricsWidget = ({ data }) => (
  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
    <div className="bg-white rounded-xl border p-5">
      <div className="flex justify-between items-start">
        <div>
          <p className="text-sm text-gray-500">당일 출하매출</p>
          <p className="text-2xl font-bold text-gray-900 mt-1">{(data.dailySales * 10000).toLocaleString()}원</p>
          <div className="flex flex-col gap-0.5 mt-2">
            <span className="text-xs text-green-600">↗ 전일 대비 +{data.dailySalesChange}%</span>
            <span className="text-xs text-blue-600">↗ 전월 동일 대비 +{data.dailySalesMonthChange}%</span>
          </div>
        </div>
        <div className="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center">
          <DollarSign className="w-5 h-5 text-yellow-600" />
        </div>
      </div>
    </div>
    <div className="bg-white rounded-xl border p-5">
      <div className="flex justify-between items-start">
        <div>
          <p className="text-sm text-gray-500">매출총이익률</p>
          <p className="text-2xl font-bold text-gray-900 mt-1">{data.profitMargin}%</p>
          <p className="text-xs text-gray-500 mt-2">영업이익률: {data.operatingMargin}%</p>
        </div>
        <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
          <BarChart3 className="w-5 h-5 text-blue-600" />
        </div>
      </div>
    </div>
    <div className="bg-white rounded-xl border p-5">
      <div className="flex justify-between items-start">
        <div>
          <p className="text-sm text-gray-500">총 미수금</p>
          <p className="text-2xl font-bold text-gray-900 mt-1">{(data.totalReceivable * 10000).toLocaleString()}원</p>
          <p className="text-xs text-red-600 mt-2">연체: {(data.overdueReceivable * 10000).toLocaleString()}원 ({data.overdueRate}%)</p>
        </div>
        <div className="w-10 h-10 bg-red-100 rounded-lg flex items-center justify-center">
          <Clock className="w-5 h-5 text-red-600" />
        </div>
      </div>
    </div>
    <div className="bg-white rounded-xl border p-5">
      <div className="flex justify-between items-start">
        <div>
          <p className="text-sm text-gray-500">일일 순수익</p>
          <p className="text-2xl font-bold text-gray-900 mt-1">{(data.dailyProfit * 10000).toLocaleString()}원</p>
          <p className="text-xs text-gray-500 mt-2">매출-매입-경비: {(data.dailyProfit * 10000).toLocaleString()}원</p>
        </div>
        <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
          <CreditCard className="w-5 h-5 text-green-600" />
        </div>
      </div>
    </div>
  </div>
);

// 2. 프로세스 파이프라인 위젯
const ProcessPipelineWidget = ({ data }) => {
  const stages = [
    { key: 'quote', name: '견적', color: 'bg-blue-100 text-blue-700', badgeColor: 'bg-blue-500' },
    { key: 'order', name: '수주', color: 'bg-indigo-100 text-indigo-700', badgeColor: 'bg-indigo-500' },
    { key: 'production', name: '생산', color: 'bg-yellow-100 text-yellow-700', badgeColor: 'bg-yellow-500' },
    { key: 'inspection', name: '검사', color: 'bg-purple-100 text-purple-700', badgeColor: 'bg-purple-500' },
    { key: 'shipping', name: '출고', color: 'bg-orange-100 text-orange-700', badgeColor: 'bg-orange-500' },
    { key: 'completed', name: '완료', color: 'bg-green-100 text-green-700', badgeColor: 'bg-green-500' },
  ];

  return (
    <div className="bg-white rounded-xl border p-5">
      <div className="flex items-center gap-2 mb-4">
        <div className="w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center">
          <Zap className="w-4 h-4 text-purple-600" />
        </div>
        <div>
          <h3 className="font-medium text-purple-700">모든 프로세스 현황</h3>
          <p className="text-xs text-gray-500">전체 업무 프로세스 실시간 모니터링</p>
        </div>
      </div>

      {/* 파이프라인 */}
      <div className="flex gap-2 mb-6">
        {stages.map((stage, idx) => (
          <div key={stage.key} className={`flex-1 ${stage.color} rounded-lg p-3 text-center relative`}>
            <span className={`absolute -top-2 -right-2 ${stage.badgeColor} text-white text-xs w-6 h-6 rounded-full flex items-center justify-center`}>
              {data[stage.key].count}
            </span>
            <p className="font-medium">{stage.name}</p>
            <p className="text-xs opacity-70">진행중</p>
          </div>
        ))}
      </div>

      {/* 상세 목록 */}
      <div className="grid grid-cols-3 gap-4">
        {stages.slice(0, 3).map(stage => (
          <div key={stage.key} className="border rounded-lg p-3">
            <div className="flex justify-between items-center mb-2">
              <div className="flex items-center gap-2">
                <span className={`w-6 h-6 rounded ${stage.badgeColor} text-white text-xs flex items-center justify-center`}>
                  {data[stage.key].count}
                </span>
                <span className="font-medium text-sm">{stage.name}</span>
              </div>
              <button className="text-xs text-blue-600">2건</button>
            </div>
            <div className="space-y-2">
              {data[stage.key].items.map((item, i) => (
                <div key={i} className="flex justify-between items-center text-sm">
                  <div>
                    <p className="font-medium text-gray-900">{item.name}</p>
                    <p className="text-xs text-gray-500">{item.desc}</p>
                    {item.amount && <p className="text-xs text-gray-600">{item.amount}M원</p>}
                  </div>
                  <span className={`px-2 py-0.5 rounded text-xs ${item.status === '검토중' ? 'bg-blue-100 text-blue-700' :
                      item.status === '대기' ? 'bg-gray-100 text-gray-700' :
                        item.status === '승인' ? 'bg-green-100 text-green-700' :
                          item.status === '계약중' ? 'bg-purple-100 text-purple-700' :
                            item.status === '진행중' ? 'bg-yellow-100 text-yellow-700' :
                              'bg-gray-100 text-gray-700'
                    }`}>
                    {item.status}
                  </span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-3 gap-4 mt-4">
        {stages.slice(3).map(stage => (
          <div key={stage.key} className="border rounded-lg p-3">
            <div className="flex justify-between items-center mb-2">
              <div className="flex items-center gap-2">
                <span className={`w-6 h-6 rounded ${stage.badgeColor} text-white text-xs flex items-center justify-center`}>
                  {data[stage.key].count}
                </span>
                <span className="font-medium text-sm">{stage.name}</span>
              </div>
              <button className="text-xs text-blue-600">2건</button>
            </div>
            <div className="space-y-2">
              {data[stage.key].items.map((item, i) => (
                <div key={i} className="flex justify-between items-center text-sm">
                  <div>
                    <p className="font-medium text-gray-900">{item.name}</p>
                    <p className="text-xs text-gray-500">{item.desc}</p>
                    {item.amount !== undefined && item.amount > 0 && <p className="text-xs text-gray-600">{item.amount}M원</p>}
                  </div>
                  <span className={`px-2 py-0.5 rounded text-xs ${item.status === '검사중' ? 'bg-purple-100 text-purple-700' :
                      item.status === '포장중' ? 'bg-orange-100 text-orange-700' :
                        item.status === '준비완료' ? 'bg-blue-100 text-blue-700' :
                          item.status === '납품완료' ? 'bg-green-100 text-green-700' :
                            'bg-gray-100 text-gray-700'
                    }`}>
                    {item.status}
                  </span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// 3. 매출 달성 위젯
const SalesAchievementWidget = ({ data }) => {
  const periods = [
    { key: 'daily', label: '일별 매출', unit: 'M', color: 'blue' },
    { key: 'monthly', label: '월별 매출', unit: '억', color: 'green' },
    { key: 'yearly', label: '연간 매출', unit: '억', color: 'purple' },
  ];

  return (
    <div className="grid grid-cols-3 gap-4">
      {periods.map(period => {
        const d = data[period.key];
        return (
          <div key={period.key} className="bg-white rounded-xl border p-5">
            <div className="flex justify-between items-center mb-3">
              <div className="flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-gray-600" />
                <span className="font-medium text-gray-900">{period.label}</span>
              </div>
              <span className={`px-2 py-1 rounded text-sm font-bold ${d.rate >= 90 ? 'bg-blue-100 text-blue-700' :
                  d.rate >= 70 ? 'bg-green-100 text-green-700' :
                    'bg-purple-100 text-purple-700'
                }`}>
                {d.rate}%
              </span>
            </div>
            <div className="grid grid-cols-2 gap-4 mb-3">
              <div>
                <p className="text-xs text-gray-500">목표</p>
                <p className="text-lg font-bold">{d.target}{period.unit}</p>
              </div>
              <div>
                <p className="text-xs text-gray-500">실적</p>
                <p className={`text-lg font-bold ${period.color === 'blue' ? 'text-blue-600' :
                    period.color === 'green' ? 'text-green-600' :
                      'text-purple-600'
                  }`}>{period.key === 'daily' ? d.actual : (d.actual / 100).toFixed(1)}{period.unit}</p>
              </div>
            </div>
            <div className="mb-3">
              <div className="flex justify-between text-xs mb-1">
                <span>달성률</span>
                <span className="font-medium">{d.rate}%</span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div className={`h-2 rounded-full ${period.color === 'blue' ? 'bg-blue-500' :
                    period.color === 'green' ? 'bg-green-500' :
                      'bg-purple-500'
                  }`} style={{ width: `${Math.min(d.rate, 100)}%` }} />
              </div>
            </div>
            <div className="flex justify-between text-sm">
              <div>
                <span className="text-gray-500">수금액</span>
                <span className="ml-2 font-medium">{period.key === 'daily' ? d.collected : (d.collected / 100).toFixed(1)}{period.unit}</span>
              </div>
              <div>
                <span className="text-gray-500">미수금</span>
                <span className="ml-2 font-medium text-red-600">{period.key === 'daily' ? d.receivable : (d.receivable / 100).toFixed(1)}{period.unit}</span>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
};

// 4. 매출 추이 차트 위젯
const SalesTrendWidget = ({ data }) => {
  const maxAmount = Math.max(...data.map(d => d.amount));
  const avgRate = 94.5;
  const maxRate = 105.3;
  const minRate = 85.3;

  return (
    <div className="bg-white rounded-xl border p-5">
      <div className="flex items-center gap-2 mb-4">
        <BarChart3 className="w-4 h-4 text-gray-600" />
        <span className="font-medium text-gray-900">월별 매출 추이 (최근 12개월)</span>
      </div>
      <div className="h-48 flex items-end gap-2">
        {data.map((d, i) => (
          <div key={i} className="flex-1 flex flex-col items-center">
            <div
              className="w-full bg-blue-400 rounded-t hover:bg-blue-500 transition-colors"
              style={{ height: `${(d.amount / maxAmount) * 100}%` }}
            />
            <span className="text-xs text-gray-500 mt-1">{d.month.replace('월', '')}</span>
          </div>
        ))}
      </div>
      <div className="grid grid-cols-3 gap-4 mt-4 pt-4 border-t">
        <div className="text-center">
          <p className="text-xs text-gray-500">평균 달성률</p>
          <p className="text-lg font-bold text-blue-600">{avgRate}%</p>
        </div>
        <div className="text-center">
          <p className="text-xs text-gray-500">최고 달성률</p>
          <p className="text-lg font-bold text-green-600">{maxRate}%</p>
        </div>
        <div className="text-center">
          <p className="text-xs text-gray-500">최저 달성률</p>
          <p className="text-lg font-bold text-orange-600">{minRate}%</p>
        </div>
      </div>
    </div>
  );
};

// 5. 미수금 추이 위젯
const ReceivableTrendWidget = ({ data }) => {
  const maxAmount = Math.max(...data.map(d => d.amount));
  const avgReceivable = 417;
  const maxReceivable = 460;

  return (
    <div className="bg-white rounded-xl border p-5">
      <div className="flex items-center gap-2 mb-4">
        <Clock className="w-4 h-4 text-gray-600" />
        <span className="font-medium text-gray-900">월별 미수금 추이</span>
      </div>
      <div className="h-48 relative">
        <svg className="w-full h-full" viewBox="0 0 400 150">
          <polyline
            fill="none"
            stroke="#f97316"
            strokeWidth="2"
            points={data.map((d, i) => `${(i / (data.length - 1)) * 380 + 10},${150 - (d.amount / maxAmount) * 130}`).join(' ')}
          />
          {data.map((d, i) => (
            <circle
              key={i}
              cx={(i / (data.length - 1)) * 380 + 10}
              cy={150 - (d.amount / maxAmount) * 130}
              r="4"
              fill="#f97316"
            />
          ))}
        </svg>
        <div className="absolute bottom-0 left-0 right-0 flex justify-between px-2">
          {data.map((d, i) => (
            <span key={i} className="text-xs text-gray-500">{d.month.replace('월', '')}</span>
          ))}
        </div>
      </div>
      <div className="grid grid-cols-2 gap-4 mt-4 pt-4 border-t">
        <div className="text-center">
          <p className="text-xs text-gray-500">평균 미수금</p>
          <p className="text-lg font-bold text-purple-600">{avgReceivable}M원</p>
        </div>
        <div className="text-center">
          <p className="text-xs text-gray-500">최고 미수금</p>
          <p className="text-lg font-bold text-red-600">{maxReceivable}M원</p>
        </div>
      </div>
    </div>
  );
};

// 6. TOP 5 고객 위젯
const TopCustomersWidget = ({ data }) => (
  <div className="bg-white rounded-xl border p-5">
    <div className="flex items-center gap-2 mb-4">
      <Users className="w-4 h-4 text-gray-600" />
      <span className="font-medium text-gray-900">TOP 5 고객</span>
    </div>
    <div className="space-y-3">
      {data.map((customer, i) => (
        <div key={i} className="flex items-center gap-3">
          <span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white ${i === 0 ? 'bg-yellow-500' :
              i === 1 ? 'bg-gray-400' :
                i === 2 ? 'bg-orange-400' :
                  'bg-blue-400'
            }`}>
            {customer.rank}
          </span>
          <div className="flex-1">
            <p className="font-medium text-gray-900">{customer.name}</p>
            <p className="text-sm text-gray-500">W{(customer.amount / 100).toFixed(1)}M</p>
          </div>
          <span className={`text-sm font-medium ${customer.change >= 0 ? 'text-green-600' : 'text-red-600'}`}>
            {customer.change >= 0 ? '↗' : '↘'} {Math.abs(customer.change)}%
          </span>
        </div>
      ))}
    </div>
  </div>
);

// 7. 생산 현황 위젯
const ProductionStatusWidget = ({ data }) => (
  <div className="bg-white rounded-xl border p-5">
    <div className="flex items-center gap-2 mb-4">
      <Factory className="w-4 h-4 text-gray-600" />
      <span className="font-medium text-gray-900">생산 현황</span>
    </div>
    <div className="bg-blue-50 rounded-lg p-3 mb-4">
      <div className="flex justify-between items-center">
        <span className="text-sm text-gray-600">전체 달성률</span>
        <span className="text-lg font-bold text-blue-600">{data.rate}%</span>
      </div>
      <p className="text-xs text-gray-500 mt-1">{data.completed} / {data.total} 개 &nbsp;&nbsp;&nbsp; 가동률 {data.utilization}%</p>
    </div>
    <div>
      <p className="text-sm font-medium text-gray-700 mb-2">공정별 현황</p>
      <div className="space-y-2">
        {data.processes.map((proc, i) => (
          <div key={i}>
            <div className="flex justify-between items-center mb-1">
              <span className="text-sm text-gray-600">{proc.name}</span>
              <span className={`px-2 py-0.5 rounded text-xs ${proc.status === '정상' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                }`}>
                {proc.status}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <div className="flex-1 bg-gray-200 rounded-full h-2">
                <div
                  className={`h-2 rounded-full ${proc.status === '정상' ? 'bg-blue-500' : 'bg-yellow-500'}`}
                  style={{ width: `${proc.rate}%` }}
                />
              </div>
              <span className="text-xs text-gray-500 w-20">{proc.completed}/{proc.total}개 ({proc.rate}%)</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// 8. 품질 현황 위젯
const QualityStatusWidget = ({ data }) => (
  <div className="bg-white rounded-xl border p-5">
    <div className="flex items-center gap-2 mb-4">
      <ShieldCheck className="w-4 h-4 text-gray-600" />
      <span className="font-medium text-gray-900">품질 현황</span>
    </div>
    <div className="bg-green-50 rounded-lg p-4 mb-4">
      <p className="text-xs text-gray-500">전체 불량률</p>
      <p className="text-3xl font-bold text-green-600">{data.defectRate}%</p>
      <p className="text-xs text-green-600 mt-1">목표: {data.target}% 이하</p>
    </div>
    <div className="grid grid-cols-3 gap-2 mb-4">
      <div className="bg-gray-50 rounded-lg p-3 text-center">
        <p className="text-xs text-gray-500">검사</p>
        <p className="text-lg font-bold">{data.inspected}</p>
      </div>
      <div className="bg-gray-50 rounded-lg p-3 text-center">
        <p className="text-xs text-gray-500">합격</p>
        <p className="text-lg font-bold text-green-600">{data.passed}</p>
      </div>
      <div className="bg-gray-50 rounded-lg p-3 text-center">
        <p className="text-xs text-gray-500">불량</p>
        <p className="text-lg font-bold text-red-600">{data.defects}</p>
      </div>
    </div>
    <div>
      <p className="text-sm font-medium text-gray-700 mb-2">공정별 불량률</p>
      <div className="space-y-2">
        {data.byProcess.map((proc, i) => (
          <div key={i} className="flex justify-between items-center">
            <span className="text-sm text-gray-600">{proc.name}</span>
            <span className={`px-2 py-0.5 rounded text-xs ${proc.rate === 0 ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
              }`}>
              {proc.rate}%
            </span>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// 9. 미수금 관리 위젯
const ReceivableTop5Widget = ({ data }) => (
  <div className="bg-white rounded-xl border p-5">
    <div className="flex items-center gap-2 mb-4">
      <CreditCard className="w-4 h-4 text-gray-600" />
      <span className="font-medium text-gray-900">거래처별 미수금 TOP 5</span>
    </div>
    <div className="space-y-3">
      {data.map((item, i) => (
        <div key={i} className="flex justify-between items-center">
          <div>
            <p className="font-medium text-gray-900">{item.name}</p>
            <p className="text-xs text-gray-500">{item.days}일 경과</p>
          </div>
          <div className="text-right">
            <p className="font-bold text-gray-900">{(item.amount * 10000).toLocaleString()}원</p>
            <span className={`px-2 py-0.5 rounded text-xs ${item.status === '위험' ? 'bg-red-100 text-red-700' : 'bg-yellow-100 text-yellow-700'
              }`}>
              {item.status}
            </span>
          </div>
        </div>
      ))}
    </div>
  </div>
);

// 10. 현금 흐름 위젯
const CashflowWidget = ({ data }) => (
  <div className="bg-white rounded-xl border p-5">
    <div className="flex items-center gap-2 mb-4">
      <DollarSign className="w-4 h-4 text-gray-600" />
      <span className="font-medium text-gray-900">현금 흐름 및 주요 거래</span>
    </div>
    <div className="grid grid-cols-2 gap-4 mb-4">
      <div className="bg-gray-50 rounded-lg p-3">
        <p className="text-xs text-gray-500">기초잔고</p>
        <p className="text-lg font-bold">{(data.opening / 100000000).toFixed(0)}억원</p>
      </div>
      <div className="bg-blue-50 rounded-lg p-3">
        <p className="text-xs text-gray-500">기말잔고</p>
        <p className="text-lg font-bold text-blue-600">{(data.closing / 100000000).toFixed(0)}억원</p>
      </div>
    </div>
    <div>
      <p className="text-sm font-medium text-gray-700 mb-2">주요 수입/지출 내역</p>
      <div className="space-y-2">
        {data.transactions.map((tx, i) => (
          <div key={i} className="flex justify-between items-center py-2 border-b last:border-0">
            <div>
              <p className="font-medium text-gray-900">{tx.desc}</p>
              <p className="text-xs text-gray-500">{tx.time}</p>
            </div>
            <span className={`font-bold ${tx.amount >= 0 ? 'text-blue-600' : 'text-red-600'}`}>
              {tx.amount >= 0 ? '+' : ''}{tx.amount.toLocaleString()}원
            </span>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// 11. 매입 현황 위젯
const PurchaseStatusWidget = ({ data }) => (
  <div className="bg-white rounded-xl border p-5">
    <div className="flex items-center gap-2 mb-4">
      <ShoppingCart className="w-4 h-4 text-gray-600" />
      <span className="font-medium text-gray-900">주요 거래처별 매입 현황</span>
    </div>
    <div className="grid grid-cols-2 gap-4 mb-4">
      <div>
        <p className="text-xs text-gray-500">월 총 매입액</p>
        <p className="text-lg font-bold">{(data.total / 10000).toFixed(0)}억원</p>
      </div>
      <div>
        <p className="text-xs text-gray-500">매출 대비 매입률</p>
        <p className="text-lg font-bold text-orange-600">{data.purchaseRate}%</p>
      </div>
    </div>
    <div className="space-y-2">
      {data.byCategory.map((cat, i) => (
        <div key={i} className="flex justify-between items-center">
          <span className="text-sm text-gray-600">{cat.name}</span>
          <div className="text-right">
            <span className="font-medium">{cat.amount.toLocaleString()}M원</span>
            <span className="text-xs text-gray-500 ml-2">{cat.rate}%</span>
          </div>
        </div>
      ))}
    </div>
  </div>
);

// 12. 재고 현황 위젯
const InventoryStatusWidget = ({ data }) => (
  <div className="bg-white rounded-xl border p-5">
    <div className="flex items-center gap-2 mb-4">
      <Box className="w-4 h-4 text-gray-600" />
      <span className="font-medium text-gray-900">재고 현황</span>
    </div>
    <div className="bg-green-50 rounded-lg p-3 mb-4">
      <div className="flex justify-between items-center">
        <div>
          <p className="text-xs text-gray-500">전체 재고</p>
          <p className="text-2xl font-bold text-green-600">{data.total} 개</p>
        </div>
        <span className="px-2 py-1 bg-green-500 text-white text-xs rounded">100%</span>
      </div>
      <p className="text-xs text-gray-500 mt-1">정상: {data.normal} | 부족: {data.shortage}</p>
    </div>
    <div>
      <p className="text-sm font-medium text-gray-700 mb-2">주요 자재 현황</p>
      <div className="space-y-2">
        {data.items.map((item, i) => (
          <div key={i}>
            <div className="flex justify-between items-center mb-1">
              <span className="text-sm text-gray-600">{item.name}</span>
              <span className={`px-2 py-0.5 rounded text-xs ${item.status === '정상' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                }`}>
                {item.status}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <div className="flex-1 bg-gray-200 rounded-full h-2">
                <div
                  className="bg-blue-500 h-2 rounded-full"
                  style={{ width: `${Math.min((item.current / item.min) * 20, 100)}%` }}
                />
              </div>
              <span className="text-xs text-gray-500">현재: {item.current} / 최소: {item.min}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// 13. 인사 현황 위젯
const HRStatusWidget = ({ data }) => (
  <div className="bg-white rounded-xl border p-5">
    <div className="flex items-center gap-2 mb-4">
      <User className="w-4 h-4 text-gray-600" />
      <span className="font-medium text-gray-900">인사 현황</span>
    </div>
    <div className="grid grid-cols-2 gap-4 mb-4">
      <div className="bg-gray-50 rounded-lg p-3">
        <p className="text-xs text-gray-500">총 인원</p>
        <p className="text-2xl font-bold">{data.totalEmployees}명</p>
      </div>
      <div className="bg-green-50 rounded-lg p-3">
        <p className="text-xs text-gray-500">출근율</p>
        <p className="text-2xl font-bold text-green-600">{data.attendanceRate}%</p>
      </div>
    </div>
    <div className="flex gap-4 mb-4">
      <div className="flex items-center gap-2">
        <Calendar className="w-4 h-4 text-gray-400" />
        <span className="text-sm text-gray-600">휴가 사용중</span>
        <span className="font-bold">{data.onLeave}명</span>
      </div>
      <div className="flex items-center gap-2">
        <Truck className="w-4 h-4 text-gray-400" />
        <span className="text-sm text-gray-600">출장중</span>
        <span className="font-bold">{data.onTrip}명</span>
      </div>
    </div>
    <div>
      <p className="text-sm font-medium text-gray-700 mb-2">최근 활동</p>
      <div className="space-y-2">
        {data.recentActivity.map((act, i) => (
          <div key={i} className="flex justify-between items-center">
            <div>
              <p className="font-medium text-gray-900">{act.name}</p>
              <p className="text-xs text-gray-500">{act.period}</p>
            </div>
            <span className={`px-2 py-0.5 rounded text-xs ${act.type === '연차' ? 'bg-blue-100 text-blue-700' :
                act.type === '출장' ? 'bg-purple-100 text-purple-700' :
                  'bg-gray-100 text-gray-700'
              }`}>
              {act.type}
            </span>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// 14. 캘린더 위젯
const CalendarWidget = ({ data }) => {
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const firstDayOfMonth = new Date(year, month, 1).getDay();
  const todayDate = today.getDate();

  const days = [];
  for (let i = 0; i < firstDayOfMonth; i++) days.push(null);
  for (let i = 1; i <= daysInMonth; i++) days.push(i);

  const weekDays = ['일', '월', '화', '수', '목', '금', '토'];

  return (
    <div className="bg-white rounded-xl border p-5">
      <div className="flex items-center gap-2 mb-4">
        <Calendar className="w-4 h-4 text-gray-600" />
        <span className="font-medium text-gray-900">일정 캘린더</span>
      </div>
      <div className="grid grid-cols-2 gap-4">
        {/* 캘린더 */}
        <div>
          <p className="text-sm font-medium text-center mb-2">{month + 1}월 {year}</p>
          <div className="grid grid-cols-7 gap-1 text-center text-xs">
            {weekDays.map(d => (
              <div key={d} className="text-gray-500 py-1">{d}</div>
            ))}
            {days.map((day, i) => (
              <div
                key={i}
                className={`py-1 rounded ${day === todayDate
                    ? 'bg-blue-500 text-white font-bold'
                    : day ? 'hover:bg-gray-100' : ''
                  }`}
              >
                {day}
              </div>
            ))}
          </div>
        </div>
        {/* 오늘 일정 */}
        <div>
          <p className="text-sm font-medium mb-2">{month + 1}월 {todayDate}일 {weekDays[today.getDay()]}요일</p>
          <p className="text-xs text-gray-500 mb-2">총 {data.length}개의 일정</p>
          <div className="space-y-2 max-h-40 overflow-y-auto">
            {data.map((item, i) => (
              <div key={i} className="p-2 bg-gray-50 rounded">
                <div className="flex justify-between items-start">
                  <p className="font-medium text-sm">{item.title}</p>
                  <span className={`px-1.5 py-0.5 rounded text-xs ${item.type === '필수' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'
                    }`}>
                    {item.type}
                  </span>
                </div>
                <div className="flex gap-2 text-xs text-gray-500 mt-1">
                  <span>⏰ {item.time}</span>
                  <span>📍 {item.location}</span>
                  <span>👥 {item.attendees}명</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// 위젯 관리 모달
// ============================================================
const WidgetManagerModal = ({ widgets, onSave, onClose }) => {
  const [config, setConfig] = useState([...widgets]);
  const [activeTab, setActiveTab] = useState('current');

  const enabledCount = config.filter(w => w.enabled).length;
  const totalCount = config.length;

  const toggleWidget = (id) => {
    setConfig(prev => prev.map(w => w.id === id ? { ...w, enabled: !w.enabled } : w));
  };

  const setWidgetWidth = (id, width) => {
    setConfig(prev => prev.map(w => w.id === id ? { ...w, width } : w));
  };

  const resetToDefault = () => {
    setConfig(prev => prev.map((w, i) => ({ ...w, enabled: true, order: i })));
  };

  const moveWidget = (id, direction) => {
    const idx = config.findIndex(w => w.id === id);
    if ((direction === -1 && idx === 0) || (direction === 1 && idx === config.length - 1)) return;

    const newConfig = [...config];
    [newConfig[idx], newConfig[idx + direction]] = [newConfig[idx + direction], newConfig[idx]];
    newConfig.forEach((w, i) => w.order = i);
    setConfig(newConfig);
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[90vh] overflow-hidden flex flex-col">
        {/* 헤더 */}
        <div className="p-4 border-b">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-bold">위젯 관리</h3>
            <button onClick={onClose} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
              ✕
            </button>
          </div>
          <p className="text-sm text-gray-500 mt-1">
            대시보드에 표시할 위젯을 선택하고 순서를 변경할 수 있습니다. 각 위젯의 너비를 전체 또는 절반(1/2)으로 설정할 수 있습니다.
          </p>
        </div>

        {/* 탭 */}
        <div className="flex border-b">
          <button
            onClick={() => setActiveTab('current')}
            className={`flex-1 py-3 text-sm font-medium ${activeTab === 'current' ? 'border-b-2 border-blue-500 text-blue-600' : 'text-gray-500'
              }`}
          >
            현재 위젯
          </button>
          <button
            onClick={() => setActiveTab('add')}
            className={`flex-1 py-3 text-sm font-medium ${activeTab === 'add' ? 'border-b-2 border-blue-500 text-blue-600' : 'text-gray-500'
              }`}
          >
            위젯 추가
          </button>
        </div>

        {/* 통계 & 초기화 */}
        <div className="flex justify-between items-center p-4 border-b">
          <span className="text-sm text-gray-600">활성화된 위젯: <span className="font-bold">{enabledCount}</span> / {totalCount}</span>
          <button
            onClick={resetToDefault}
            className="text-sm text-blue-600 hover:text-blue-700 px-3 py-1 border border-blue-200 rounded-lg"
          >
            기본값으로 초기화
          </button>
        </div>

        {/* 위젯 목록 */}
        <div className="flex-1 overflow-y-auto p-4">
          <div className="space-y-2">
            {config.filter(w => activeTab === 'current' ? w.enabled : !w.enabled).map((widget, idx) => (
              <div key={widget.id} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                {/* 드래그 핸들 */}
                <div className="cursor-move text-gray-400">
                  <div className="grid grid-cols-2 gap-0.5">
                    <div className="w-1 h-1 bg-gray-400 rounded-full" />
                    <div className="w-1 h-1 bg-gray-400 rounded-full" />
                    <div className="w-1 h-1 bg-gray-400 rounded-full" />
                    <div className="w-1 h-1 bg-gray-400 rounded-full" />
                    <div className="w-1 h-1 bg-gray-400 rounded-full" />
                    <div className="w-1 h-1 bg-gray-400 rounded-full" />
                  </div>
                </div>

                {/* 아이콘 */}
                <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Zap className="w-5 h-5 text-blue-600" />
                </div>

                {/* 정보 */}
                <div className="flex-1 min-w-0">
                  <p className="font-medium text-gray-900 truncate">{widget.name}</p>
                  <p className="text-xs text-gray-500 truncate">{widget.desc}</p>
                </div>

                {/* 너비 선택 */}
                <div className="flex items-center gap-1">
                  <span className="text-xs text-gray-500">너비:</span>
                  <button
                    onClick={() => setWidgetWidth(widget.id, 'full')}
                    className={`px-2 py-1 text-xs rounded ${widget.width === 'full' ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-600'
                      }`}
                  >
                    전체
                  </button>
                  <button
                    onClick={() => setWidgetWidth(widget.id, 'half')}
                    className={`px-2 py-1 text-xs rounded ${widget.width === 'half' ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-600'
                      }`}
                  >
                    1/2
                  </button>
                </div>

                {/* 토글 */}
                <button
                  onClick={() => toggleWidget(widget.id)}
                  className={`w-12 h-6 rounded-full transition-colors ${widget.enabled ? 'bg-blue-500' : 'bg-gray-300'
                    }`}
                >
                  <div className={`w-5 h-5 bg-white rounded-full shadow transform transition-transform ${widget.enabled ? 'translate-x-6' : 'translate-x-0.5'
                    }`} />
                </button>

                {/* 삭제 */}
                <button
                  onClick={() => toggleWidget(widget.id)}
                  className="p-1 text-red-400 hover:text-red-600"
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* 푸터 */}
        <div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
          <button
            onClick={onClose}
            className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            취소
          </button>
          <button
            onClick={() => onSave(config)}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            저장
          </button>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// 역할별 대시보드
// ============================================================

// 판매팀(판매담당자) 대시보드
const SalesDashboard = ({ quotes = [], orders = [], shipments = [], onNavigate }) => {
  // 실제 데이터 기반 통계
  const pendingQuotes = quotes.filter(q => q.status === '검토중' || q.status === '작성중');
  const confirmedOrders = orders.filter(o => o.status === '확정');
  const pendingProduction = orders.filter(o => o.productionStatus === '대기' || !o.productionStatus);
  const readyToShip = orders.filter(o => o.productionStatus === '완료' && o.shipmentStatus !== '출하완료');

  // 내가 작성한 생산지시 중 승인대기 (참조용)
  const myPendingApprovals = orders.filter(o =>
    o.splits?.some(s => s.productionStatus === '승인대기')
  );

  return (
    <div className="space-y-4">
      <div className="space-y-3">
        <div>
          <h2 className="text-xl font-bold text-gray-900">판매담당자 대시보드</h2>
          <p className="text-sm text-gray-500">판매팀 전용 대시보드</p>
        </div>
        <div className="flex justify-end gap-2">
          <button
            onClick={() => onNavigate('quote-create')}
            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 text-sm font-medium flex items-center gap-2"
          >
            <Plus className="w-4 h-4" /> 견적 등록
          </button>
        </div>
      </div>

      {/* 핵심 지표 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div
          className="bg-white rounded-xl border p-5 cursor-pointer hover:border-blue-300 transition-colors"
          onClick={() => onNavigate('quote-list')}
        >
          <div className="flex items-center gap-2 mb-2">
            <FileText className="w-5 h-5 text-blue-500" />
            <p className="text-sm text-gray-500">견적 대기</p>
          </div>
          <p className="text-2xl font-bold">{pendingQuotes.length}건</p>
          <p className="text-xs text-gray-400 mt-1">클릭하여 견적 목록 이동</p>
        </div>
        <div
          className="bg-white rounded-xl border p-5 cursor-pointer hover:border-green-300 transition-colors"
          onClick={() => onNavigate('order-list')}
        >
          <div className="flex items-center gap-2 mb-2">
            <ShoppingCart className="w-5 h-5 text-green-500" />
            <p className="text-sm text-gray-500">확정 수주</p>
          </div>
          <p className="text-2xl font-bold text-green-600">{confirmedOrders.length}건</p>
          <p className="text-xs text-gray-400 mt-1">클릭하여 수주 목록 이동</p>
        </div>
        <div
          className="bg-white rounded-xl border p-5 cursor-pointer hover:border-yellow-300 transition-colors"
          onClick={() => onNavigate('order-list')}
        >
          <div className="flex items-center gap-2 mb-2">
            <Factory className="w-5 h-5 text-yellow-500" />
            <p className="text-sm text-gray-500">생산지시 대기</p>
          </div>
          <p className="text-2xl font-bold text-yellow-600">{pendingProduction.length}건</p>
          <p className="text-xs text-gray-400 mt-1">생산지시 필요</p>
        </div>
        <div
          className="bg-white rounded-xl border p-5 cursor-pointer hover:border-purple-300 transition-colors"
          onClick={() => onNavigate('shipment-list')}
        >
          <div className="flex items-center gap-2 mb-2">
            <Truck className="w-5 h-5 text-purple-500" />
            <p className="text-sm text-gray-500">출하 대기</p>
          </div>
          <p className="text-2xl font-bold text-purple-600">{readyToShip.length}건</p>
          <p className="text-xs text-gray-400 mt-1">생산완료, 출하 가능</p>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4">
        {/* 최근 견적 */}
        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-medium text-gray-900">최근 견적</h3>
            <button
              onClick={() => onNavigate('quote-list')}
              className="text-sm text-blue-600 hover:text-blue-700"
            >
              전체보기 →
            </button>
          </div>
          <div className="space-y-2">
            {quotes.slice(0, 5).map((q, i) => (
              <div
                key={i}
                className="flex justify-between items-center p-3 bg-gray-50 rounded-lg cursor-pointer hover:bg-gray-100"
                onClick={() => onNavigate('quote-detail', q)}
              >
                <div>
                  <p className="font-mono text-sm text-blue-600">{q.quoteNo}</p>
                  <p className="text-sm text-gray-600">{q.customerName}</p>
                </div>
                <div className="text-right">
                  <p className="text-sm font-medium">{(q.totalAmount / 10000).toLocaleString()}만원</p>
                  <span className={`inline-block px-2 py-0.5 rounded text-xs ${q.status === '수주전환' ? 'bg-green-100 text-green-700' :
                      q.status === '검토중' ? 'bg-blue-100 text-blue-700' :
                        'bg-gray-100 text-gray-600'
                    }`}>
                    {q.status}
                  </span>
                </div>
              </div>
            ))}
            {quotes.length === 0 && (
              <p className="text-center text-gray-400 py-4">견적 데이터가 없습니다</p>
            )}
          </div>
        </div>

        {/* 최근 수주 */}
        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-medium text-gray-900">최근 수주</h3>
            <button
              onClick={() => onNavigate('order-list')}
              className="text-sm text-blue-600 hover:text-blue-700"
            >
              전체보기 →
            </button>
          </div>
          <div className="space-y-2">
            {orders.slice(0, 5).map((o, i) => (
              <div
                key={i}
                className="flex justify-between items-center p-3 bg-gray-50 rounded-lg cursor-pointer hover:bg-gray-100"
                onClick={() => onNavigate('order-detail', o)}
              >
                <div>
                  <p className="font-mono text-sm text-blue-600">{o.orderNo}</p>
                  <p className="text-sm text-gray-600">{o.customerName}</p>
                </div>
                <div className="text-right">
                  <p className="text-sm text-gray-500">{o.dueDate}</p>
                  <span className={`inline-block px-2 py-0.5 rounded text-xs ${o.creditGrade === 'A' ? 'bg-green-100 text-green-700' :
                      o.creditGrade === 'B' ? 'bg-yellow-100 text-yellow-700' :
                        'bg-red-100 text-red-700'
                    }`}>
                    {o.creditGrade}등급
                  </span>
                </div>
              </div>
            ))}
            {orders.length === 0 && (
              <p className="text-center text-gray-400 py-4">수주 데이터가 없습니다</p>
            )}
          </div>
        </div>
      </div>

      {/* 내 생산지시 승인 현황 (참조) */}
      {myPendingApprovals.length > 0 && (
        <div className="bg-blue-50 border border-blue-200 rounded-xl p-5">
          <h3 className="font-medium text-blue-800 mb-3">내가 요청한 생산지시 승인 현황</h3>
          <p className="text-sm text-blue-600 mb-2">
            {myPendingApprovals.length}건의 생산지시가 생산관리팀 승인을 기다리고 있습니다.
          </p>
          <p className="text-xs text-blue-500">※ 승인되면 생산이 시작됩니다.</p>
        </div>
      )}
    </div>
  );
};

// 생산관리자 대시보드
const ProductionDashboard = ({ workOrders = [], onNavigate, onApprove }) => {
  // 실제 데이터 기반 통계
  const pendingApproval = workOrders.filter(w => w.approvalStatus === '승인대기');
  const inProgressOrders = workOrders.filter(w => w.status === '작업중');
  const waitingOrders = workOrders.filter(w => w.status === '작업대기' && w.approvalStatus !== '승인대기');
  const completedOrders = workOrders.filter(w => w.status === '작업완료');

  // 납기 임박 (D-3 이내)
  const today = new Date();
  const urgentOrders = workOrders.filter(w => {
    if (w.status === '작업완료') return false;
    const dueDate = new Date(w.dueDate);
    const diffDays = Math.ceil((dueDate - today) / (1000 * 60 * 60 * 24));
    return diffDays <= 3 && diffDays >= 0;
  });

  // 승인 처리
  const handleApprove = (wo) => {
    if (onApprove) {
      onApprove(wo.id);
    }
  };

  return (
    <div className="space-y-4">
      <div className="space-y-3">
        <div>
          <h2 className="text-xl font-bold text-gray-900">생산관리자 대시보드</h2>
          <p className="text-sm text-gray-500">생산관리팀 전용 대시보드</p>
        </div>
        <div className="flex justify-end gap-2">
          <button
            onClick={() => onNavigate('work-order-list')}
            className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 text-sm font-medium flex items-center gap-2"
          >
            <ClipboardList className="w-4 h-4" /> 작업지시 목록
          </button>
        </div>
      </div>

      {/* 핵심 지표 */}
      <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
        <div
          className="bg-white rounded-xl border p-5 cursor-pointer hover:border-yellow-300 transition-colors"
          onClick={() => onNavigate('work-order-list')}
        >
          <div className="flex items-center gap-2 mb-2">
            <Clock className="w-5 h-5 text-yellow-500" />
            <p className="text-sm text-gray-500">작업대기</p>
          </div>
          <p className="text-2xl font-bold text-yellow-600">{waitingOrders.length}건</p>
        </div>
        <div
          className="bg-white rounded-xl border p-5 cursor-pointer hover:border-blue-300 transition-colors"
          onClick={() => onNavigate('work-order-list')}
        >
          <div className="flex items-center gap-2 mb-2">
            <Factory className="w-5 h-5 text-blue-500" />
            <p className="text-sm text-gray-500">작업중</p>
          </div>
          <p className="text-2xl font-bold text-blue-600">{inProgressOrders.length}건</p>
        </div>
        <div
          className="bg-white rounded-xl border p-5 cursor-pointer hover:border-green-300 transition-colors"
          onClick={() => onNavigate('work-order-list')}
        >
          <div className="flex items-center gap-2 mb-2">
            <CheckCircle className="w-5 h-5 text-green-500" />
            <p className="text-sm text-gray-500">작업완료</p>
          </div>
          <p className="text-2xl font-bold text-green-600">{completedOrders.length}건</p>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4">
        {/* 진행중 작업 */}
        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-medium text-gray-900">진행중 작업</h3>
            <button
              onClick={() => onNavigate('work-order-list')}
              className="text-sm text-blue-600 hover:text-blue-700"
            >
              전체보기 →
            </button>
          </div>
          <div className="space-y-2">
            {inProgressOrders.slice(0, 5).map((wo, i) => (
              <div
                key={i}
                className="flex justify-between items-center p-3 bg-gray-50 rounded-lg cursor-pointer hover:bg-gray-100"
                onClick={() => onNavigate('work-order-detail', wo)}
              >
                <div>
                  <p className="font-mono text-sm text-blue-600">{wo.workOrderNo}</p>
                  <p className="text-sm text-gray-600">{wo.customerName}</p>
                </div>
                <div className="text-right">
                  <div className="flex items-center gap-2">
                    <div className="w-16 bg-gray-200 rounded-full h-2">
                      <div
                        className="bg-blue-500 h-2 rounded-full"
                        style={{ width: `${wo.totalQty > 0 ? (wo.completedQty / wo.totalQty) * 100 : 0}%` }}
                      />
                    </div>
                    <span className="text-xs text-gray-500">{wo.completedQty}/{wo.totalQty}</span>
                  </div>
                  <p className="text-xs text-gray-400">{wo.currentStep}</p>
                </div>
              </div>
            ))}
            {inProgressOrders.length === 0 && (
              <p className="text-center text-gray-400 py-4">진행중인 작업이 없습니다</p>
            )}
          </div>
        </div>

        {/* 납기 임박 */}
        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-medium text-gray-900">납기 임박 (D-3)</h3>
          </div>
          <div className="space-y-2">
            {urgentOrders.slice(0, 5).map((wo, i) => {
              const dueDate = new Date(wo.dueDate);
              const diffDays = Math.ceil((dueDate - today) / (1000 * 60 * 60 * 24));
              return (
                <div
                  key={i}
                  className="flex justify-between items-center p-3 bg-red-50 rounded-lg cursor-pointer hover:bg-red-100"
                  onClick={() => onNavigate('work-order-detail', wo)}
                >
                  <div>
                    <p className="font-mono text-sm text-blue-600">{wo.workOrderNo}</p>
                    <p className="text-sm text-gray-600">{wo.customerName}</p>
                  </div>
                  <span className={`px-3 py-1 rounded text-sm font-bold ${diffDays <= 1 ? 'bg-red-500 text-white' : 'bg-red-100 text-red-700'
                    }`}>
                    D-{diffDays}
                  </span>
                </div>
              );
            })}
            {urgentOrders.length === 0 && (
              <p className="text-center text-gray-400 py-4">납기 임박 작업이 없습니다</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

// 구매팀 대시보드
const PurchaseDashboard = ({ materials = [], purchaseOrders = [], onCreatePO, onNavigate }) => {
  // 재고 부족 자재 (안전재고 이하)
  const lowStockMaterials = materials.filter(m => m.stock <= m.minStock);

  // 발주 현황
  const pendingPOs = purchaseOrders.filter(po => po.status === '발주대기' || po.status === '승인대기');
  const orderedPOs = purchaseOrders.filter(po => po.status === '발주완료');
  const inTransitPOs = purchaseOrders.filter(po => po.status === '배송중');

  // 입고 예정 (더미 데이터)
  const upcomingDeliveries = [
    { date: '2025-03-05', vendor: '철강공업', item: '갈바코일 0.5T', qty: '10톤', status: '배송중' },
    { date: '2025-03-06', vendor: '모터공급사', item: '튜블러모터', qty: '50EA', status: '발주완료' },
    { date: '2025-03-08', vendor: '알루미늄', item: '알루미늄 프레임', qty: '200EA', status: '발주완료' },
  ];

  return (
    <div className="space-y-4">
      <div className="space-y-3">
        <div>
          <h2 className="text-xl font-bold text-gray-900">구매 대시보드</h2>
          <p className="text-sm text-gray-500">구매팀 전용 대시보드</p>
        </div>
        <div className="flex justify-end gap-2">
          <button
            onClick={() => onNavigate('purchase-order-list')}
            className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 text-sm font-medium"
          >
            발주 목록 →
          </button>
          <button
            onClick={() => onNavigate('inventory-list')}
            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 text-sm font-medium flex items-center gap-2"
          >
            <Package className="w-4 h-4" /> 재고 현황
          </button>
        </div>
      </div>

      {/* 재고 부족 알림 - 가장 중요! */}
      {lowStockMaterials.length > 0 && (
        <div className="bg-red-50 border-2 border-red-300 rounded-xl p-5">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center">
                <AlertTriangle className="w-5 h-5 text-red-600" />
              </div>
              <div>
                <h3 className="font-bold text-red-800">재고 부족 알림</h3>
                <p className="text-sm text-red-600">{lowStockMaterials.length}개 품목이 안전재고 이하입니다</p>
              </div>
            </div>
            <button
              onClick={() => onNavigate('inventory-list')}
              className="text-sm text-red-600 hover:text-red-700 font-medium"
            >
              전체보기 →
            </button>
          </div>
          <div className="space-y-2">
            {lowStockMaterials.slice(0, 5).map((m, i) => (
              <div
                key={i}
                className="flex items-center justify-between p-3 bg-white rounded-lg border border-red-200"
              >
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <p className="font-mono text-sm text-blue-600">{m.materialCode}</p>
                    <span className={`px-2 py-0.5 rounded text-xs ${m.stock === 0 ? 'bg-red-500 text-white' : 'bg-yellow-100 text-yellow-700'
                      }`}>
                      {m.stock === 0 ? '재고없음' : '부족'}
                    </span>
                  </div>
                  <p className="text-sm text-gray-600">{m.materialName}</p>
                  <p className="text-xs text-gray-400">
                    현재: {m.stock}{m.unit} / 안전재고: {m.minStock}{m.unit}
                  </p>
                </div>
                <button
                  onClick={() => onCreatePO && onCreatePO(m)}
                  className="px-4 py-1.5 bg-blue-500 text-white text-sm rounded hover:bg-blue-600 font-medium"
                >
                  발주요청
                </button>
              </div>
            ))}
            {lowStockMaterials.length > 5 && (
              <button
                onClick={() => onNavigate('inventory-list')}
                className="w-full py-2 text-center text-red-600 hover:bg-red-100 rounded-lg text-sm"
              >
                +{lowStockMaterials.length - 5}건 더보기
              </button>
            )}
          </div>
        </div>
      )}

      {/* 재고 부족 없을 때 */}
      {lowStockMaterials.length === 0 && (
        <div className="bg-green-50 border border-green-200 rounded-xl p-5">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
              <CheckCircle className="w-5 h-5 text-green-600" />
            </div>
            <div>
              <h3 className="font-medium text-green-800">재고 상태 양호</h3>
              <p className="text-sm text-green-600">모든 자재가 안전재고 이상입니다.</p>
            </div>
          </div>
        </div>
      )}

      {/* 핵심 지표 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div
          className="bg-white rounded-xl border p-5 cursor-pointer hover:border-red-300 transition-colors"
          onClick={() => onNavigate('inventory-list')}
        >
          <div className="flex items-center gap-2 mb-2">
            <AlertTriangle className="w-5 h-5 text-red-500" />
            <p className="text-sm text-gray-500">재고부족</p>
          </div>
          <p className="text-2xl font-bold text-red-600">{lowStockMaterials.length}건</p>
        </div>
        <div
          className="bg-white rounded-xl border p-5 cursor-pointer hover:border-yellow-300 transition-colors"
          onClick={() => onNavigate('purchase-order-list')}
        >
          <div className="flex items-center gap-2 mb-2">
            <Clock className="w-5 h-5 text-yellow-500" />
            <p className="text-sm text-gray-500">발주대기</p>
          </div>
          <p className="text-2xl font-bold text-yellow-600">{pendingPOs.length}건</p>
        </div>
        <div
          className="bg-white rounded-xl border p-5 cursor-pointer hover:border-blue-300 transition-colors"
          onClick={() => onNavigate('purchase-order-list')}
        >
          <div className="flex items-center gap-2 mb-2">
            <Truck className="w-5 h-5 text-blue-500" />
            <p className="text-sm text-gray-500">배송중</p>
          </div>
          <p className="text-2xl font-bold text-blue-600">{inTransitPOs.length}건</p>
        </div>
        <div
          className="bg-white rounded-xl border p-5 cursor-pointer hover:border-green-300 transition-colors"
          onClick={() => onNavigate('inventory-list')}
        >
          <div className="flex items-center gap-2 mb-2">
            <Package className="w-5 h-5 text-green-500" />
            <p className="text-sm text-gray-500">총 품목</p>
          </div>
          <p className="text-2xl font-bold text-green-600">{materials.length}개</p>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4">
        {/* 입고 예정 */}
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-medium text-gray-900 mb-3">입고 예정</h3>
          <div className="space-y-2">
            {upcomingDeliveries.map((d, i) => (
              <div key={i} className="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                <div>
                  <p className="text-sm font-medium">{d.item}</p>
                  <p className="text-xs text-gray-500">{d.vendor} | {d.qty}</p>
                </div>
                <div className="text-right">
                  <p className="text-sm font-medium">{d.date}</p>
                  <span className={`text-xs px-2 py-0.5 rounded ${d.status === '배송중' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'
                    }`}>
                    {d.status}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 최근 발주 */}
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-medium text-gray-900 mb-3">최근 발주</h3>
          {purchaseOrders.length === 0 ? (
            <div className="text-center py-6 text-gray-400">
              <Package className="w-12 h-12 mx-auto mb-2 opacity-50" />
              <p>발주 내역이 없습니다</p>
            </div>
          ) : (
            <div className="space-y-2">
              {purchaseOrders.slice(0, 5).map((po, i) => (
                <div key={i} className="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                  <div>
                    <p className="font-mono text-sm text-blue-600">{po.poNo}</p>
                    <p className="text-sm text-gray-600">{po.vendor}</p>
                  </div>
                  <span className={`px-2 py-0.5 rounded text-xs ${po.status === '입고완료' ? 'bg-green-100 text-green-700' :
                      po.status === '배송중' ? 'bg-blue-100 text-blue-700' :
                        po.status === '발주완료' ? 'bg-purple-100 text-purple-700' :
                          'bg-yellow-100 text-yellow-700'
                    }`}>
                    {po.status}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* 자재 카테고리별 현황 */}
      <div className="bg-white rounded-xl border p-5">
        <h3 className="font-medium text-gray-900 mb-3">자재 카테고리별 현황</h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {['원자재', '절곡부품', '구매부품', '조립품'].map((cat, i) => {
            const catMaterials = materials.filter(m => m.itemType === cat);
            const lowStock = catMaterials.filter(m => m.stock <= m.minStock).length;
            return (
              <div key={i} className="bg-gray-50 rounded-lg p-3 text-center">
                <p className="text-sm text-gray-600">{cat}</p>
                <p className="text-xl font-bold">{catMaterials.length}개</p>
                {lowStock > 0 && (
                  <p className="text-xs text-red-500">부족: {lowStock}개</p>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

// 품질관리 대시보드
const QualityDashboard = ({ workOrders = [], onNavigate }) => {
  // 검사 대기 목록 (작업완료 상태)
  const pendingInspection = workOrders.filter(wo =>
    wo.status === '작업완료' && wo.inspectionStatus !== '검사완료'
  );

  // 중간검사 대기 (작업중)
  const processInspection = workOrders.filter(wo =>
    wo.status === '작업중'
  );

  const data = {
    incomingInspection: 3,
    processInspection: processInspection.length,
    finalInspection: pendingInspection.length,
    monthlyDefectRate: 0.5,
    pendingInspections: [
      ...pendingInspection.slice(0, 2).map(wo => ({
        lot: wo.workOrderNo,
        type: '제품검사',
        item: wo.productName,
      })),
      { lot: 'L-251205-001', type: '수입검사', item: '알루미늄 프레임' },
    ],
    defectTypes: [
      { type: '치수불량', rate: 40 },
      { type: '외관불량', rate: 30 },
      { type: '기능불량', rate: 20 },
      { type: '기타', rate: 10 },
    ],
  };

  return (
    <div className="space-y-4">
      <div>
        <h2 className="text-xl font-bold text-gray-900">품질 대시보드</h2>
        <p className="text-sm text-gray-500">품질관리팀 전용 대시보드</p>
      </div>

      {/* 핵심 지표 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border p-5">
          <p className="text-sm text-gray-500">수입검사 대기</p>
          <p className="text-2xl font-bold mt-1">{data.incomingInspection}건</p>
        </div>
        <div className="bg-white rounded-xl border p-5">
          <p className="text-sm text-gray-500">중간검사 대기</p>
          <p className="text-2xl font-bold mt-1">{data.processInspection}건</p>
        </div>
        <div className="bg-white rounded-xl border p-5">
          <p className="text-sm text-gray-500">제품검사 대기</p>
          <p className="text-2xl font-bold mt-1">{data.finalInspection}건</p>
        </div>
        <div className="bg-white rounded-xl border p-5">
          <p className="text-sm text-gray-500">월간 불량률</p>
          <p className="text-2xl font-bold text-green-600 mt-1">{data.monthlyDefectRate}%</p>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        {/* 검사 대기 목록 */}
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-medium text-gray-900 mb-3">🔍 검사 대기 목록</h3>
          <div className="space-y-2">
            {data.pendingInspections.map((p, i) => (
              <div key={i} className="flex justify-between items-center p-2 bg-gray-50 rounded">
                <div>
                  <p className="font-mono text-sm">{p.lot}</p>
                  <p className="text-sm text-gray-600">{p.item}</p>
                </div>
                <span className={`px-2 py-1 rounded text-xs ${p.type === '수입검사' ? 'bg-blue-100 text-blue-700' :
                    p.type === '중간검사' ? 'bg-yellow-100 text-yellow-700' :
                      'bg-green-100 text-green-700'
                  }`}>
                  {p.type}
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* 불량 유형별 현황 */}
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-medium text-gray-900 mb-3">📈 불량 유형별 현황</h3>
          <div className="space-y-2">
            {data.defectTypes.map((d, i) => (
              <div key={i} className="flex items-center gap-2">
                <span className="w-20 text-sm">{d.type}</span>
                <div className="flex-1 bg-gray-200 rounded-full h-4">
                  <div
                    className="bg-red-400 h-4 rounded-full"
                    style={{ width: `${d.rate}%` }}
                  />
                </div>
                <span className="text-sm font-medium w-10">{d.rate}%</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// 회계팀 대시보드
const AccountingDashboard = ({ orders = [], shipments = [], onApproveShipment, onRejectShipment, onNavigate }) => {
  // C등급 출하 승인대기 목록
  const pendingCGradeShipments = orders.filter(o =>
    o.creditGrade === 'C' &&
    o.productionStatus === '완료' &&
    o.accountingStatus !== '회계확인완료'
  );

  // 통계 데이터
  const monthlySales = orders.reduce((sum, o) => sum + (o.totalAmount || 0), 0);
  const cGradeOrders = orders.filter(o => o.creditGrade === 'C');
  const cGradeTotal = cGradeOrders.reduce((sum, o) => sum + (o.totalAmount || 0), 0);

  // 수금/지급 예정 (더미 데이터)
  const collectSchedule = [
    { date: '12/10', customer: '삼성전자', amount: 2400 },
    { date: '12/15', customer: 'LG전자', amount: 1800 },
  ];
  const paymentSchedule = [
    { date: '12/15', vendor: '철강공업', amount: 800 },
    { date: '12/20', vendor: '모터공급사', amount: 500 },
  ];

  // 출하 승인
  const handleApprove = (order) => {
    if (onApproveShipment) {
      onApproveShipment(order.id);
    }
  };

  // 출하 반려
  const handleReject = (order) => {
    const reason = prompt('반려 사유를 입력하세요:');
    if (reason && onRejectShipment) {
      onRejectShipment(order.id, reason);
    }
  };

  return (
    <div className="space-y-4">
      <div className="space-y-3">
        <div>
          <h2 className="text-xl font-bold text-gray-900">회계 대시보드</h2>
          <p className="text-sm text-gray-500">회계팀 전용 대시보드</p>
        </div>
        <div className="flex justify-end">
          <button
            onClick={() => onNavigate('order-list')}
            className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 text-sm font-medium"
          >
            수주 목록 →
          </button>
        </div>
      </div>

      {/* 핵심 지표 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center gap-2 mb-2">
            <DollarSign className="w-5 h-5 text-blue-500" />
            <p className="text-sm text-gray-500">이번달 매출</p>
          </div>
          <p className="text-2xl font-bold">{(monthlySales / 100000000).toFixed(1)}억</p>
        </div>
        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center gap-2 mb-2">
            <AlertTriangle className="w-5 h-5 text-red-500" />
            <p className="text-sm text-gray-500">C등급 매출</p>
          </div>
          <p className="text-2xl font-bold text-red-600">{(cGradeTotal / 10000).toLocaleString()}만원</p>
          <p className="text-xs text-gray-400">{cGradeOrders.length}건</p>
        </div>
        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center gap-2 mb-2">
            <TrendingUp className="w-5 h-5 text-green-500" />
            <p className="text-sm text-gray-500">수금 예정</p>
          </div>
          <p className="text-2xl font-bold text-green-600">{collectSchedule.reduce((s, c) => s + c.amount, 0).toLocaleString()}만원</p>
        </div>
        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center gap-2 mb-2">
            <TrendingDown className="w-5 h-5 text-orange-500" />
            <p className="text-sm text-gray-500">지급 예정</p>
          </div>
          <p className="text-2xl font-bold text-orange-600">{paymentSchedule.reduce((s, p) => s + p.amount, 0).toLocaleString()}만원</p>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4">
        {/* 수금 예정 */}
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-medium text-gray-900 mb-3 flex items-center gap-2">
            <ArrowDownCircle className="w-4 h-4 text-green-500" /> 수금 예정
          </h3>
          <div className="space-y-2">
            {collectSchedule.map((c, i) => (
              <div key={i} className="flex justify-between items-center p-3 bg-green-50 rounded-lg">
                <span className="text-sm font-medium">{c.date}</span>
                <span className="text-sm text-gray-600">{c.customer}</span>
                <span className="font-bold text-green-600">{c.amount.toLocaleString()}만원</span>
              </div>
            ))}
          </div>
        </div>

        {/* 지급 예정 */}
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-medium text-gray-900 mb-3">지급 예정</h3>
          <div className="space-y-2">
            {paymentSchedule.map((p, i) => (
              <div key={i} className="flex justify-between items-center p-3 bg-orange-50 rounded-lg">
                <span className="text-sm font-medium">{p.date}</span>
                <span className="text-sm text-gray-600">{p.vendor}</span>
                <span className="font-bold text-orange-600">{p.amount.toLocaleString()}만원</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* C등급 고객 현황 */}
      <div className="bg-white rounded-xl border p-5">
        <h3 className="font-medium text-gray-900 mb-3">C등급 고객 수주 현황</h3>
        {cGradeOrders.length === 0 ? (
          <p className="text-center text-gray-400 py-4">C등급 수주가 없습니다</p>
        ) : (
          <div className="space-y-2">
            {cGradeOrders.slice(0, 5).map((order, i) => (
              <div
                key={i}
                className="flex justify-between items-center p-3 bg-gray-50 rounded-lg cursor-pointer hover:bg-gray-100"
                onClick={() => onNavigate('order-detail', order)}
              >
                <div>
                  <p className="font-mono text-sm text-blue-600">{order.orderNo}</p>
                  <p className="text-sm text-gray-600">{order.customerName}</p>
                </div>
                <div className="text-right">
                  <p className="font-bold">{(order.totalAmount / 10000).toLocaleString()}만원</p>
                  <span className={`text-xs px-2 py-0.5 rounded ${order.accountingStatus === '회계확인완료' ? 'bg-green-100 text-green-700' :
                      order.productionStatus === '완료' ? 'bg-yellow-100 text-yellow-700' :
                        'bg-gray-100 text-gray-600'
                    }`}>
                    {order.accountingStatus === '회계확인완료' ? '승인완료' :
                      order.productionStatus === '완료' ? '승인대기' : '생산중'}
                  </span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

// 생산담당자 대시보드 (모바일 최적화)
const WorkerDashboard = ({ workOrders = [], currentUser, onStartWork, onInputWorkLog, onCompleteWork, onNavigate }) => {
  const [showWorkLogModal, setShowWorkLogModal] = useState(false);
  const [selectedWork, setSelectedWork] = useState(null);
  const [workLog, setWorkLog] = useState({
    completedQty: 0,
    defectQty: 0,
    note: '',
  });

  // 승인완료된 작업 중 본인에게 배정되었거나 아직 미배정인 작업
  // (생산담당자는 미배정 작업도 볼 수 있어야 함 - 본인이 시작할 수 있도록)
  const myWorks = workOrders.filter(wo =>
    wo.approvalStatus === '승인완료' && (
      wo.worker === currentUser?.name ||
      wo.assignee === currentUser?.name ||
      (!wo.worker && !wo.assignee) || // 미배정 작업
      wo.assignee === '김생산' // 기존 샘플 데이터 호환
    )
  );

  // 작업중인 것
  const inProgressWorks = myWorks.filter(wo => wo.status === '작업중');
  // 작업대기
  const waitingWorks = myWorks.filter(wo => wo.status === '작업대기');
  // 오늘 완료
  const today = new Date().toISOString().split('T')[0];
  const todayCompleted = myWorks.filter(wo =>
    wo.status === '작업완료' && wo.completedDate === today
  );

  // 작업 시작
  const handleStartWork = (wo) => {
    if (onStartWork) {
      onStartWork(wo.id);
    }
  };

  // 작업일지 모달 열기
  const handleOpenWorkLog = (wo) => {
    setSelectedWork(wo);
    setWorkLog({
      completedQty: wo.completedQty || 0,
      defectQty: wo.defectQty || 0,
      note: wo.workNote || '',
    });
    setShowWorkLogModal(true);
  };

  // 작업일지 저장
  const handleSaveWorkLog = () => {
    if (onInputWorkLog && selectedWork) {
      onInputWorkLog(selectedWork.id, workLog);
    }
    setShowWorkLogModal(false);
    setSelectedWork(null);
  };

  // 작업 완료
  const handleCompleteWork = (wo) => {
    if (onCompleteWork) {
      onCompleteWork(wo.id);
    }
  };

  // 총 실적 계산
  const totalCompleted = myWorks.reduce((sum, wo) => sum + (wo.completedQty || 0), 0);
  const totalDefects = myWorks.reduce((sum, wo) => sum + (wo.defectQty || 0), 0);

  return (
    <div className="space-y-4 max-w-lg mx-auto">
      {/* 상단 헤더 */}
      <div className="bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-xl p-4">
        <div className="flex items-center gap-3">
          <div className="w-12 h-12 bg-white/20 rounded-full flex items-center justify-center">
            <User className="w-6 h-6" />
          </div>
          <div>
            <p className="text-lg font-bold">👷 {currentUser?.name || '김생산'} 님</p>
            <p className="text-sm opacity-80">생산담당자 | {new Date().toLocaleDateString('ko-KR')}</p>
          </div>
        </div>
      </div>

      {/* 오늘 내 실적 요약 */}
      <div className="bg-white rounded-xl border p-4">
        <h3 className="font-medium text-gray-900 mb-3 flex items-center gap-2">
          <BarChart3 className="w-4 h-4" /> 오늘 내 실적
        </h3>
        <div className="grid grid-cols-4 gap-2">
          <div className="bg-yellow-50 rounded-lg p-3 text-center">
            <p className="text-xs text-gray-500">대기</p>
            <p className="text-xl font-bold text-yellow-600">{waitingWorks.length}</p>
          </div>
          <div className="bg-blue-50 rounded-lg p-3 text-center">
            <p className="text-xs text-gray-500">진행중</p>
            <p className="text-xl font-bold text-blue-600">{inProgressWorks.length}</p>
          </div>
          <div className="bg-green-50 rounded-lg p-3 text-center">
            <p className="text-xs text-gray-500">완료</p>
            <p className="text-xl font-bold text-green-600">{totalCompleted}</p>
          </div>
          <div className="bg-red-50 rounded-lg p-3 text-center">
            <p className="text-xs text-gray-500">불량</p>
            <p className="text-xl font-bold text-red-600">{totalDefects}</p>
          </div>
        </div>
      </div>

      {/* 진행중인 작업 (최우선) */}
      {inProgressWorks.length > 0 && (
        <div className="bg-blue-50 border-2 border-blue-300 rounded-xl p-4">
          <h3 className="font-medium text-blue-800 mb-3">진행중인 작업</h3>
          <div className="space-y-3">
            {inProgressWorks.map((wo, i) => (
              <div key={i} className="bg-white rounded-lg p-4 border-2 border-blue-400">
                <div className="flex justify-between items-start mb-2">
                  <div>
                    <p className="font-mono text-sm text-blue-600">{wo.workOrderNo}</p>
                    <p className="font-bold text-lg">{wo.productName}</p>
                    <p className="text-sm text-gray-600">{wo.customerName} | {wo.siteName}</p>
                  </div>
                  <span className="px-3 py-1 bg-blue-500 text-white rounded-full text-xs font-medium animate-pulse">
                    ▶ 작업중
                  </span>
                </div>
                {/* 품목 정보 영역 */}
                <div className="mb-3 p-2 bg-blue-50 rounded-lg border border-blue-200">
                  <div className="grid grid-cols-2 gap-2 text-xs">
                    <div className="flex items-center gap-1">
                      <span className="text-gray-500">품목코드:</span>
                      <span className="font-mono font-medium">{wo.itemCode || wo.productCode || '-'}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <span className="text-gray-500">규격:</span>
                      <span className="font-medium">{wo.width && wo.height ? `${wo.width}×${wo.height}` : wo.spec || '-'}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <span className="text-gray-500">LOT번호:</span>
                      <span className="font-mono font-medium text-orange-600">{wo.lotNo || wo.productionLotNo || '-'}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <span className="text-gray-500">납기일:</span>
                      <span className="font-medium text-red-600">{wo.dueDate || '-'}</span>
                    </div>
                  </div>
                </div>
                <div className="grid grid-cols-3 gap-2 mb-3 text-center bg-gray-50 rounded-lg p-2">
                  <div>
                    <p className="text-xs text-gray-500">목표</p>
                    <p className="font-bold">{wo.totalQty}개소</p>
                  </div>
                  <div>
                    <p className="text-xs text-gray-500">완료</p>
                    <p className="font-bold text-green-600">{wo.completedQty || 0}개소</p>
                  </div>
                  <div>
                    <p className="text-xs text-gray-500">불량</p>
                    <p className="font-bold text-red-600">{wo.defectQty || 0}개소</p>
                  </div>
                </div>
                <div className="flex gap-2">
                  <button
                    onClick={() => handleOpenWorkLog(wo)}
                    className="flex-1 py-2.5 bg-blue-600 text-white rounded-lg text-sm font-medium flex items-center justify-center gap-2"
                  >
                    <Edit3 className="w-4 h-4" /> 작업일지
                  </button>
                  <button
                    onClick={() => handleCompleteWork(wo)}
                    className="flex-1 py-2.5 bg-green-600 text-white rounded-lg text-sm font-medium flex items-center justify-center gap-2"
                  >
                    <CheckCircle className="w-4 h-4" /> 작업 완료
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 대기중인 작업 */}
      <div className="bg-white rounded-xl border p-4">
        <h3 className="font-medium text-gray-900 mb-3">대기중인 작업 ({waitingWorks.length}건)</h3>
        {waitingWorks.length === 0 ? (
          <div className="text-center py-6 text-gray-400">
            <CheckCircle className="w-12 h-12 mx-auto mb-2 opacity-50" />
            <p>대기중인 작업이 없습니다</p>
          </div>
        ) : (
          <div className="space-y-3">
            {waitingWorks.map((wo, i) => (
              <div key={i} className="p-3 rounded-lg border-2 border-gray-200 hover:border-blue-300 transition-colors">
                <div className="flex justify-between items-start mb-2">
                  <div>
                    <p className="font-mono text-sm text-gray-500">{wo.workOrderNo}</p>
                    <p className="font-medium">{wo.productName}</p>
                    <p className="text-xs text-gray-500">{wo.customerName} | {wo.siteName}</p>
                  </div>
                  <span className="px-2 py-1 bg-yellow-100 text-yellow-700 rounded text-xs">
                    ○ 대기
                  </span>
                </div>
                {/* 품목 정보 영역 */}
                <div className="mb-2 p-2 bg-gray-50 rounded-lg text-xs">
                  <div className="grid grid-cols-2 gap-1">
                    <div className="flex items-center gap-1">
                      <span className="text-gray-400">품목:</span>
                      <span className="font-mono">{wo.itemCode || wo.productCode || '-'}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <span className="text-gray-400">규격:</span>
                      <span>{wo.width && wo.height ? `${wo.width}×${wo.height}` : wo.spec || '-'}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <span className="text-gray-400">수량:</span>
                      <span className="font-medium">{wo.totalQty}개소</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <span className="text-gray-400">납기:</span>
                      <span className="text-red-600 font-medium">{wo.dueDate || '-'}</span>
                    </div>
                  </div>
                </div>
                <button
                  onClick={() => handleStartWork(wo)}
                  className="w-full py-2 bg-blue-500 text-white rounded-lg text-sm font-medium flex items-center justify-center gap-2 hover:bg-blue-600"
                >
                  <PlayCircle className="w-4 h-4" /> 작업 시작
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 오늘 완료한 작업 */}
      {todayCompleted.length > 0 && (
        <div className="bg-green-50 rounded-xl border border-green-200 p-4">
          <h3 className="font-medium text-green-800 mb-3">오늘 완료 ({todayCompleted.length}건)</h3>
          <div className="space-y-2">
            {todayCompleted.map((wo, i) => (
              <div key={i} className="p-3 bg-white rounded-lg">
                <div className="flex justify-between items-start mb-2">
                  <div>
                    <p className="font-mono text-sm text-gray-500">{wo.workOrderNo}</p>
                    <p className="text-sm font-medium">{wo.productName}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-bold text-green-600">{wo.completedQty || wo.totalQty}개소</p>
                    <p className="text-xs text-gray-400">불량: {wo.defectQty || 0}</p>
                  </div>
                </div>
                {/* 품목 정보 */}
                <div className="flex gap-3 text-xs text-gray-500">
                  <span>품목: <span className="font-mono">{wo.itemCode || wo.productCode || '-'}</span></span>
                  <span>규격: {wo.width && wo.height ? `${wo.width}×${wo.height}` : wo.spec || '-'}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 작업일지 입력 모달 - WL-SCR 문서양식관리 양식 적용 */}
      {showWorkLogModal && selectedWork && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 overflow-y-auto">
          <div className="bg-white rounded-xl w-full max-w-4xl my-4">
            {/* ========== 헤더 영역: 로고 + 제목 + 결재란 ========== */}
            <div className="border-b-2 border-black">
              <div className="flex items-start justify-between p-4">
                {/* 좌측: 로고 + 제목 */}
                <div className="flex items-center gap-4">
                  <div className="text-xl font-bold text-blue-800 border-2 border-blue-800 px-3 py-1">
                    KD경동기업
                  </div>
                  <div className="text-center">
                    <h2 className="text-2xl font-bold tracking-widest">작 업 일 지</h2>
                    <div className="inline-block mt-1 px-3 py-0.5 text-sm font-bold" style={{ backgroundColor: '#FFFF00' }}>
                      스크린 생산부서
                    </div>
                  </div>
                </div>

                {/* 우측: 결재란 + 닫기 버튼 */}
                <div className="flex items-start gap-3">
                  {/* 결재란 테이블 */}
                  <table className="border-collapse text-xs">
                    <thead>
                      <tr>
                        <td className="border border-black px-3 py-1 bg-gray-200 font-bold text-center">작성</td>
                        <td className="border border-black px-3 py-1 bg-gray-200 font-bold text-center">검토</td>
                        <td className="border border-black px-3 py-1 bg-gray-200 font-bold text-center">승인</td>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td className="border border-black w-14 h-10 text-center">결</td>
                        <td className="border border-black w-14 h-10 text-center">재</td>
                        <td className="border border-black w-14 h-10 text-center">란</td>
                      </tr>
                      <tr>
                        <td className="border border-black px-1 py-0.5 text-center text-xs">판매/전진</td>
                        <td className="border border-black px-1 py-0.5 text-center text-xs">생산</td>
                        <td className="border border-black px-1 py-0.5 text-center text-xs" style={{ backgroundColor: '#00FFFF' }}>품질</td>
                      </tr>
                    </tbody>
                  </table>
                  <button
                    onClick={() => setShowWorkLogModal(false)}
                    className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold"
                  >
                    ✕
                  </button>
                </div>
              </div>
            </div>

            {/* ========== 신청업체/신청내용 정보 (WL-HEADER-INFO 블록) ========== */}
            <div className="p-4 border-b">
              <div className="grid grid-cols-2 gap-4">
                {/* 좌측: 신청업체 정보 */}
                <div className="border border-black">
                  <div className="bg-gray-800 text-white text-center py-1 text-sm font-bold">
                    신 청 업 체
                  </div>
                  <table className="w-full text-sm border-collapse">
                    <tbody>
                      <tr>
                        <td className="border border-gray-400 px-2 py-1.5 bg-gray-100 font-medium w-24">발주처</td>
                        <td className="border border-gray-400 px-2 py-1.5">{selectedWork.customerName || '-'}</td>
                      </tr>
                      <tr>
                        <td className="border border-gray-400 px-2 py-1.5 bg-gray-100 font-medium">현장명</td>
                        <td className="border border-gray-400 px-2 py-1.5">{selectedWork.siteName || '-'}</td>
                      </tr>
                      <tr>
                        <td className="border border-gray-400 px-2 py-1.5 bg-gray-100 font-medium">제품명</td>
                        <td className="border border-gray-400 px-2 py-1.5">{selectedWork.productName || '-'}</td>
                      </tr>
                      <tr>
                        <td className="border border-gray-400 px-2 py-1.5 bg-gray-100 font-medium">규격(W×H)</td>
                        <td className="border border-gray-400 px-2 py-1.5">{selectedWork.width || '-'} × {selectedWork.height || '-'}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>

                {/* 우측: 신청내용 정보 */}
                <div className="border border-black">
                  <div className="bg-gray-800 text-white text-center py-1 text-sm font-bold">
                    신 청 내 용
                  </div>
                  <table className="w-full text-sm border-collapse">
                    <tbody>
                      <tr>
                        <td className="border border-gray-400 px-2 py-1.5 bg-gray-100 font-medium w-28">작업지시번호</td>
                        <td className="border border-gray-400 px-2 py-1.5 font-mono text-blue-600">{selectedWork.workOrderNo || '-'}</td>
                      </tr>
                      <tr>
                        <td className="border border-gray-400 px-2 py-1.5 bg-gray-100 font-medium">LOT번호</td>
                        <td className="border border-gray-400 px-2 py-1.5 font-mono">{selectedWork.lotNo || selectedWork.productionLotNo || '-'}</td>
                      </tr>
                      <tr>
                        <td className="border border-gray-400 px-2 py-1.5 bg-gray-100 font-medium">납기일</td>
                        <td className="border border-gray-400 px-2 py-1.5">{selectedWork.dueDate || '-'}</td>
                      </tr>
                      <tr>
                        <td className="border border-gray-400 px-2 py-1.5 bg-gray-100 font-medium">생산담당자</td>
                        <td className="border border-gray-400 px-2 py-1.5">{currentUser?.name || '김생산'}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            {/* ========== 작업내역 테이블 (TBL-WORKLOG-SCREEN 블록) ========== */}
            <div className="p-4">
              <h3 className="font-bold text-sm mb-2 border-b-2 border-black pb-1">■ 작업 내역</h3>
              <div className="overflow-x-auto">
                <table className="w-full text-xs border-collapse">
                  <thead>
                    <tr>
                      <th rowSpan={2} className="border border-gray-400 px-2 py-1 bg-gray-200 w-10">일련<br />번호</th>
                      <th rowSpan={2} className="border border-gray-400 px-2 py-1 bg-gray-200 w-24">입고 LOT NO.</th>
                      <th rowSpan={2} className="border border-gray-400 px-2 py-1 bg-gray-200 w-16">제품명</th>
                      <th rowSpan={2} className="border border-gray-400 px-2 py-1 bg-gray-200 w-16">부호</th>
                      <th colSpan={3} className="border border-gray-400 px-2 py-1 bg-gray-200">제작사이즈(mm)</th>
                      <th colSpan={5} className="border border-gray-400 px-2 py-1" style={{ backgroundColor: '#FFF2CC' }}>규격(매수)</th>
                    </tr>
                    <tr>
                      <th className="border border-gray-400 px-1 py-1 bg-gray-200 w-12">가로</th>
                      <th className="border border-gray-400 px-1 py-1 bg-gray-200 w-12">세로</th>
                      <th className="border border-gray-400 px-1 py-1 bg-gray-200 w-14">나머지<br />높이</th>
                      <th className="border border-gray-400 px-1 py-1 w-10" style={{ backgroundColor: '#FFF2CC' }}>1210</th>
                      <th className="border border-gray-400 px-1 py-1 w-10" style={{ backgroundColor: '#FFF2CC' }}>900</th>
                      <th className="border border-gray-400 px-1 py-1 w-10" style={{ backgroundColor: '#FFF2CC' }}>600</th>
                      <th className="border border-gray-400 px-1 py-1 w-10" style={{ backgroundColor: '#FFF2CC' }}>400</th>
                      <th className="border border-gray-400 px-1 py-1 w-10" style={{ backgroundColor: '#FFF2CC' }}>300</th>
                    </tr>
                  </thead>
                  <tbody>
                    {/* 작업내역 행 - 샘플 데이터 */}
                    <tr>
                      <td className="border border-gray-400 px-2 py-1.5 text-center">1</td>
                      <td className="border border-gray-400 px-2 py-1.5 text-center font-mono text-xs">
                        <input
                          type="text"
                          className="w-full text-center border-0 focus:ring-1 focus:ring-blue-500 text-xs"
                          defaultValue={selectedWork.incomingLotNo || ''}
                          placeholder="입고LOT"
                        />
                      </td>
                      <td className="border border-gray-400 px-2 py-1.5 text-center">{selectedWork.productName?.substring(0, 4) || '스크린'}</td>
                      <td className="border border-gray-400 px-2 py-1.5 text-center">{selectedWork.partCode || '-'}</td>
                      <td className="border border-gray-400 px-2 py-1.5 text-center" style={{ backgroundColor: '#FFFF00' }}>
                        <input
                          type="number"
                          className="w-full text-center border-0 focus:ring-1 focus:ring-blue-500 text-xs"
                          defaultValue={selectedWork.width || ''}
                          placeholder="가로"
                        />
                      </td>
                      <td className="border border-gray-400 px-2 py-1.5 text-center" style={{ backgroundColor: '#FFFF00' }}>
                        <input
                          type="number"
                          className="w-full text-center border-0 focus:ring-1 focus:ring-blue-500 text-xs"
                          defaultValue={selectedWork.height || ''}
                          placeholder="세로"
                        />
                      </td>
                      <td className="border border-gray-400 px-2 py-1.5 text-center" style={{ backgroundColor: '#FFCCCC' }}>
                        <input
                          type="number"
                          className="w-full text-center border-0 focus:ring-1 focus:ring-blue-500 text-xs"
                          placeholder="나머지"
                        />
                      </td>
                      <td className="border border-gray-400 px-1 py-1.5 text-center">
                        <input type="number" className="w-full text-center border-0 focus:ring-1 focus:ring-blue-500 text-xs" placeholder="-" />
                      </td>
                      <td className="border border-gray-400 px-1 py-1.5 text-center">
                        <input type="number" className="w-full text-center border-0 focus:ring-1 focus:ring-blue-500 text-xs" placeholder="-" />
                      </td>
                      <td className="border border-gray-400 px-1 py-1.5 text-center">
                        <input type="number" className="w-full text-center border-0 focus:ring-1 focus:ring-blue-500 text-xs" placeholder="-" />
                      </td>
                      <td className="border border-gray-400 px-1 py-1.5 text-center">
                        <input type="number" className="w-full text-center border-0 focus:ring-1 focus:ring-blue-500 text-xs" placeholder="-" />
                      </td>
                      <td className="border border-gray-400 px-1 py-1.5 text-center">
                        <input type="number" className="w-full text-center border-0 focus:ring-1 focus:ring-blue-500 text-xs" placeholder="-" />
                      </td>
                    </tr>
                    {/* 빈 행 추가 (최대 5행) */}
                    {[2, 3, 4, 5].map(num => (
                      <tr key={num}>
                        <td className="border border-gray-400 px-2 py-1.5 text-center text-gray-400">{num}</td>
                        <td className="border border-gray-400 px-2 py-1.5"><input type="text" className="w-full text-center border-0 text-xs" /></td>
                        <td className="border border-gray-400 px-2 py-1.5"><input type="text" className="w-full text-center border-0 text-xs" /></td>
                        <td className="border border-gray-400 px-2 py-1.5"><input type="text" className="w-full text-center border-0 text-xs" /></td>
                        <td className="border border-gray-400 px-2 py-1.5" style={{ backgroundColor: '#FFFF00' }}><input type="number" className="w-full text-center border-0 text-xs" /></td>
                        <td className="border border-gray-400 px-2 py-1.5" style={{ backgroundColor: '#FFFF00' }}><input type="number" className="w-full text-center border-0 text-xs" /></td>
                        <td className="border border-gray-400 px-2 py-1.5" style={{ backgroundColor: '#FFCCCC' }}><input type="number" className="w-full text-center border-0 text-xs" /></td>
                        <td className="border border-gray-400 px-1 py-1.5"><input type="number" className="w-full text-center border-0 text-xs" /></td>
                        <td className="border border-gray-400 px-1 py-1.5"><input type="number" className="w-full text-center border-0 text-xs" /></td>
                        <td className="border border-gray-400 px-1 py-1.5"><input type="number" className="w-full text-center border-0 text-xs" /></td>
                        <td className="border border-gray-400 px-1 py-1.5"><input type="number" className="w-full text-center border-0 text-xs" /></td>
                        <td className="border border-gray-400 px-1 py-1.5"><input type="number" className="w-full text-center border-0 text-xs" /></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* ========== 하단 요약 및 버튼 ========== */}
            <div className="p-4 border-t bg-gray-50">
              <div className="grid grid-cols-4 gap-4 mb-4">
                <div className="bg-white rounded-lg p-3 text-center border">
                  <p className="text-xs text-gray-500">목표 수량</p>
                  <p className="text-xl font-bold">{selectedWork.totalQty || 0}개소</p>
                </div>
                <div className="bg-white rounded-lg p-3 text-center border">
                  <label className="text-xs text-gray-500">완료 수량</label>
                  <input
                    type="number"
                    value={workLog.completedQty}
                    onChange={(e) => setWorkLog({ ...workLog, completedQty: parseInt(e.target.value) || 0 })}
                    className="w-full text-xl font-bold text-center text-green-600 border-0 focus:ring-2 focus:ring-green-500 rounded"
                    min="0"
                  />
                </div>
                <div className="bg-white rounded-lg p-3 text-center border">
                  <label className="text-xs text-gray-500">불량 수량</label>
                  <input
                    type="number"
                    value={workLog.defectQty}
                    onChange={(e) => setWorkLog({ ...workLog, defectQty: parseInt(e.target.value) || 0 })}
                    className="w-full text-xl font-bold text-center text-red-600 border-0 focus:ring-2 focus:ring-red-500 rounded"
                    min="0"
                  />
                </div>
                <div className="bg-white rounded-lg p-3 text-center border">
                  <p className="text-xs text-gray-500">진행률</p>
                  <p className="text-xl font-bold text-blue-600">
                    {selectedWork.totalQty ? Math.round((workLog.completedQty / selectedWork.totalQty) * 100) : 0}%
                  </p>
                </div>
              </div>

              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">비고 (특이사항)</label>
                <textarea
                  value={workLog.note}
                  onChange={(e) => setWorkLog({ ...workLog, note: e.target.value })}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
                  rows={2}
                  placeholder="설비이상, 자재문제 등 특이사항 기록"
                />
              </div>

              <div className="flex gap-2 justify-end">
                <button
                  onClick={() => setShowWorkLogModal(false)}
                  className="px-6 py-2.5 border rounded-lg font-medium hover:bg-gray-100"
                >
                  취소
                </button>
                <button
                  onClick={() => window.print()}
                  className="px-6 py-2.5 border rounded-lg font-medium hover:bg-gray-100 flex items-center gap-2"
                >
                  <Printer className="w-4 h-4" /> 인쇄
                </button>
                <button
                  onClick={handleSaveWorkLog}
                  className="px-6 py-2.5 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 flex items-center gap-2"
                >
                  <Save className="w-4 h-4" /> 저장
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 탭 필터 (칩 스타일) - 검정/흰색 통일 스타일
// 선택: 검정 배경 + 흰색 텍스트, 미선택: 흰색 배경 + 회색 테두리 + 검정 텍스트
const TabFilter = ({ tabs, activeTab, onTabChange }) => (
  <div className="flex flex-wrap gap-2">
    {tabs.map(tab => (
      <button
        key={tab.id}
        onClick={() => onTabChange(tab.id)}
        className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-full border transition-colors
          ${activeTab === tab.id
            ? 'bg-gray-900 text-white border-gray-900'
            : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'}`}
      >
        <span>{tab.label}</span>
        {tab.count !== undefined && (
          <span className={activeTab === tab.id ? 'text-white' : 'text-gray-500'}>
            {tab.count}
          </span>
        )}
      </button>
    ))}
  </div>
);

// 검색 입력
const SearchInput = ({ placeholder, value, onChange }) => (
  <div className="relative bg-white rounded-xl border">
    <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
    <input
      type="text"
      placeholder={placeholder}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className="w-full pl-12 pr-4 py-3 bg-transparent rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
    />
  </div>
);

// 버튼
const Button = ({ variant = 'primary', size = 'md', children, onClick, disabled, className = '' }) => {
  const variants = {
    primary: 'bg-blue-500 text-white hover:bg-blue-600',
    secondary: 'bg-gray-100 text-gray-700 hover:bg-gray-200',
    success: 'bg-green-500 text-white hover:bg-green-600',
    danger: 'bg-red-500 text-white hover:bg-red-600',
    outline: 'border border-gray-300 text-gray-700 hover:bg-gray-50',
    ghost: 'text-gray-600 hover:bg-gray-100',
  };
  const sizes = {
    sm: 'px-3 py-1.5 text-sm',
    md: 'px-4 py-2 text-sm',
    lg: 'px-5 py-2.5 text-base',
  };
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      className={`inline-flex items-center gap-2 font-medium rounded-lg transition-colors 
        ${variants[variant]} ${sizes[size]} ${disabled ? 'opacity-50 cursor-not-allowed' : ''} ${className}`}
    >
      {children}
    </button>
  );
};

// 카드 섹션
// ============ 반응형 유틸리티 ============

// 화면 크기 감지 훅
const useResponsive = () => {
  const [screenSize, setScreenSize] = useState('desktop');

  useEffect(() => {
    const checkSize = () => {
      const width = window.innerWidth;
      if (width < 768) {
        setScreenSize('mobile');
      } else if (width < 1024) {
        setScreenSize('tablet');
      } else {
        setScreenSize('desktop');
      }
    };

    checkSize();
    window.addEventListener('resize', checkSize);
    return () => window.removeEventListener('resize', checkSize);
  }, []);

  return {
    screenSize,
    isMobile: screenSize === 'mobile',
    isTablet: screenSize === 'tablet',
    isDesktop: screenSize === 'desktop',
    isMobileOrTablet: screenSize === 'mobile' || screenSize === 'tablet',
  };
};

// 목록 선택 공통 훅 (CLAUDE.md 12번 규칙)
const useListSelection = (data = []) => {
  const [selectedIds, setSelectedIds] = useState([]);

  useEffect(() => {
    setSelectedIds(prev => prev.filter(id => data.some(item => item.id === id)));
  }, [data]);

  const handleSelect = (id) => {
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
    );
  };

  const handleSelectAll = (e) => {
    setSelectedIds(e.target.checked ? data.map(item => item.id) : []);
  };

  const clearSelection = () => setSelectedIds([]);

  return {
    selectedIds,
    setSelectedIds,
    handleSelect,
    handleSelectAll,
    clearSelection,
    isAllSelected: data.length > 0 && selectedIds.length === data.length,
    hasSelection: selectedIds.length > 0,
    isMultiSelect: selectedIds.length > 1,
    isSelected: (id) => selectedIds.includes(id),
  };
};

// 모바일 헤더 컴포넌트
const MobileHeader = ({ onMenuToggle, onBack, showBack = false, title = '' }) => {
  return (
    <header className="sticky top-0 z-40 bg-white border-b px-4 py-3">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          {showBack ? (
            <button onClick={onBack} className="p-2 -ml-2 hover:bg-gray-100 rounded-lg">
              <ChevronLeft className="w-5 h-5 text-gray-600" />
            </button>
          ) : null}
          <button onClick={() => window.location.reload()} className="p-2 hover:bg-gray-100 rounded-lg">
            <Home className="w-5 h-5 text-gray-600" />
          </button>
        </div>

        <div className="flex items-center gap-2">
          <button className="p-2 hover:bg-gray-100 rounded-lg">
            <Search className="w-5 h-5 text-gray-600" />
          </button>
          <button className="p-2 hover:bg-gray-100 rounded-lg">
            <Sun className="w-5 h-5 text-gray-600" />
          </button>
          <button className="p-2 hover:bg-gray-100 rounded-full bg-gray-100">
            <User className="w-5 h-5 text-gray-600" />
          </button>
          <button onClick={onMenuToggle} className="p-2 hover:bg-gray-100 rounded-lg">
            <Menu className="w-5 h-5 text-gray-600" />
          </button>
        </div>
      </div>
    </header>
  );
};

// 데스크탑/태블릿 헤더 컴포넌트
const DesktopHeader = ({
  user = { name: '김대표', role: '대표이사', roleName: '대표이사' },
  users = [],
  onUserChange,
  showFeatureDescription,
  onToggleFeatureDescription,
  // 버전 히스토리 관련
  currentVersion = 1,
  hasChanges = false,
  onOpenHistory,
  // 유저플로우 패널 관련
  showFlowPanel = false,
  onToggleFlowPanel,
  userNickname,
  // 기능정의문서 패널 관련
  showFeatureDocPanel = false,
  onToggleFeatureDocPanel,
  // 종합 플로우차트/기능정의서 패널 관련
  showComprehensiveFlowPanel = false,
  onToggleComprehensiveFlowPanel,
  showAllMenuFeatureDocPanel = false,
  onToggleAllMenuFeatureDocPanel,
  // 어드민 모드
  isFeatureAdmin = false
}) => {
  return (
    <header className="sticky top-0 z-40 bg-white border-b px-6 py-3">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <button className="p-2 hover:bg-gray-100 rounded-lg lg:hidden">
            <Menu className="w-5 h-5 text-gray-600" />
          </button>
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              placeholder="통합 검색..."
              className="w-full pl-10 pr-4 py-2 bg-gray-50 border-0 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
        </div>

        <div className="flex items-center gap-4">
          {/* 버전 히스토리 버튼 */}
          <button
            onClick={onOpenHistory}
            className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border transition-colors ${hasChanges
                ? 'bg-yellow-50 border-yellow-300 text-yellow-700'
                : 'bg-emerald-50 border-emerald-200 text-emerald-700 hover:bg-emerald-100'
              }`}
          >
            <GitBranch className="w-4 h-4" />
            <span className="text-sm font-medium">v{currentVersion}</span>
            {hasChanges && (
              <span className="w-2 h-2 rounded-full bg-yellow-500 animate-pulse" />
            )}
          </button>

          {/* 종합 플로우차트 패널 토글 버튼 */}
          <button
            onClick={onToggleComprehensiveFlowPanel}
            className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border transition-colors ${showComprehensiveFlowPanel
                ? 'bg-blue-100 border-blue-300 text-blue-700'
                : 'bg-blue-50 border-blue-200 text-blue-700 hover:bg-blue-100'
              }`}
          >
            <Activity className="w-4 h-4" />
            <span className="text-sm font-medium">플로우</span>
            {showComprehensiveFlowPanel && <Check className="w-3 h-3" />}
          </button>

          {/* 전체 메뉴 기능정의문서 패널 토글 */}
          <button
            onClick={onToggleAllMenuFeatureDocPanel}
            className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border transition-colors ${showAllMenuFeatureDocPanel
                ? 'bg-indigo-100 border-indigo-300 text-indigo-700'
                : 'bg-indigo-50 border-indigo-200 text-indigo-700 hover:bg-indigo-100'
              }`}
          >
            <BookOpen className="w-4 h-4" />
            <span className="text-sm font-medium">기능정의문서</span>
            {showAllMenuFeatureDocPanel && <Check className="w-3 h-3" />}
          </button>

          {/* 기능정의서 보기 토글 */}
          <button
            onClick={onToggleFeatureDescription}
            className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border transition-colors ${showFeatureDescription
                ? 'bg-purple-100 border-purple-300 text-purple-700'
                : 'bg-white border-gray-200 text-gray-600 hover:bg-gray-50'
              }`}
          >
            <FileText className="w-4 h-4" />
            <span className="text-sm font-medium">기능정의서</span>
            {isFeatureAdmin && showFeatureDescription && (
              <span className="text-[10px] px-1.5 py-0.5 bg-purple-600 text-white rounded font-bold">ADMIN</span>
            )}
            {showFeatureDescription && !isFeatureAdmin && <Check className="w-3 h-3" />}
          </button>
          <button className="p-2 hover:bg-gray-100 rounded-lg">
            <Sun className="w-5 h-5 text-gray-600" />
          </button>
          <button className="p-2 hover:bg-gray-100 rounded-lg">
            <Bell className="w-5 h-5 text-gray-600" />
          </button>
          <div className="flex items-center gap-3 pl-4 border-l">
            <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
              <User className="w-5 h-5 text-blue-600" />
            </div>
            <div className="hidden sm:block">
              <p className="text-sm font-medium text-gray-900">{user.name}</p>
              <p className="text-xs text-gray-500">{user.roleName || user.role}</p>
            </div>
            <select
              value={user.id}
              onChange={(e) => onUserChange && onUserChange(e.target.value)}
              className="text-sm border rounded-lg px-2 py-1 bg-white"
            >
              {users.map(u => (
                <option key={u.id} value={u.id}>{u.roleName}</option>
              ))}
            </select>
          </div>
        </div>
      </div>
    </header>
  );
};

// 모바일 슬라이드 메뉴
const MobileMenu = ({ isOpen, onClose, activeMenu, onMenuChange, menuConfig }) => {
  const [expandedMenus, setExpandedMenus] = useState(['sales', 'production']);

  // 메뉴 그룹 정의
  const allMenuGroups = [
    {
      id: 'master', label: '기준정보', icon: Settings, subMenus: [
        { id: 'item-master', label: '품목기준', icon: Layers },
        { id: 'process-master', label: '공정기준', icon: GitBranch },
        { id: 'quality-master', label: '품질기준', icon: ShieldCheck },
        { id: 'customer-master', label: '거래처', icon: Users },
        { id: 'site-master', label: '현장', icon: MapPin },
        { id: 'order-master', label: '수주기준', icon: Package },
        { id: 'process', label: '공정', icon: GitBranch },
        { id: 'number-rule', label: '채번', icon: ClipboardList },
        { id: 'code-rule', label: '공통코드', icon: Layers },
        { id: 'quote-formula', label: '견적수식', icon: Calculator },
        { id: 'document-template', label: '문서양식', icon: FileText },
      ]
    },
    {
      id: 'sales', label: '판매', icon: DollarSign, subMenus: [
        { id: 'customer', label: '거래처', icon: Users },
        { id: 'quote', label: '견적', icon: FileText },
        { id: 'order', label: '수주', icon: Package },
        { id: 'site', label: '현장', icon: Building },
        { id: 'price', label: '단가', icon: DollarSign },
      ]
    },
    {
      id: 'outbound', label: '출고', icon: Upload, subMenus: [
        { id: 'shipment', label: '출하', icon: Truck },
      ]
    },
    {
      id: 'production', label: '생산', icon: Factory, subMenus: [
        { id: 'item', label: '품목', icon: Package },
        { id: 'production-dashboard', label: '생산 현황판', icon: BarChart3 },
        { id: 'work-order', label: '작업지시', icon: ClipboardList },
        { id: 'work-result', label: '작업실적', icon: Clipboard },
        { id: 'worker-task', label: '작업자 화면', icon: User },
      ]
    },
    {
      id: 'quality', label: '품질', icon: ShieldCheck, subMenus: [
        { id: 'inspection', label: '검사', icon: ShieldCheck },
        { id: 'defect', label: '부적합품', icon: XCircle },
      ]
    },
    {
      id: 'inventory', label: '자재', icon: Warehouse, subMenus: [
        { id: 'stock', label: '재고현황', icon: Box },
        { id: 'inbound', label: '입고', icon: Download },
      ]
    },
    {
      id: 'accounting', label: '회계', icon: CreditCard, subMenus: [
        {
          id: 'acc-customer', label: '거래처', icon: Building, subMenus: [
            { id: 'acc-customer-list', label: '거래처 신용등급 목록' },
            { id: 'acc-customer-register', label: '신규 거래처 신용등급 생성' },
            { id: 'acc-customer-edit', label: '신용등급 변경' },
            { id: 'acc-customer-statement', label: '거래명세서 발행' },
            { id: 'acc-customer-tax', label: '세금계산서 발행' },
          ]
        },
        {
          id: 'sales-account', label: '매출', icon: TrendingUp, subMenus: [
            { id: 'sales-list', label: '판매조회 리스트' },
          ]
        },
        {
          id: 'purchase', label: '매입', icon: ShoppingCart, subMenus: [
            { id: 'purchase-list', label: '품의서 리스트' },
            { id: 'purchase-register', label: '품의서 등록' },
            { id: 'expense-list', label: '지출결의서 리스트' },
            { id: 'expense-register', label: '지출결의서 등록' },
            { id: 'expense-estimate', label: '지출예상내역서' },
          ]
        },
        {
          id: 'cashbook', label: '금전출납부', icon: CreditCard, subMenus: [
            { id: 'cashbook-list', label: '금전출납부' },
            { id: 'cashbook-register', label: '출납 등록' },
            { id: 'cashbook-edit', label: '출납 수정' },
          ]
        },
        {
          id: 'collection', label: '수금', icon: DollarSign, subMenus: [
            { id: 'collection-list', label: '수금 리스트' },
            { id: 'collection-register', label: '수금 등록' },
            { id: 'receivable-list', label: '미수금 현황' },
            { id: 'bill-list', label: '어음 목록' },
          ]
        },
        {
          id: 'cost-analysis', label: '원가', icon: Calculator, subMenus: [
            { id: 'cost-list', label: '수주별 원가 분석' },
            { id: 'cost-summary', label: '원가요약' },
            { id: 'cost-material', label: '자재비' },
            { id: 'cost-outsourcing', label: '외주비' },
            { id: 'cost-labor', label: '인건비' },
            { id: 'cost-expense', label: '경비' },
            { id: 'cost-manufacturing', label: '제조원가' },
          ]
        },
      ]
    },
  ];

  const menuGroups = allMenuGroups.filter(g => menuConfig[g.id]?.enabled !== false);

  const toggleMenu = (menuId) => {
    setExpandedMenus(prev =>
      prev.includes(menuId) ? prev.filter(id => id !== menuId) : [...prev, menuId]
    );
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="absolute right-0 top-0 h-full w-80 bg-white shadow-xl overflow-y-auto">
        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-blue-500 rounded-lg flex items-center justify-center text-white font-bold">
              S
            </div>
            <div>
              <h1 className="font-bold text-gray-900">SAM</h1>
              <p className="text-xs text-gray-500">Smart Automation Management</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
            ✕
          </button>
        </div>

        {/* 메뉴 */}
        <nav className="p-3 space-y-1">
          {menuGroups.map(group => (
            <div key={group.id}>
              <button
                onClick={() => toggleMenu(group.id)}
                className={`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-sm font-medium transition-colors
                  ${expandedMenus.includes(group.id) ? 'bg-blue-50 text-blue-700' : 'text-gray-700 hover:bg-gray-100'}`}
              >
                <div className="flex items-center gap-3">
                  <group.icon className="w-5 h-5" />
                  {group.label}
                </div>
                {expandedMenus.includes(group.id) ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
              </button>
              {expandedMenus.includes(group.id) && (
                <div className="mt-1 ml-5 space-y-0.5">
                  {group.subMenus.map(sub => (
                    <div key={sub.id}>
                      {sub.subMenus ? (
                        // 3단계 메뉴가 있는 경우
                        <>
                          <button
                            onClick={() => toggleMenu(sub.id)}
                            className={`w-full flex items-center justify-between px-3 py-2 rounded-lg text-sm transition-colors
                              ${expandedMenus.includes(sub.id) ? 'bg-gray-100 text-gray-900' : 'text-gray-600 hover:bg-gray-100'}`}
                          >
                            <div className="flex items-center gap-3">
                              {sub.icon && <sub.icon className="w-4 h-4" />}
                              {sub.label}
                            </div>
                            {expandedMenus.includes(sub.id) ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
                          </button>
                          {expandedMenus.includes(sub.id) && (
                            <div className="mt-0.5 ml-4 space-y-0.5">
                              {sub.subMenus.map(subSub => (
                                <button
                                  key={subSub.id}
                                  onClick={() => { onMenuChange(subSub.id); onClose(); }}
                                  className={`w-full flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs transition-colors
                                    ${activeMenu === subSub.id ? 'bg-blue-500 text-white' : 'text-gray-500 hover:bg-gray-100'}`}
                                >
                                  <span className="w-1 h-1 rounded-full bg-current" />
                                  {subSub.label}
                                </button>
                              ))}
                            </div>
                          )}
                        </>
                      ) : (
                        // 2단계 메뉴만 있는 경우
                        <button
                          onClick={() => { onMenuChange(sub.id); onClose(); }}
                          className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors
                            ${activeMenu === sub.id ? 'bg-blue-500 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
                        >
                          {sub.icon && <sub.icon className="w-4 h-4" />}
                          {sub.label}
                        </button>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          ))}
        </nav>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════
// 메뉴ID-페이지타이틀 매핑 테이블
// ═══════════════════════════════════════════════════════════════════
const menuTitleMap = {
  // 대시보드
  'dashboard': '대시보드',
  'sales-dashboard': '판매 대시보드',
  'production-dashboard': '생산 현황판',
  'quality-dashboard': '품질 대시보드',
  'accounting-dashboard': '회계 대시보드',
  'purchase-dashboard': '구매 대시보드',
  'worker-dashboard': '작업자 대시보드',
  // 기준정보
  'item-master': '품목기준관리',
  'process-master': '공정기준관리',
  'quality-master': '품질기준관리',
  'customer-master': '거래처기준관리',
  'site-master': '현장기준관리',
  'order-master': '수주기준관리',
  'process': '공정관리',
  'number-rule': '채번관리',
  'code-rule': '공통코드관리',
  'quote-formula': '견적수식관리',
  'document-template': '문서양식관리',
  // 판매관리
  'customer': '거래처관리',
  'quote': '견적관리',
  'quote-register': '견적등록',
  'order': '수주관리',
  'order-list': '수주목록',
  'order-detail': '수주상세',
  'shipment': '출하관리',
  'site': '현장관리',
  'price': '단가관리',
  // 생산관리
  'item': '품목관리',
  'work-order': '작업지시 관리',
  'work-result': '작업실적',
  'worker-task': '작업자 화면',
  // 품질관리
  'inspection': '검사관리',
  'defect': '부적합품관리',
  // 자재관리
  'stock': '재고현황',
  'inbound': '입고관리',
  'outbound': '출고관리',
  // 회계관리
  'sales-account': '매출관리',
  'tax-invoice': '세금계산서관리',
  'collection': '수금관리',
  'acc-customer': '회계 거래처관리',
};

// ═══════════════════════════════════════════════════════════════════
// DOM 요소 자동 분석 유틸리티
// ═══════════════════════════════════════════════════════════════════
const analyzeElement = (element) => {
  if (!element) return null;

  const result = {
    uiInfo: {
      componentType: '',
      position: '',
      interaction: '',
      style: '',
    },
    funcInfo: {
      purpose: '',
      trigger: '',
      process: '',
      result: '',
      validation: '',
    },
    dataInfo: {
      source: '',
      endpoint: '',
      method: '',
      fields: '',
      relatedTable: '',
    },
    label: '',
  };

  // 요소 타입 분석
  const tagName = element.tagName?.toLowerCase();
  const type = element.type;
  const role = element.getAttribute?.('role');

  // 컴포넌트 타입 결정
  if (tagName === 'button' || role === 'button') {
    result.uiInfo.componentType = '버튼';
    result.uiInfo.interaction = '클릭';
  } else if (tagName === 'input') {
    if (type === 'checkbox') {
      result.uiInfo.componentType = '체크박스';
      result.uiInfo.interaction = '선택';
    } else if (type === 'radio') {
      result.uiInfo.componentType = '라디오';
      result.uiInfo.interaction = '선택';
    } else {
      result.uiInfo.componentType = '입력필드';
      result.uiInfo.interaction = '입력';
    }
  } else if (tagName === 'select') {
    result.uiInfo.componentType = '셀렉트박스';
    result.uiInfo.interaction = '선택';
  } else if (tagName === 'textarea') {
    result.uiInfo.componentType = '텍스트영역';
    result.uiInfo.interaction = '입력';
  } else if (tagName === 'a') {
    result.uiInfo.componentType = '링크';
    result.uiInfo.interaction = '클릭';
  } else if (tagName === 'table') {
    result.uiInfo.componentType = '테이블';
    result.uiInfo.interaction = '조회';
  } else if (tagName === 'tr') {
    result.uiInfo.componentType = '테이블행';
    result.uiInfo.interaction = '클릭';
  } else if (tagName === 'th' || tagName === 'td') {
    result.uiInfo.componentType = '테이블셀';
  } else if (tagName === 'label') {
    result.uiInfo.componentType = '라벨';
  } else if (tagName === 'img' || tagName === 'svg') {
    result.uiInfo.componentType = '아이콘/이미지';
  } else if (element.className?.includes('modal') || element.className?.includes('dialog')) {
    result.uiInfo.componentType = '모달';
  } else if (element.className?.includes('card')) {
    result.uiInfo.componentType = '카드';
  } else if (element.className?.includes('tab')) {
    result.uiInfo.componentType = '탭';
    result.uiInfo.interaction = '클릭';
  } else {
    result.uiInfo.componentType = '영역';
  }

  // 텍스트 내용 추출
  const text = element.innerText?.trim()?.substring(0, 50) ||
    element.value ||
    element.placeholder ||
    element.getAttribute?.('aria-label') ||
    element.title || '';

  if (text) {
    result.label = text.split('\n')[0]; // 첫 줄만
  }

  // 스타일 분석
  const className = element.className || '';
  if (className.includes('bg-blue') || className.includes('primary')) {
    result.uiInfo.style = 'Primary 스타일';
  } else if (className.includes('bg-red') || className.includes('danger')) {
    result.uiInfo.style = 'Danger 스타일';
  } else if (className.includes('bg-green') || className.includes('success')) {
    result.uiInfo.style = 'Success 스타일';
  } else if (className.includes('bg-orange') || className.includes('warning')) {
    result.uiInfo.style = 'Warning 스타일';
  } else if (className.includes('bg-gray') || className.includes('secondary')) {
    result.uiInfo.style = 'Secondary 스타일';
  }

  // React 내부 정보에서 onClick 핸들러 분석
  try {
    const reactKey = Object.keys(element).find(key => key.startsWith('__reactFiber$'));
    if (reactKey) {
      const fiber = element[reactKey];
      let currentFiber = fiber;

      // props에서 onClick 찾기
      while (currentFiber) {
        const props = currentFiber.memoizedProps || currentFiber.pendingProps;
        if (props?.onClick) {
          const onClickStr = props.onClick.toString();

          // navigate 패턴 찾기
          const navigateMatch = onClickStr.match(/navigate\(['"]([^'"]+)['"]\)/);
          if (navigateMatch) {
            const targetMenu = navigateMatch[1];
            const targetTitle = menuTitleMap[targetMenu] || targetMenu;
            result.funcInfo.result = `→ ${targetTitle} 페이지로 이동`;
            result.funcInfo.purpose = `${targetTitle} 화면으로 이동`;
          }

          // setView 패턴 찾기
          const setViewMatch = onClickStr.match(/setView\(['"]([^'"]+)['"]\)/);
          if (setViewMatch) {
            const targetView = setViewMatch[1];
            const targetTitle = menuTitleMap[targetView] || targetView;
            result.funcInfo.result = `→ ${targetTitle} 화면으로 전환`;
            result.funcInfo.purpose = `${targetTitle} 화면 표시`;
          }

          // setActiveMenu 패턴 찾기
          const menuMatch = onClickStr.match(/setActiveMenu\(['"]([^'"]+)['"]\)/);
          if (menuMatch) {
            const targetMenu = menuMatch[1];
            const targetTitle = menuTitleMap[targetMenu] || targetMenu;
            result.funcInfo.result = `→ ${targetTitle} 메뉴로 이동`;
          }

          // 모달 열기 패턴
          if (onClickStr.includes('setShow') && onClickStr.includes('true')) {
            const modalMatch = onClickStr.match(/setShow(\w+)\(true\)/);
            if (modalMatch) {
              result.funcInfo.result = `→ ${modalMatch[1]} 모달 열기`;
            } else {
              result.funcInfo.result = '→ 모달/팝업 열기';
            }
          }

          // 저장/등록 패턴
          if (onClickStr.includes('save') || onClickStr.includes('Save') ||
            onClickStr.includes('submit') || onClickStr.includes('Submit')) {
            result.funcInfo.purpose = '데이터 저장';
            result.dataInfo.method = 'POST';
          }

          // 삭제 패턴
          if (onClickStr.includes('delete') || onClickStr.includes('Delete') ||
            onClickStr.includes('remove') || onClickStr.includes('Remove')) {
            result.funcInfo.purpose = '데이터 삭제';
            result.dataInfo.method = 'DELETE';
          }

          // 수정 패턴
          if (onClickStr.includes('edit') || onClickStr.includes('Edit') ||
            onClickStr.includes('update') || onClickStr.includes('Update')) {
            result.funcInfo.purpose = '데이터 수정';
            result.dataInfo.method = 'PUT';
          }

          break;
        }
        currentFiber = currentFiber.return;
      }
    }
  } catch (e) {
    // React 내부 접근 실패 시 무시
  }

  // href 속성 확인 (링크)
  const href = element.getAttribute?.('href');
  if (href && href !== '#') {
    result.funcInfo.result = `→ ${href} 로 이동`;
  }

  // placeholder에서 힌트 추출
  const placeholder = element.placeholder;
  if (placeholder) {
    result.funcInfo.purpose = `${placeholder} 입력`;
  }

  return result;
};

// 좌표로 요소 찾기
const getElementAtPoint = (x, y, containerRef) => {
  // 현재 드래그 중인 뱃지는 제외하고 요소 찾기
  const elements = document.elementsFromPoint(x, y);

  // 뱃지 오버레이와 패널을 제외한 실제 UI 요소 찾기
  for (const el of elements) {
    // 뱃지 관련 요소 제외
    if (el.closest('[data-badge-overlay]') || el.closest('[data-feature-panel]')) {
      continue;
    }
    // 의미 있는 요소 찾기
    if (el.tagName && !['HTML', 'BODY', 'MAIN', 'DIV', 'SECTION', 'ARTICLE'].includes(el.tagName.toUpperCase()) ||
      el.onclick || el.getAttribute?.('role') || el.className?.includes('btn') || el.className?.includes('button')) {
      return el;
    }
    // div지만 클릭 가능한 요소
    if (el.tagName === 'DIV' && (el.onclick || el.className?.includes('cursor-pointer') || el.className?.includes('hover:'))) {
      return el;
    }
  }

  // 못 찾으면 첫 번째 유의미한 요소
  return elements.find(el => el.tagName && !['HTML', 'BODY'].includes(el.tagName.toUpperCase()));
};

// ═══════════════════════════════════════════════════════════════════
// 닉네임 입력 모달 컴포넌트
// ═══════════════════════════════════════════════════════════════════
const NicknameModal = ({ onSave, currentNickname }) => {
  const [nickname, setNickname] = useState(currentNickname || '');
  const inputRef = React.useRef(null);
  const isEditMode = !!currentNickname;

  React.useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
      // 수정 모드일 때 기존 이름 전체 선택
      if (isEditMode) {
        inputRef.current.select();
      }
    }
  }, [isEditMode]);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (nickname.trim().length >= 2) {
      onSave(nickname.trim());
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[9999]">
      <div className="bg-white rounded-lg shadow-xl w-96 overflow-hidden border border-gray-300">
        <div className="bg-gray-200 text-black px-6 py-4 border-b border-gray-300">
          <h2 className="text-xl font-bold">{isEditMode ? '이름 변경' : '기능정의서 접근'}</h2>
          <p className="text-sm text-gray-600 mt-1">
            {isEditMode ? '새로운 닉네임을 입력해주세요' : '닉네임을 입력해주세요'}
          </p>
        </div>
        <form onSubmit={handleSubmit} className="p-6">
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-2">
              닉네임 (2자 이상)
            </label>
            <input
              ref={inputRef}
              type="text"
              value={nickname}
              onChange={(e) => setNickname(e.target.value)}
              placeholder="예: 김기획"
              className="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-gray-500 focus:ring-2 focus:ring-gray-200 transition-all text-lg"
              maxLength={20}
            />
          </div>
          <p className="text-xs text-gray-500 mb-4">
            {isEditMode ? (
              <>
                * 이름을 변경하면 기존에 작성한 모든 기능정의서의 작성자 이름이<br />
                &nbsp;&nbsp;함께 변경됩니다.
              </>
            ) : (
              <>
                * 이 닉네임은 기능정의서 작성 시 표시됩니다.<br />
                * 브라우저에 저장되어 다음 접속 시 자동으로 사용됩니다.
              </>
            )}
          </p>
          <button
            type="submit"
            disabled={nickname.trim().length < 2 || (isEditMode && nickname.trim() === currentNickname)}
            className="w-full py-3 bg-gray-800 text-white rounded-lg font-medium hover:bg-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-all border border-gray-600"
          >
            {isEditMode ? '이름 변경하기' : '시작하기'}
          </button>
        </form>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════
// 버전 히스토리 관리 모달 컴포넌트
// ═══════════════════════════════════════════════════════════════════
const VersionHistoryModal = ({ isOpen, onClose, history, onCommit, onRollback, currentVersion, hasChanges, autoMessage }) => {
  if (!isOpen) return null;

  const handleQuickCommit = () => {
    if (!autoMessage) {
      alert('변경사항이 없습니다.');
      return;
    }
    onCommit(autoMessage);
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[9999]">
      <div className="bg-white rounded-2xl shadow-2xl w-[600px] max-h-[80vh] overflow-hidden">
        {/* 헤더 */}
        <div className="bg-gradient-to-r from-emerald-600 to-teal-600 text-white px-6 py-4 flex items-center justify-between">
          <div>
            <h2 className="text-xl font-bold flex items-center gap-2">
              <GitBranch className="w-5 h-5" />
              버전 히스토리
            </h2>
            <p className="text-sm opacity-90 mt-1">
              현재 버전: v{currentVersion} {hasChanges && <span className="text-yellow-300">• 변경사항 있음</span>}
            </p>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-white/20 rounded-lg transition-colors">
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 커밋 버튼 - 자동 메시지 */}
        {hasChanges && (
          <div className="p-4 border-b bg-yellow-50">
            <div className="mb-3 p-3 bg-white rounded-lg border border-yellow-200 max-h-40 overflow-y-auto">
              <p className="text-xs text-gray-500 mb-1">자동 생성된 커밋 메시지:</p>
              <p className="text-sm font-medium text-gray-800 whitespace-pre-wrap">{autoMessage}</p>
            </div>
            <button
              onClick={handleQuickCommit}
              className="w-full py-3 bg-emerald-500 text-white rounded-xl font-medium hover:bg-emerald-600 transition-colors flex items-center justify-center gap-2"
            >
              <Save className="w-4 h-4" />
              v{currentVersion + 1} 커밋하기
            </button>
          </div>
        )}

        {/* 히스토리 목록 */}
        <div className="overflow-y-auto max-h-[50vh]">
          {history.length === 0 ? (
            <div className="p-8 text-center text-gray-500">
              <Clock className="w-12 h-12 mx-auto mb-3 opacity-30" />
              <p>아직 커밋된 버전이 없습니다.</p>
              <p className="text-sm mt-1">변경 후 커밋하면 히스토리가 기록됩니다.</p>
            </div>
          ) : (
            <div className="divide-y">
              {history.map((item, index) => (
                <div
                  key={item.id}
                  className={`p-4 hover:bg-gray-50 ${index === 0 ? 'bg-emerald-50' : ''}`}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-bold text-emerald-600">v{item.version}</span>
                        {index === 0 && (
                          <span className="text-xs px-2 py-0.5 bg-emerald-100 text-emerald-700 rounded-full">현재</span>
                        )}
                      </div>
                      <p className="text-sm font-medium text-gray-900 mt-1 whitespace-pre-wrap">{item.message}</p>
                      {item.summary && (
                        <p className="text-xs text-gray-500 mt-1 whitespace-pre-wrap">{item.summary}</p>
                      )}
                      <div className="flex items-center gap-3 mt-2 text-xs text-gray-400">
                        <span className="flex items-center gap-1">
                          <User className="w-3 h-3" />
                          {item.author}
                        </span>
                        <span className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {new Date(item.timestamp).toLocaleString()}
                        </span>
                      </div>
                    </div>
                    {index > 0 && (
                      <button
                        onClick={() => {
                          if (window.confirm(`v${item.version}로 롤백하시겠습니까?\n현재 변경사항은 사라집니다.`)) {
                            onRollback(item.id);
                          }
                        }}
                        className="px-3 py-1.5 text-xs bg-orange-100 text-orange-700 rounded-lg hover:bg-orange-200 transition-colors"
                      >
                        롤백
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 푸터 */}
        <div className="p-4 border-t bg-gray-50 text-xs text-gray-500">
          💡 커밋하면 현재 상태가 저장되고, 다른 사용자에게 공개됩니다.
        </div>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════
// 유저플로우 모달 컴포넌트
// ═══════════════════════════════════════════════════════════════════
const UserFlowModal = ({ isOpen, onClose, currentScreen, allBadges, allScreens }) => {
  const [selectedScreen, setSelectedScreen] = useState(currentScreen);
  const [flowData, setFlowData] = useState(() => {
    const saved = localStorage.getItem('pageUserFlows');
    return saved ? JSON.parse(saved) : {};
  });

  // 플로우 데이터 저장
  React.useEffect(() => {
    localStorage.setItem('pageUserFlows', JSON.stringify(flowData));
  }, [flowData]);

  // 현재 화면 변경 시 선택 화면 업데이트
  React.useEffect(() => {
    if (currentScreen) setSelectedScreen(currentScreen);
  }, [currentScreen]);

  if (!isOpen) return null;

  // 현재 화면의 뱃지들
  const screenBadges = allBadges[selectedScreen] || [];

  // 뱃지에서 데이터 흐름 정보 추출
  const extractDataFlows = (badges) => {
    const flows = [];
    badges.forEach(badge => {
      // 데이터 소스가 있는 경우
      if (badge.dataInfo?.source) {
        flows.push({
          type: 'data_source',
          from: badge.dataInfo.source,
          to: selectedScreen,
          label: badge.dataInfo.fields || badge.description,
          badgeId: badge.id,
          badgeNumber: badge.number
        });
      }
      // API 엔드포인트가 있는 경우
      if (badge.dataInfo?.endpoint) {
        flows.push({
          type: 'api',
          endpoint: badge.dataInfo.endpoint,
          method: badge.dataInfo.method || 'GET',
          label: badge.description,
          badgeId: badge.id,
          badgeNumber: badge.number
        });
      }
      // 관련 테이블이 있는 경우
      if (badge.dataInfo?.relatedTable) {
        flows.push({
          type: 'table',
          table: badge.dataInfo.relatedTable,
          label: badge.description,
          badgeId: badge.id,
          badgeNumber: badge.number
        });
      }
    });
    return flows;
  };

  // 액션 플로우 (사용자 인터랙션)
  const extractActionFlows = (badges) => {
    return badges
      .filter(b => b.uiInfo?.interaction || b.funcInfo?.trigger)
      .map(badge => ({
        id: badge.id,
        number: badge.number,
        action: badge.uiInfo?.interaction || badge.funcInfo?.trigger,
        component: badge.uiInfo?.componentType,
        description: badge.description,
        result: badge.funcInfo?.result,
        process: badge.funcInfo?.process
      }));
  };

  const dataFlows = extractDataFlows(screenBadges);
  const actionFlows = extractActionFlows(screenBadges);

  // 다른 화면과의 연결 관계 찾기
  const findConnectedScreens = () => {
    const connections = [];

    // 데이터 소스에서 다른 화면 참조 찾기
    screenBadges.forEach(badge => {
      const desc = (badge.description || '').toLowerCase();
      const source = (badge.dataInfo?.source || '').toLowerCase();

      Object.keys(allScreens || {}).forEach(screenKey => {
        if (screenKey !== selectedScreen) {
          const screenName = screenKey.split('-')[0].toLowerCase();
          if (desc.includes(screenName) || source.includes(screenName)) {
            connections.push({
              targetScreen: screenKey,
              type: 'reference',
              badge: badge
            });
          }
        }
      });
    });

    return connections;
  };

  const connectedScreens = findConnectedScreens();

  // 화면 이름 포맷팅
  const formatScreenName = (key) => {
    if (!key) return '';
    const parts = key.split('-');
    return parts[0];
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[9999]">
      <div className="bg-white rounded-2xl shadow-2xl w-[900px] max-h-[85vh] overflow-hidden">
        {/* 헤더 */}
        <div className="bg-gradient-to-r from-indigo-600 to-blue-600 text-white px-6 py-4 flex items-center justify-between">
          <div>
            <h2 className="text-xl font-bold flex items-center gap-2">
              <GitBranch className="w-5 h-5" />
              페이지 유저플로우
            </h2>
            <p className="text-sm opacity-90 mt-1">데이터 흐름 & 사용자 인터랙션</p>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-white/20 rounded-lg transition-colors">
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 화면 선택 */}
        <div className="p-4 border-b bg-gray-50">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="text-sm font-medium text-gray-600">화면:</span>
            <select
              value={selectedScreen}
              onChange={(e) => setSelectedScreen(e.target.value)}
              className="px-3 py-1.5 border rounded-lg text-sm bg-white"
            >
              {Object.keys(allBadges).map(screenKey => (
                <option key={screenKey} value={screenKey}>
                  {formatScreenName(screenKey)} ({(allBadges[screenKey] || []).length}개 뱃지)
                </option>
              ))}
            </select>
            <span className="ml-auto text-xs text-gray-400">
              기능정의서 뱃지에서 자동 생성됨
            </span>
          </div>
        </div>

        {/* 플로우 내용 */}
        <div className="overflow-y-auto max-h-[55vh] p-6">
          {screenBadges.length === 0 ? (
            <div className="text-center py-12 text-gray-400">
              <GitBranch className="w-16 h-16 mx-auto mb-4 opacity-30" />
              <p className="text-lg">이 화면에 등록된 기능정의서가 없습니다</p>
              <p className="text-sm mt-2">기능정의서에 뱃지를 추가하면 자동으로 플로우가 생성됩니다</p>
            </div>
          ) : (
            <div className="space-y-6">
              {/* 화면 개요 */}
              <div className="bg-indigo-50 rounded-xl p-4 border border-indigo-200">
                <h3 className="font-bold text-indigo-900 mb-3 flex items-center gap-2">
                  <Layers className="w-4 h-4" />
                  {formatScreenName(selectedScreen)} 화면 개요
                </h3>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div className="bg-white rounded-lg p-3 text-center">
                    <div className="text-2xl font-bold text-indigo-600">{screenBadges.length}</div>
                    <div className="text-xs text-gray-500">전체 기능</div>
                  </div>
                  <div className="bg-white rounded-lg p-3 text-center">
                    <div className="text-2xl font-bold text-green-600">{actionFlows.length}</div>
                    <div className="text-xs text-gray-500">인터랙션</div>
                  </div>
                  <div className="bg-white rounded-lg p-3 text-center">
                    <div className="text-2xl font-bold text-orange-600">{dataFlows.length}</div>
                    <div className="text-xs text-gray-500">데이터 연결</div>
                  </div>
                </div>
              </div>

              {/* 데이터 흐름 */}
              {dataFlows.length > 0 && (
                <div className="bg-orange-50 rounded-xl p-4 border border-orange-200">
                  <h3 className="font-bold text-orange-900 mb-3 flex items-center gap-2">
                    <Database className="w-4 h-4" />
                    데이터 흐름
                  </h3>
                  <div className="space-y-2">
                    {dataFlows.map((flow, idx) => (
                      <div key={idx} className="bg-white rounded-lg p-3 flex items-center gap-3">
                        <span className="w-6 h-6 bg-orange-500 text-white rounded-full flex items-center justify-center text-xs font-bold">
                          {flow.badgeNumber}
                        </span>
                        {flow.type === 'data_source' && (
                          <>
                            <span className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs font-medium">
                              {flow.from}
                            </span>
                            <ArrowRight className="w-4 h-4 text-gray-400" />
                            <span className="px-2 py-1 bg-indigo-100 text-indigo-700 rounded text-xs font-medium">
                              {formatScreenName(flow.to)}
                            </span>
                            <span className="text-xs text-gray-500 ml-2">{flow.label}</span>
                          </>
                        )}
                        {flow.type === 'api' && (
                          <>
                            <span className={`px-2 py-1 rounded text-xs font-medium ${flow.method === 'GET' ? 'bg-green-100 text-green-700' :
                                flow.method === 'POST' ? 'bg-blue-100 text-blue-700' :
                                  flow.method === 'PUT' ? 'bg-yellow-100 text-yellow-700' :
                                    'bg-red-100 text-red-700'
                              }`}>
                              {flow.method}
                            </span>
                            <code className="px-2 py-1 bg-gray-100 rounded text-xs">{flow.endpoint}</code>
                            <span className="text-xs text-gray-500 ml-2">{flow.label}</span>
                          </>
                        )}
                        {flow.type === 'table' && (
                          <>
                            <span className="px-2 py-1 bg-purple-100 text-purple-700 rounded text-xs font-medium">
                              테이블
                            </span>
                            <code className="px-2 py-1 bg-gray-100 rounded text-xs">{flow.table}</code>
                            <span className="text-xs text-gray-500 ml-2">{flow.label}</span>
                          </>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 사용자 인터랙션 플로우 */}
              {actionFlows.length > 0 && (
                <div className="bg-green-50 rounded-xl p-4 border border-green-200">
                  <h3 className="font-bold text-green-900 mb-3 flex items-center gap-2">
                    <MousePointer className="w-4 h-4" />
                    사용자 인터랙션 플로우
                  </h3>
                  <div className="space-y-3">
                    {actionFlows.map((action, idx) => (
                      <div key={action.id} className="bg-white rounded-lg p-3">
                        <div className="flex items-start gap-3">
                          <span className="w-6 h-6 bg-green-500 text-white rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0">
                            {action.number}
                          </span>
                          <div className="flex-1">
                            <div className="flex items-center gap-2 flex-wrap">
                              {action.component && (
                                <span className="px-2 py-0.5 bg-blue-100 text-blue-700 rounded text-xs">
                                  {action.component}
                                </span>
                              )}
                              {action.action && (
                                <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">
                                  {action.action}
                                </span>
                              )}
                            </div>
                            <p className="text-sm text-gray-700 mt-1">{action.description}</p>
                            {action.process && (
                              <div className="mt-2 text-xs text-gray-500 flex items-start gap-1">
                                <ArrowRight className="w-3 h-3 mt-0.5 flex-shrink-0" />
                                <span>{action.process}</span>
                              </div>
                            )}
                            {action.result && (
                              <div className="mt-1 text-xs text-green-600 flex items-start gap-1">
                                <Check className="w-3 h-3 mt-0.5 flex-shrink-0" />
                                <span>{action.result}</span>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 연결된 화면들 */}
              {connectedScreens.length > 0 && (
                <div className="bg-purple-50 rounded-xl p-4 border border-purple-200">
                  <h3 className="font-bold text-purple-900 mb-3 flex items-center gap-2">
                    <Link className="w-4 h-4" />
                    연결된 화면
                  </h3>
                  <div className="flex flex-wrap gap-2">
                    {[...new Set(connectedScreens.map(c => c.targetScreen))].map(screen => (
                      <button
                        key={screen}
                        onClick={() => setSelectedScreen(screen)}
                        className="px-3 py-1.5 bg-white border border-purple-200 rounded-lg text-sm hover:bg-purple-100 transition-colors flex items-center gap-2"
                      >
                        <ArrowRight className="w-3 h-3" />
                        {formatScreenName(screen)}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {/* 전체 플로우 다이어그램 */}
              <div className="bg-gray-50 rounded-xl p-4 border border-gray-200">
                <h3 className="font-bold text-gray-900 mb-3 flex items-center gap-2">
                  <GitBranch className="w-4 h-4" />
                  플로우 다이어그램
                </h3>
                <div className="bg-white rounded-lg p-4 min-h-[200px]">
                  {/* 간단한 플로우 시각화 */}
                  <div className="flex flex-col items-center gap-4">
                    {/* 데이터 소스 */}
                    {dataFlows.filter(f => f.type === 'data_source').length > 0 && (
                      <div className="flex items-center gap-2 flex-wrap justify-center">
                        {[...new Set(dataFlows.filter(f => f.type === 'data_source').map(f => f.from))].map(source => (
                          <div key={source} className="px-3 py-2 bg-blue-100 text-blue-700 rounded-lg text-sm font-medium">
                            📊 {source}
                          </div>
                        ))}
                      </div>
                    )}

                    {dataFlows.length > 0 && (
                      <div className="flex flex-col items-center">
                        <div className="w-0.5 h-6 bg-gray-300" />
                        <ChevronDown className="w-4 h-4 text-gray-400" />
                      </div>
                    )}

                    {/* 현재 화면 */}
                    <div className="px-6 py-4 bg-indigo-500 text-white rounded-xl font-bold text-center shadow-lg">
                      {formatScreenName(selectedScreen)}
                      <div className="text-xs opacity-80 mt-1">{screenBadges.length}개 기능</div>
                    </div>

                    {/* 인터랙션 표시 */}
                    {actionFlows.length > 0 && (
                      <div className="flex flex-wrap gap-2 justify-center max-w-lg">
                        {actionFlows.slice(0, 6).map(action => (
                          <div key={action.id} className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs">
                            {action.action || action.component}
                          </div>
                        ))}
                        {actionFlows.length > 6 && (
                          <div className="px-2 py-1 bg-gray-100 text-gray-500 rounded text-xs">
                            +{actionFlows.length - 6}개
                          </div>
                        )}
                      </div>
                    )}

                    {/* 연결된 화면 */}
                    {connectedScreens.length > 0 && (
                      <>
                        <div className="flex flex-col items-center">
                          <ChevronDown className="w-4 h-4 text-gray-400" />
                          <div className="w-0.5 h-6 bg-gray-300" />
                        </div>
                        <div className="flex items-center gap-2 flex-wrap justify-center">
                          {[...new Set(connectedScreens.map(c => c.targetScreen))].slice(0, 4).map(screen => (
                            <div key={screen} className="px-3 py-2 bg-purple-100 text-purple-700 rounded-lg text-sm">
                              🔗 {formatScreenName(screen)}
                            </div>
                          ))}
                        </div>
                      </>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 푸터 */}
        <div className="p-4 border-t bg-gray-50 text-xs text-gray-500 flex items-center justify-between">
          <span>💡 기능정의서 뱃지의 데이터 연동/기능 정보에서 자동 생성됩니다</span>
          <span className="text-gray-400">
            마지막 업데이트: {new Date().toLocaleString()}
          </span>
        </div>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════
// 인라인 뱃지 입력 컴포넌트 (클릭한 위치에 표시)
// ═══════════════════════════════════════════════════════════════════
const InlineBadgeInput = ({ position, number, onSave, onCancel, existingBadge, onDelete }) => {
  const [label, setLabel] = useState(existingBadge?.label || '');
  const [description, setDescription] = useState(existingBadge?.description || '');
  const [showDetails, setShowDetails] = useState(false);
  const [uiType, setUiType] = useState(existingBadge?.uiInfo?.componentType || '');
  const [interaction, setInteraction] = useState(existingBadge?.uiInfo?.interaction || '');
  const [selectedColor, setSelectedColor] = useState(existingBadge?.color || 'red');
  const labelInputRef = React.useRef(null);
  const inputRef = React.useRef(null);

  const isEditMode = !!existingBadge;

  // 뱃지 색상 옵션 - 컬러로 표시
  const colorOptions = [
    { id: 'red', name: '기본', hex: '#ef4444' },
    { id: 'blue', name: '정보', hex: '#3b82f6' },
    { id: 'green', name: '완료', hex: '#22c55e' },
    { id: 'purple', name: '중요', hex: '#a855f7' },
    { id: 'orange', name: '주의', hex: '#f97316' },
    { id: 'gray', name: '참고', hex: '#6b7280' },
  ];

  // UI 컴포넌트 타입 옵션
  const uiTypeOptions = ['버튼', '입력필드', '테이블', '모달', '드롭다운', '체크박스', '라디오', '탭', '카드', '아이콘', '레이블', '기타'];
  const interactionOptions = ['클릭', '더블클릭', '호버', '입력', '선택', '드래그', '스크롤', '포커스', '제출', '기타'];

  // 자동 포커스 (제목 입력창에 먼저 포커스)
  React.useEffect(() => {
    if (labelInputRef.current) {
      labelInputRef.current.focus();
    }
  }, []);

  // Enter로 저장, ESC로 취소
  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && !e.shiftKey && !showDetails) {
      e.preventDefault();
      handleSave();
    }
    if (e.key === 'Escape') {
      onCancel();
    }
  };

  const handleSave = () => {
    if (!label.trim() && !description.trim() && !uiType && !interaction) return;

    const badgeData = {
      label: label.trim(),
      description: description.trim(),
      color: selectedColor,
      uiInfo: (uiType || interaction) ? {
        componentType: uiType || undefined,
        interaction: interaction || undefined,
      } : undefined,
    };
    onSave(badgeData);
  };

  // 입력창 위치 계산 (마우스 클릭 위치에 정확히 좌측 정렬)
  const getPopupStyle = () => {
    const style = {
      position: 'absolute',
      zIndex: 1000,
    };

    // absoluteX, absoluteY가 있으면 픽셀 좌표 사용 (좌측 정렬)
    if (position.absoluteX !== undefined && position.absoluteY !== undefined) {
      style.left = `${position.absoluteX}px`;
      style.top = `${position.absoluteY}px`;
    } else {
      // 레거시 비율 좌표 (중앙 정렬)
      if (position.x > 60) {
        style.right = `${100 - position.x}%`;
      } else {
        style.left = `${position.x}%`;
      }

      if (position.y > 50) {
        style.bottom = `${100 - position.y}%`;
      } else {
        style.top = `${position.y}%`;
      }
    }

    return style;
  };

  return (
    <div
      style={getPopupStyle()}
      className="bg-white rounded-xl shadow-2xl border-2 border-gray-500 w-80 overflow-hidden badge-input-popup"
      onClick={(e) => e.stopPropagation()}
    >
      {/* 헤더 - 와이어프레임 스타일 */}
      <div className="bg-gray-600 text-white px-3 py-2 flex items-center justify-between" style={{ backgroundColor: '#4b5563' }}>
        <div className="flex items-center gap-2">
          <span className="w-6 h-6 bg-white text-gray-700 rounded-full flex items-center justify-center font-bold text-sm">
            {number}
          </span>
          <span className="font-medium text-sm">{isEditMode ? '뱃지 수정' : '뱃지 추가'}</span>
        </div>
        <button onClick={onCancel} className="hover:bg-gray-700 rounded p-1">
          <X className="w-4 h-4" />
        </button>
      </div>

      {/* 입력 영역 */}
      <div className="p-3 space-y-3">
        {/* 기능 제목 */}
        <div>
          <label className="text-xs text-gray-600 mb-1 block">기능 제목</label>
          <input
            ref={labelInputRef}
            type="text"
            value={label}
            onChange={(e) => setLabel(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="예: 검색, 등록, 삭제, 목록 테이블..."
            className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-gray-500"
          />
        </div>

        {/* 기능 설명 */}
        <div>
          <label className="text-xs text-gray-600 mb-1 block">기능 설명</label>
          <textarea
            ref={inputRef}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="기능에 대한 상세 설명을 입력하세요..."
            className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-gray-500 resize-none"
            rows={3}
          />
        </div>

        {/* 색상 선택 */}
        <div className="badge-color-picker">
          <label className="text-xs text-gray-600 mb-1.5 block">뱃지 색상</label>
          <div className="flex gap-2">
            {colorOptions.map(color => (
              <button
                key={color.id}
                onClick={() => setSelectedColor(color.id)}
                className={`w-7 h-7 rounded-full transition-all ${selectedColor === color.id
                    ? 'ring-2 ring-offset-2 ring-gray-400 scale-110'
                    : 'hover:scale-105'
                  }`}
                title={color.name}
                style={{ backgroundColor: color.hex, filter: 'none', WebkitFilter: 'none' }}
              />
            ))}
          </div>
        </div>

        {/* 상세정보 토글 - 와이어프레임 스타일 */}
        <button
          onClick={() => setShowDetails(!showDetails)}
          className="w-full text-left text-xs text-gray-600 hover:text-gray-800 flex items-center gap-1"
        >
          <ChevronDown className={`w-3 h-3 transition-transform ${showDetails ? 'rotate-180' : ''}`} />
          {showDetails ? '상세정보 접기' : '+ 상세정보 추가 (UI 형태, 인터랙션)'}
        </button>

        {/* 상세정보 입력 - 와이어프레임 스타일 */}
        {showDetails && (
          <div className="space-y-2 p-2 bg-gray-50 rounded-lg">
            <div>
              <label className="text-xs text-gray-600 mb-1 block">UI 형태</label>
              <select
                value={uiType}
                onChange={(e) => setUiType(e.target.value)}
                className="w-full px-2 py-1.5 border rounded text-xs focus:ring-2 focus:ring-gray-500"
              >
                <option value="">선택...</option>
                {uiTypeOptions.map(opt => (
                  <option key={opt} value={opt}>{opt}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="text-xs text-gray-600 mb-1 block">인터랙션</label>
              <select
                value={interaction}
                onChange={(e) => setInteraction(e.target.value)}
                className="w-full px-2 py-1.5 border rounded text-xs focus:ring-2 focus:ring-gray-500"
              >
                <option value="">선택...</option>
                {interactionOptions.map(opt => (
                  <option key={opt} value={opt}>{opt}</option>
                ))}
              </select>
            </div>
          </div>
        )}

        {/* 버튼 영역 */}
        <div className="flex items-center justify-between pt-2 border-t">
          <p className="text-xs text-gray-400">
            {showDetails ? '' : 'Enter: 저장'}
          </p>
          <div className="flex gap-2">
            {isEditMode && onDelete && (
              <button
                onClick={() => onDelete(existingBadge.id)}
                className="px-3 py-1.5 text-xs text-red-600 hover:bg-red-50 rounded"
              >
                삭제
              </button>
            )}
            <button
              onClick={onCancel}
              className="px-3 py-1.5 text-xs text-gray-600 hover:bg-gray-100 rounded"
            >
              취소
            </button>
            <button
              onClick={handleSave}
              disabled={!description.trim() && !uiType && !interaction}
              className="px-3 py-1.5 text-xs bg-gray-600 text-white rounded hover:bg-gray-700 disabled:opacity-50"
            >
              {isEditMode ? '수정' : '저장'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════
// 기능정의문서 모달 컴포넌트 (화면별 상세 기능정의서)
// ═══════════════════════════════════════════════════════════════════
const FeatureDocumentModal = ({ isOpen, onClose, screenKey, screenName }) => {
  const [expandedSections, setExpandedSections] = useState({});
  const [expandedItems, setExpandedItems] = useState({});
  const [filterType, setFilterType] = useState('all'); // 'all', 'ui', 'function', 'data', 'interaction', 'state', 'validation'

  // 화면별 기능정의서 데이터 조회
  const featureDoc = getScreenFeatureDocument(screenKey);

  if (!isOpen) return null;

  // 필터 타입별 색상 - 와이어프레임 스타일: 그레이스케일
  const filterColors = {
    all: 'bg-gray-100 text-gray-700',
    ui: 'bg-gray-200 text-gray-800',
    function: 'bg-gray-300 text-gray-800',
    data: 'bg-gray-200 text-gray-700',
    interaction: 'bg-gray-300 text-gray-700',
    state: 'bg-gray-200 text-gray-800',
    validation: 'bg-gray-300 text-gray-800'
  };

  // 속성 유형별 색상 - 와이어프레임 스타일: 그레이스케일
  const propertyTypeColors = {
    ui: { bg: 'bg-gray-50', border: 'border-gray-300', text: 'text-gray-700', badge: 'bg-gray-200 text-gray-800' },
    function: { bg: 'bg-gray-100', border: 'border-gray-300', text: 'text-gray-700', badge: 'bg-gray-300 text-gray-800' },
    data: { bg: 'bg-gray-50', border: 'border-gray-300', text: 'text-gray-700', badge: 'bg-gray-200 text-gray-700' },
    interaction: { bg: 'bg-gray-100', border: 'border-gray-300', text: 'text-gray-700', badge: 'bg-gray-300 text-gray-700' },
    state: { bg: 'bg-gray-50', border: 'border-gray-300', text: 'text-gray-800', badge: 'bg-gray-200 text-gray-800' },
    validation: { bg: 'bg-gray-100', border: 'border-gray-300', text: 'text-gray-800', badge: 'bg-gray-300 text-gray-800' }
  };

  // 섹션 유형별 아이콘
  const sectionTypeIcons = {
    header: '📋',
    search: '🔍',
    table: '📊',
    form: '📝',
    modal: '🔲',
    button: '🔘',
    card: '🃏',
    tab: '📑',
    list: '📃',
    tree: '🌳'
  };

  // 항목 유형별 아이콘
  const itemTypeIcons = {
    button: '🔘',
    input: '✏️',
    select: '📋',
    checkbox: '☑️',
    'checkbox-group': '☑️',
    radio: '🔘',
    'table-column': '📊',
    'stat-card': '📈',
    label: '🏷️',
    'list-item': '•',
    'tree-node': '🌿',
    'modal-header': '🔲',
    content: '📄',
    card: '🃏',
    'tab-button': '📑'
  };

  const toggleSection = (sectionIndex) => {
    setExpandedSections(prev => ({
      ...prev,
      [sectionIndex]: !prev[sectionIndex]
    }));
  };

  const toggleItem = (sectionIndex, itemIndex) => {
    const key = `${sectionIndex}-${itemIndex}`;
    setExpandedItems(prev => ({
      ...prev,
      [key]: !prev[key]
    }));
  };

  // 필터링된 속성 반환
  const getFilteredProperties = (properties) => {
    if (filterType === 'all') return properties;
    return properties.filter(prop => prop.propertyType === filterType);
  };

  // 아이템에 필터에 맞는 속성이 있는지 확인
  const hasFilteredProperties = (item) => {
    if (filterType === 'all') return true;
    return item.properties?.some(prop => prop.propertyType === filterType);
  };

  return (
    <div className="fixed inset-0 bg-black/50 z-[9999] flex items-start justify-center pt-10 pb-10 overflow-y-auto">
      <div className="bg-white rounded-xl shadow-2xl w-[900px] max-h-[90vh] flex flex-col mx-4">
        {/* 헤더 - 와이어프레임 스타일 */}
        <div className="flex-shrink-0 px-6 py-4 border-b bg-gray-700 rounded-t-xl">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-xl font-bold text-white flex items-center gap-2">
                기능정의문서
              </h2>
              <p className="text-gray-300 text-sm mt-1">
                {featureDoc ? `${featureDoc.menuPath} > ${featureDoc.screenName}` : screenName || screenKey}
              </p>
            </div>
            <button
              onClick={onClose}
              className="p-2 rounded-lg hover:bg-gray-600 text-white transition-colors"
            >
              ✕
            </button>
          </div>
        </div>

        {/* 필터 탭 */}
        <div className="flex-shrink-0 px-6 py-3 border-b bg-gray-50">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="text-xs font-medium text-gray-500 mr-2">필터:</span>
            {[
              { key: 'all', label: '전체' },
              { key: 'ui', label: 'UI 표시' },
              { key: 'interaction', label: '인터랙션' },
              { key: 'function', label: '기능' },
              { key: 'state', label: '상태변화' },
              { key: 'data', label: '데이터' },
              { key: 'validation', label: '유효성검사' }
            ].map(filter => (
              <button
                key={filter.key}
                onClick={() => setFilterType(filter.key)}
                className={`px-3 py-1 rounded-full text-xs font-medium transition-colors ${filterType === filter.key
                    ? filterColors[filter.key] + ' ring-2 ring-offset-1 ring-gray-300'
                    : 'bg-white text-gray-500 hover:bg-gray-100 border'
                  }`}
              >
                {filter.label}
              </button>
            ))}
          </div>
        </div>

        {/* 본문 */}
        <div className="flex-1 overflow-y-auto p-6">
          {!featureDoc ? (
            <div className="text-center py-12">
              <BookOpen className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-600 mb-2">기능정의서가 없습니다</h3>
              <p className="text-sm text-gray-400">
                이 화면({screenKey})에 대한 기능정의서가 아직 작성되지 않았습니다.
              </p>
            </div>
          ) : (
            <div className="space-y-6">
              {/* 화면 설명 - 와이어프레임 스타일 */}
              {featureDoc.description && (
                <div className="p-4 bg-gray-100 rounded-lg border border-gray-300">
                  <p className="text-sm text-gray-800">{featureDoc.description}</p>
                </div>
              )}

              {/* 섹션 목록 */}
              {featureDoc.sections?.map((section, sectionIndex) => {
                // 필터에 맞는 아이템이 있는지 확인
                const hasFilteredItems = section.items?.some(item => hasFilteredProperties(item));
                if (filterType !== 'all' && !hasFilteredItems) return null;

                const isExpanded = expandedSections[sectionIndex] !== false; // 기본 펼침

                return (
                  <div key={sectionIndex} className="border rounded-lg overflow-hidden">
                    {/* 섹션 헤더 */}
                    <button
                      onClick={() => toggleSection(sectionIndex)}
                      className="w-full px-4 py-3 bg-gray-100 flex items-center justify-between hover:bg-gray-150 transition-colors"
                    >
                      <div className="flex items-center gap-2">
                        <span className="text-lg">{sectionTypeIcons[section.sectionType] || '📁'}</span>
                        <span className="font-bold text-gray-800">{section.sectionName}</span>
                        <span className="text-xs px-2 py-0.5 bg-gray-200 text-gray-600 rounded">
                          {section.sectionType}
                        </span>
                        <span className="text-xs text-gray-500">
                          ({section.items?.length || 0}개 항목)
                        </span>
                      </div>
                      <ChevronDown className={`w-5 h-5 text-gray-500 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />
                    </button>

                    {/* 항목 목록 */}
                    {isExpanded && (
                      <div className="divide-y">
                        {section.items?.map((item, itemIndex) => {
                          if (filterType !== 'all' && !hasFilteredProperties(item)) return null;

                          const itemKey = `${sectionIndex}-${itemIndex}`;
                          const isItemExpanded = expandedItems[itemKey] !== false; // 기본 펼침
                          const filteredProps = getFilteredProperties(item.properties || []);

                          return (
                            <div key={itemIndex} className="bg-white">
                              {/* 항목 헤더 */}
                              <button
                                onClick={() => toggleItem(sectionIndex, itemIndex)}
                                className="w-full px-4 py-2 flex items-center justify-between hover:bg-gray-50 transition-colors"
                              >
                                <div className="flex items-center gap-2">
                                  <span className="text-sm">{itemTypeIcons[item.itemType] || '•'}</span>
                                  <span className="font-medium text-gray-700">{item.itemName}</span>
                                  <span className="text-xs px-1.5 py-0.5 bg-gray-100 text-gray-500 rounded">
                                    {item.itemType}
                                  </span>
                                </div>
                                <div className="flex items-center gap-2">
                                  <span className="text-xs text-gray-400">
                                    {filteredProps.length}개 속성
                                  </span>
                                  <ChevronRight className={`w-4 h-4 text-gray-400 transition-transform ${isItemExpanded ? 'rotate-90' : ''}`} />
                                </div>
                              </button>

                              {/* 속성 목록 */}
                              {isItemExpanded && filteredProps.length > 0 && (
                                <div className="px-4 pb-3 pt-1 ml-6 space-y-2">
                                  {filteredProps.map((prop, propIndex) => {
                                    const colors = propertyTypeColors[prop.propertyType] || propertyTypeColors.ui;
                                    return (
                                      <div
                                        key={propIndex}
                                        className={`p-3 rounded-lg ${colors.bg} border ${colors.border}`}
                                      >
                                        <div className="flex items-start gap-2">
                                          <span className={`text-xs px-1.5 py-0.5 rounded ${colors.badge} font-medium flex-shrink-0`}>
                                            {prop.propertyType === 'ui' && 'UI'}
                                            {prop.propertyType === 'function' && '기능'}
                                            {prop.propertyType === 'data' && '데이터'}
                                            {prop.propertyType === 'interaction' && '인터랙션'}
                                            {prop.propertyType === 'state' && '상태'}
                                            {prop.propertyType === 'validation' && '검증'}
                                          </span>
                                          <div className="flex-1">
                                            <p className={`text-sm font-medium ${colors.text}`}>
                                              {prop.propertyName}
                                            </p>
                                            <p className="text-sm text-gray-600 mt-0.5">
                                              {prop.description}
                                            </p>
                                          </div>
                                        </div>
                                      </div>
                                    );
                                  })}
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                );
              })}

              {/* 상태 관리 섹션 - 와이어프레임 스타일 */}
              {featureDoc.stateManagement && featureDoc.stateManagement.length > 0 && (
                <div className="border rounded-lg overflow-hidden">
                  <div className="px-4 py-3 bg-gray-200 border-b border-gray-300">
                    <div className="flex items-center gap-2">
                      <span className="font-bold text-gray-800">상태 관리 (State)</span>
                    </div>
                  </div>
                  <div className="p-4 bg-white">
                    <div className="overflow-x-auto">
                      <table className="w-full text-sm">
                        <thead>
                          <tr className="bg-gray-100">
                            <th className="px-3 py-2 text-left font-medium text-gray-700 border-b">State 이름</th>
                            <th className="px-3 py-2 text-left font-medium text-gray-700 border-b">타입</th>
                            <th className="px-3 py-2 text-left font-medium text-gray-700 border-b">초기값</th>
                            <th className="px-3 py-2 text-left font-medium text-gray-700 border-b">설명</th>
                          </tr>
                        </thead>
                        <tbody>
                          {featureDoc.stateManagement.map((state, idx) => (
                            <tr key={idx} className="border-b last:border-0 hover:bg-gray-50">
                              <td className="px-3 py-2 font-mono text-gray-700">{state.stateName}</td>
                              <td className="px-3 py-2 text-gray-600">{state.type}</td>
                              <td className="px-3 py-2 font-mono text-xs text-gray-500">{state.initialValue}</td>
                              <td className="px-3 py-2 text-gray-700">{state.description}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              )}

              {/* 데이터 흐름 섹션 - 와이어프레임 스타일 */}
              {featureDoc.dataFlow && featureDoc.dataFlow.length > 0 && (
                <div className="border rounded-lg overflow-hidden">
                  <div className="px-4 py-3 bg-gray-200 border-b border-gray-300">
                    <div className="flex items-center gap-2">
                      <span className="font-bold text-gray-800">데이터 흐름 (Data Flow)</span>
                    </div>
                  </div>
                  <div className="p-4 bg-white space-y-3">
                    {featureDoc.dataFlow.map((flow, idx) => (
                      <div key={idx} className="flex items-start gap-3 p-3 bg-gray-100 rounded-lg">
                        <div className="flex-shrink-0 w-6 h-6 rounded-full bg-gray-300 flex items-center justify-center text-gray-700 font-bold text-xs">
                          {idx + 1}
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2 flex-wrap">
                            <span className="px-2 py-0.5 bg-gray-300 text-gray-700 rounded text-xs font-medium">
                              {flow.trigger}
                            </span>
                            <span className="text-gray-500">→</span>
                            <span className="font-mono text-sm text-gray-700">
                              {flow.action}
                            </span>
                          </div>
                          <p className="text-sm text-gray-600 mt-1">{flow.result}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* 푸터 */}
        <div className="flex-shrink-0 px-6 py-3 border-t bg-gray-50 flex items-center justify-between rounded-b-xl">
          <p className="text-xs text-gray-500">
            화면 키: <code className="px-1.5 py-0.5 bg-gray-200 rounded">{screenKey}</code>
          </p>
          <button
            onClick={onClose}
            className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors text-sm font-medium"
          >
            닫기
          </button>
        </div>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════════════
// 기능정의서 패널 컴포넌트
// ═══════════════════════════════════════════════════════════════════
const FeatureDescriptionPanel = ({
  isOpen,
  onClose,
  badges,
  selectedBadge,
  onSelectBadge,
  onUpdateBadge,
  onDeleteBadge,
  onAddBadge,
  isAddingBadge,
  setIsAddingBadge,
  badgeEditMode,
  setBadgeEditMode,
  screenName,
  screenPath = '',
  screenId = '',
  allBadges = {},
  onImportBadges,
  // 닉네임 관련
  userNickname,
  onChangeNickname,
  // 템플릿 로드 관련
  onLoadTemplate,
  currentScreenKey = '',
  hasTemplate = false,
  // 기능 추출 관련
  onExtractFeatures,
  // 댓글 관련
  onAddComment,
  onDeleteComment,
  // 어드민 모드
  isAdmin = false,
}) => {
  const fileInputRef = React.useRef(null);
  const [showBackupMenu, setShowBackupMenu] = useState(false);
  const [newComment, setNewComment] = useState('');
  const [expandedComments, setExpandedComments] = useState({}); // 뱃지별 댓글 아코디언 상태
  const [commentInputs, setCommentInputs] = useState({}); // 뱃지별 댓글 입력값
  const [editingBadgeId, setEditingBadgeId] = useState(null); // 인라인 수정 중인 뱃지 ID
  const [editFormData, setEditFormData] = useState({}); // 수정 폼 데이터
  const [lastSaved, setLastSaved] = useState(() => {
    return localStorage.getItem('featureBadges_lastSaved') || null;
  });
  const [autoBackupEnabled, setAutoBackupEnabled] = useState(() => {
    return localStorage.getItem('featureBadges_autoBackup') === 'true';
  });
  const [lastAutoBackup, setLastAutoBackup] = useState(() => {
    return localStorage.getItem('featureBadges_lastAutoBackup') || null;
  });

  // 버전 관리 상태
  const [showVersionModal, setShowVersionModal] = useState(false);
  const [showVersionHistory, setShowVersionHistory] = useState(false);
  const [versionChangeLog, setVersionChangeLog] = useState('');

  // 기능정의문서 모달 상태
  const [showFeatureDocModal, setShowFeatureDocModal] = useState(false);

  // 현재 화면에 기능정의서가 있는지 확인
  const hasFeatureDoc = !!getScreenFeatureDocument(currentScreenKey);
  const [screenVersions, setScreenVersions] = useState(() => {
    const saved = localStorage.getItem('featureDescriptionVersions');
    return saved ? JSON.parse(saved) : {};
  });

  // 현재 화면의 버전 정보 가져오기
  const currentVersion = screenVersions[currentScreenKey] || { version: '1.0.0', history: [] };

  // 버전 업그레이드 함수
  const upgradeVersion = (type = 'patch') => {
    const [major, minor, patch] = currentVersion.version.split('.').map(Number);
    let newVersion;

    if (type === 'major') {
      newVersion = `${major + 1}.0.0`;
    } else if (type === 'minor') {
      newVersion = `${major}.${minor + 1}.0`;
    } else {
      newVersion = `${major}.${minor}.${patch + 1}`;
    }

    const historyEntry = {
      version: newVersion,
      previousVersion: currentVersion.version,
      changeLog: versionChangeLog,
      updatedAt: new Date().toISOString(),
      updatedBy: userNickname || '익명',
      badgeCount: badges.length
    };

    const updatedVersionData = {
      version: newVersion,
      history: [historyEntry, ...(currentVersion.history || [])]
    };

    const updatedVersions = {
      ...screenVersions,
      [currentScreenKey]: updatedVersionData
    };

    setScreenVersions(updatedVersions);
    localStorage.setItem('featureDescriptionVersions', JSON.stringify(updatedVersions));
    setVersionChangeLog('');
    setShowVersionModal(false);
  };

  // 자동 변경 이력 저장 (뱃지 추가/수정/삭제 시)
  const prevBadgesRef = React.useRef(badges);
  const autoSaveTimeoutRef = React.useRef(null);

  React.useEffect(() => {
    // 초기 로드 시 또는 화면 전환 시 이전 상태 업데이트
    if (!currentScreenKey) return;

    const prevBadges = prevBadgesRef.current;
    const prevCount = prevBadges?.length || 0;
    const currentCount = badges?.length || 0;

    // 변경 감지 (뱃지 수 변경 또는 내용 변경)
    const hasChanged = prevCount !== currentCount ||
      JSON.stringify(prevBadges) !== JSON.stringify(badges);

    if (hasChanged && prevBadges !== badges) {
      // 디바운스: 연속 변경 시 마지막 변경만 저장
      if (autoSaveTimeoutRef.current) {
        clearTimeout(autoSaveTimeoutRef.current);
      }

      autoSaveTimeoutRef.current = setTimeout(() => {
        // 변경 유형 감지
        let changeType = '';
        let changeDetail = '';

        if (currentCount > prevCount) {
          const addedCount = currentCount - prevCount;
          changeType = '뱃지 추가';
          changeDetail = `${addedCount}개 뱃지 추가됨`;
        } else if (currentCount < prevCount) {
          const removedCount = prevCount - currentCount;
          changeType = '뱃지 삭제';
          changeDetail = `${removedCount}개 뱃지 삭제됨`;
        } else {
          changeType = '뱃지 수정';
          changeDetail = '뱃지 내용 수정됨';
        }

        // 자동 이력 저장 (패치 버전은 올리지 않고 이력만 추가)
        const autoHistoryEntry = {
          version: currentVersion.version,
          previousVersion: currentVersion.version,
          changeLog: `[자동저장] ${changeType}: ${changeDetail}`,
          updatedAt: new Date().toISOString(),
          updatedBy: userNickname || 'Claude',
          badgeCount: currentCount,
          isAutoSave: true
        };

        const updatedVersionData = {
          ...currentVersion,
          lastModified: new Date().toISOString(),
          history: [autoHistoryEntry, ...(currentVersion.history || []).slice(0, 49)] // 최대 50개 이력 유지
        };

        const updatedVersions = {
          ...screenVersions,
          [currentScreenKey]: updatedVersionData
        };

        setScreenVersions(updatedVersions);
        localStorage.setItem('featureDescriptionVersions', JSON.stringify(updatedVersions));
      }, 2000); // 2초 디바운스
    }

    prevBadgesRef.current = badges;

    return () => {
      if (autoSaveTimeoutRef.current) {
        clearTimeout(autoSaveTimeoutRef.current);
      }
    };
  }, [badges, currentScreenKey, currentVersion, screenVersions, userNickname]);

  // 비밀번호 확인 후 삭제
  const DELETE_PASSWORD = '1234';
  const handleDeleteWithPassword = (badgeId) => {
    const password = window.prompt('삭제하려면 비밀번호를 입력하세요:');
    if (password === null) return; // 취소
    if (password === DELETE_PASSWORD) {
      onDeleteBadge(badgeId);
      setEditingBadgeId(null);
    } else {
      alert('비밀번호가 올바르지 않습니다.');
    }
  };

  // 인라인 수정 시작
  const startEditing = (badge) => {
    setEditingBadgeId(badge.id);
    setEditFormData({
      label: badge.label || '',
      description: badge.description || '',
      color: badge.color || 'red',
      uiInfo: badge.uiInfo || {},
      funcInfo: badge.funcInfo || {},
      dataInfo: badge.dataInfo || {},
    });
  };

  // 인라인 수정 저장
  const saveEditing = () => {
    if (editingBadgeId && editFormData.label?.trim()) {
      onUpdateBadge(editingBadgeId, editFormData);
      setEditingBadgeId(null);
      setEditFormData({});
    }
  };

  // 인라인 수정 취소
  const cancelEditing = () => {
    setEditingBadgeId(null);
    setEditFormData({});
  };

  // 자동 백업 실행 함수 (로컬 파일 시스템 사용)
  const performAutoBackup = React.useCallback(async () => {
    if (Object.keys(allBadges).length === 0) return; // 데이터가 없으면 백업 안함

    try {
      await createBackup(allBadges, 'auto');
      const now = new Date().toISOString();
      setLastAutoBackup(now);
    } catch (error) {
      console.error('자동 백업 실패:', error);
    }
  }, [allBadges]);

  // 자동 백업 체크 - 앱 로드 시 하루가 지났으면 자동 백업
  React.useEffect(() => {
    if (!autoBackupEnabled) return;
    if (Object.keys(allBadges).length === 0) return;

    const today = new Date().toISOString().slice(0, 10);
    const lastBackupDate = lastAutoBackup ? lastAutoBackup.slice(0, 10) : null;

    // 오늘 이미 백업했으면 스킵
    if (lastBackupDate === today) return;

    // 약간의 지연 후 자동 백업 실행 (앱 로드 완료 후)
    const timer = setTimeout(() => {
      performAutoBackup();
    }, 2000);

    return () => clearTimeout(timer);
  }, [autoBackupEnabled, lastAutoBackup, allBadges, performAutoBackup]);

  // 자동 백업 토글
  const toggleAutoBackup = () => {
    const newValue = !autoBackupEnabled;
    setAutoBackupEnabled(newValue);
    localStorage.setItem('featureBadges_autoBackup', newValue.toString());
    if (newValue) {
      // 자동 백업 활성화 시 즉시 백업 실행
      performAutoBackup();
    }
  };

  // 전체 뱃지 내보내기 (로컬 파일 다운로드)
  const exportBadges = async () => {
    try {
      await createBackup(allBadges, 'manual');
      setShowBackupMenu(false);
      alert('✅ 백업 파일이 다운로드되었습니다.');
    } catch (error) {
      console.error('백업 실패:', error);
      alert('❌ 백업 중 오류가 발생했습니다.');
    }
  };

  // JSON 파일에서 뱃지 가져오기 (로컬 파일 시스템 사용)
  const importBadges = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    try {
      const data = await importFromFile(file);

      if (data.badges) {
        const confirmImport = window.confirm(
          `기존 데이터를 백업 파일로 교체하시겠습니까?\n\n` +
          `백업 파일 정보:\n` +
          `- 내보낸 날짜: ${data.exportedAt || data.metadata?.lastModified ? new Date(data.exportedAt || data.metadata.lastModified).toLocaleString() : '알 수 없음'}\n` +
          `- 화면 수: ${Object.keys(data.badges).length}개\n` +
          `- 전체 뱃지 수: ${Object.values(data.badges).flat().length}개`
        );

        if (confirmImport) {
          onImportBadges(data.badges);
          const now = new Date().toISOString();
          setBadgeMetadata(prev => ({
            ...prev,
            lastModified: now,
            author: userNickname || 'system',
            version: data.metadata?.version || prev.version
          }));
          setLastSaved(now);
          alert('✅ 백업 파일을 성공적으로 불러왔습니다!');
        }
      } else {
        alert('올바른 백업 파일 형식이 아닙니다.');
      }
    } catch (err) {
      alert('파일을 읽는 중 오류가 발생했습니다: ' + err.message);
    }

    event.target.value = ''; // 같은 파일 다시 선택 가능하도록
    setShowBackupMenu(false);
  };

  // 수동 저장 (로컬 JSON 파일로 다운로드)
  const manualSave = async () => {
    try {
      const success = await saveFeatureBadges(allBadges, {
        version: badgeMetadata.version,
        author: userNickname || 'system',
        description: '기능정의서 수동 저장'
      });

      if (success) {
        const now = new Date().toISOString();
        setBadgeMetadata(prev => ({ ...prev, lastModified: now, author: userNickname || 'system' }));
        setLastSaved(now);
        setShowBackupMenu(false);
        alert('✅ 파일이 다운로드되었습니다.\npublic/data/ 폴더에 저장하세요.');
      } else {
        alert('❌ 저장에 실패했습니다.');
      }
    } catch (error) {
      console.error('저장 오류:', error);
      alert('❌ 저장 중 오류가 발생했습니다.');
    }
  };

  // 전체 뱃지 통계
  const totalScreens = Object.keys(allBadges).length;
  const totalBadges = Object.values(allBadges).flat().length;

  // 아코디언 열림 상태
  const [expandedSections, setExpandedSections] = useState({
    uiInfo: false,
    funcInfo: false,
    dataInfo: false,
  });

  // 구조화된 뱃지 데이터
  const [newBadge, setNewBadge] = useState({
    label: '',
    color: 'blue',
    x: 50,
    y: 50,
    description: '', // 자유 텍스트 설명
    // 구조화된 정보
    uiInfo: {
      componentType: '',    // 버튼, 입력필드, 테이블, 모달 등
      position: '',         // 상단, 좌측, 중앙 등
      interaction: '',      // 클릭, 입력, 선택, 드래그 등
      style: '',            // 스타일 특징
    },
    funcInfo: {
      purpose: '',          // 기능 목적
      trigger: '',          // 실행 조건
      process: '',          // 처리 과정
      result: '',           // 결과/출력
      validation: '',       // 유효성 검사
    },
    dataInfo: {
      source: '',           // 데이터 출처 (API, State, DB)
      endpoint: '',         // API 엔드포인트
      method: '',           // GET, POST, PUT, DELETE
      fields: '',           // 관련 필드
      relatedTable: '',     // 관련 테이블/엔티티
    },
  });

  // 아코디언 토글
  const toggleSection = (section) => {
    setExpandedSections(prev => ({
      ...prev,
      [section]: !prev[section]
    }));
  };

  // 뱃지 색상 - 컬러로 표시
  const badgeColors = [
    { id: 'red', bg: 'bg-red-500', text: 'text-white', label: '기본', hex: '#ef4444' },
    { id: 'blue', bg: 'bg-blue-500', text: 'text-white', label: '정보', hex: '#3b82f6' },
    { id: 'green', bg: 'bg-green-500', text: 'text-white', label: '완료', hex: '#22c55e' },
    { id: 'purple', bg: 'bg-purple-500', text: 'text-white', label: '중요', hex: '#a855f7' },
    { id: 'orange', bg: 'bg-orange-500', text: 'text-white', label: '주의', hex: '#f97316' },
    { id: 'gray', bg: 'bg-gray-500', text: 'text-white', label: '참고', hex: '#6b7280' },
  ];

  // UI 컴포넌트 타입 옵션
  const componentTypes = ['버튼', '입력필드', '셀렉트박스', '테이블', '모달', '탭', '카드', '아이콘', '라벨', '링크', '체크박스', '라디오', '기타'];
  const interactionTypes = ['클릭', '더블클릭', '입력', '선택', '드래그', '호버', '포커스', '스크롤', '키보드', '자동'];
  const dataSourceTypes = ['API 호출', 'State 관리', 'Props 전달', 'LocalStorage', 'URL 파라미터', '하드코딩', '계산값'];
  const httpMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];

  const getColorClasses = (colorId) => {
    const color = badgeColors.find(c => c.id === colorId) || badgeColors[0];
    return `${color.bg} ${color.text}`;
  };

  // 뱃지 색상 hex 값 반환 (인라인 스타일용)
  const getColorHex = (colorId) => {
    const color = badgeColors.find(c => c.id === colorId) || badgeColors[0];
    return color.hex;
  };

  // 뱃지 추가 시 구조화된 설명 생성
  const generateDescription = (badge) => {
    let desc = '';

    // 자유 텍스트 설명이 있으면 먼저 추가
    if (badge.description) {
      desc += badge.description;
    }

    // UI 정보
    if (badge.uiInfo.componentType || badge.uiInfo.interaction) {
      if (desc) desc += '\n\n';
      desc += `【UI 정보】\n`;
      if (badge.uiInfo.componentType) desc += `• 컴포넌트: ${badge.uiInfo.componentType}\n`;
      if (badge.uiInfo.position) desc += `• 위치: ${badge.uiInfo.position}\n`;
      if (badge.uiInfo.interaction) desc += `• 인터랙션: ${badge.uiInfo.interaction}\n`;
      if (badge.uiInfo.style) desc += `• 스타일: ${badge.uiInfo.style}\n`;
    }

    // 기능 정보
    if (badge.funcInfo.purpose || badge.funcInfo.process) {
      if (desc) desc += '\n\n';
      desc += `【기능 정보】\n`;
      if (badge.funcInfo.purpose) desc += `• 목적: ${badge.funcInfo.purpose}\n`;
      if (badge.funcInfo.trigger) desc += `• 실행조건: ${badge.funcInfo.trigger}\n`;
      if (badge.funcInfo.process) desc += `• 처리과정: ${badge.funcInfo.process}\n`;
      if (badge.funcInfo.result) desc += `• 결과: ${badge.funcInfo.result}\n`;
      if (badge.funcInfo.validation) desc += `• 유효성검사: ${badge.funcInfo.validation}\n`;
    }

    // 데이터 연동 정보
    if (badge.dataInfo.source || badge.dataInfo.endpoint) {
      if (desc) desc += '\n\n';
      desc += `【데이터 연동】\n`;
      if (badge.dataInfo.source) desc += `• 데이터출처: ${badge.dataInfo.source}\n`;
      if (badge.dataInfo.endpoint) desc += `• API: ${badge.dataInfo.method ? badge.dataInfo.method + ' ' : ''}${badge.dataInfo.endpoint}\n`;
      if (badge.dataInfo.fields) desc += `• 필드: ${badge.dataInfo.fields}\n`;
      if (badge.dataInfo.relatedTable) desc += `• 관련테이블: ${badge.dataInfo.relatedTable}\n`;
    }

    return desc.trim() || '설명 없음';
  };

  const resetNewBadge = () => {
    setNewBadge({
      label: '', color: 'blue', x: 50, y: 50,
      description: '',
      uiInfo: { componentType: '', position: '', interaction: '', style: '' },
      funcInfo: { purpose: '', trigger: '', process: '', result: '', validation: '' },
      dataInfo: { source: '', endpoint: '', method: '', fields: '', relatedTable: '' },
    });
    setExpandedSections({ uiInfo: false, funcInfo: false, dataInfo: false });
  };

  if (!isOpen) return null;

  return (
    <div className="w-full bg-white flex flex-col h-full overflow-hidden border-l-2 border-gray-400">
      {/* 숨겨진 파일 입력 */}
      <input
        type="file"
        ref={fileInputRef}
        onChange={importBadges}
        accept=".json"
        className="hidden"
      />

      {/* 헤더 - 심플하고 명확하게 */}
      <div className="flex-shrink-0 border-b-2 border-gray-300 bg-white">
        <div className="px-4 py-3 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <h2 className="font-bold text-black text-base">
              기능정의서
            </h2>
            <span className="px-2 py-0.5 bg-gray-800 text-white rounded text-xs font-medium">
              v{currentVersion.version}
            </span>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setShowBackupMenu(!showBackupMenu)}
              className="p-1.5 rounded hover:bg-gray-100 text-gray-700"
              title="백업/복원"
            >
              <Database className="w-4 h-4" />
            </button>
            <button
              onClick={onClose}
              className="p-1.5 rounded hover:bg-gray-100 text-gray-700 font-bold text-lg"
              title="패널 닫기"
            >
              ✕
            </button>
          </div>
        </div>

        {/* 백업 드롭다운 메뉴 */}
        {showBackupMenu && (
          <div className="absolute top-16 right-2 w-52 bg-white rounded-lg shadow-xl border-2 border-gray-300 z-50">
            <div className="p-3 border-b border-gray-200 bg-gray-50">
              <p className="text-sm text-black font-medium">
                {totalScreens}개 화면 · {totalBadges}개 뱃지
              </p>
            </div>
            <div className="p-2">
              <button
                onClick={manualSave}
                className="w-full px-3 py-2 text-left text-sm text-black hover:bg-gray-100 rounded flex items-center gap-2"
              >
                <Save className="w-4 h-4 text-gray-700" />
                저장
              </button>
              <button
                onClick={exportBadges}
                className="w-full px-3 py-2 text-left text-sm text-black hover:bg-gray-100 rounded flex items-center gap-2"
              >
                <Download className="w-4 h-4 text-gray-700" />
                내보내기
              </button>
              <button
                onClick={() => fileInputRef.current?.click()}
                className="w-full px-3 py-2 text-left text-sm text-black hover:bg-gray-100 rounded flex items-center gap-2"
              >
                <Upload className="w-4 h-4 text-gray-700" />
                가져오기
              </button>
            </div>
          </div>
        )}
      </div>

      {/* 뱃지 목록 */}
      <div className="flex-1 overflow-y-auto p-4">
        {badges.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            <p className="text-sm font-medium">등록된 기능 설명이 없습니다</p>
            <p className="text-xs mt-2">화면에서 C키로 추가하세요</p>
          </div>
        ) : (
          <div className="space-y-3">
            {badges.map((badge, index) => (
              <div
                key={badge.id}
                className={`rounded-lg border-2 transition-all ${editingBadgeId === badge.id
                    ? 'border-blue-500 bg-blue-50'
                    : 'border-gray-300 hover:border-gray-500 bg-white'
                  }`}
              >
                {/* 수정 모드 */}
                {editingBadgeId === badge.id ? (
                  <div className="p-3" onClick={(e) => e.stopPropagation()}>
                    {/* 헤더 */}
                    <div className="flex items-center gap-2 mb-3">
                      <span
                        className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0"
                        style={{ backgroundColor: badgeColors.find(c => c.id === editFormData.color)?.hex || '#ef4444', color: '#ffffff', filter: 'none' }}
                      >
                        {index + 1}
                      </span>
                      <span className="text-sm font-bold text-black">수정 중</span>
                      <div className="flex-1" />
                      <button onClick={cancelEditing} className="text-gray-500 hover:text-black text-lg font-bold">✕</button>
                    </div>

                    {/* 기능명 */}
                    <div className="mb-2">
                      <label className="text-xs text-gray-600 mb-1 block">기능명 *</label>
                      <input
                        type="text"
                        value={editFormData.label || ''}
                        onChange={(e) => setEditFormData(prev => ({ ...prev, label: e.target.value }))}
                        className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                        placeholder="기능명을 입력하세요"
                      />
                    </div>

                    {/* 설명 */}
                    <div className="mb-2">
                      <label className="text-xs text-gray-600 mb-1 block">설명</label>
                      <textarea
                        value={editFormData.description || ''}
                        onChange={(e) => setEditFormData(prev => ({ ...prev, description: e.target.value }))}
                        className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-blue-500 resize-none"
                        rows={3}
                        placeholder="기능 설명을 입력하세요"
                      />
                    </div>

                    {/* 색상 선택 */}
                    <div className="mb-3">
                      <label className="text-xs text-gray-600 mb-1 block">색상</label>
                      <div className="flex gap-2">
                        {badgeColors.map(color => (
                          <button
                            key={color.id}
                            onClick={() => setEditFormData(prev => ({ ...prev, color: color.id }))}
                            className={`w-6 h-6 rounded-full ${editFormData.color === color.id ? 'ring-2 ring-offset-1 ring-gray-600' : ''}`}
                            style={{ backgroundColor: color.hex, filter: 'none' }}
                            title={color.label}
                          />
                        ))}
                      </div>
                    </div>

                    {/* 저장/취소 버튼 */}
                    <div className="flex gap-2">
                      <button
                        onClick={saveEditing}
                        disabled={!editFormData.label?.trim()}
                        className="flex-1 py-1.5 bg-gray-800 text-white rounded text-sm font-medium hover:bg-gray-900 disabled:opacity-50"
                      >
                        저장
                      </button>
                      <button
                        onClick={() => handleDeleteWithPassword(badge.id)}
                        className="px-3 py-1.5 text-red-600 border border-red-300 rounded text-sm hover:bg-red-50"
                      >
                        삭제
                      </button>
                      <button
                        onClick={cancelEditing}
                        className="px-3 py-1.5 border border-gray-300 rounded text-sm hover:bg-gray-100"
                      >
                        취소
                      </button>
                    </div>
                  </div>
                ) : (
                  /* 일반 모드 */
                  <div className="p-3 cursor-pointer" onClick={() => startEditing(badge)}>
                    {/* 뱃지 번호 + 이름 + 수정/삭제 버튼 */}
                    <div className="flex items-center gap-2">
                      {/* 뱃지 번호 */}
                      <span
                        className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0"
                        style={{ backgroundColor: badgeColors.find(c => c.id === badge.color)?.hex || '#ef4444', color: '#ffffff', filter: 'none' }}
                      >
                        {index + 1}
                      </span>
                      {/* 기능명 - 자동 확장 (여러 줄 가능) */}
                      <span className="flex-1 text-sm font-semibold text-black break-words">
                        {badge.label || '(제목없음)'}
                      </span>
                      {/* 수정/삭제 버튼 */}
                      {(isAdmin || badge.author === userNickname) && (
                        <div className="flex items-center gap-1 flex-shrink-0">
                          <button
                            onClick={(e) => { e.stopPropagation(); startEditing(badge); }}
                            className="p-1.5 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded"
                            title="수정"
                          >
                            <Edit3 className="w-4 h-4" />
                          </button>
                          <button
                            onClick={(e) => { e.stopPropagation(); handleDeleteWithPassword(badge.id); }}
                            className="p-1.5 text-gray-500 hover:text-red-600 hover:bg-red-50 rounded"
                            title="삭제"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      )}
                    </div>
                    {/* 설명 미리보기 - 자동 확장 (모든 내용 표시) */}
                    {badge.description && (
                      <p className="text-sm text-gray-700 mt-2 pl-8 whitespace-pre-wrap break-words">{badge.description}</p>
                    )}
                    {/* 작성자 정보 */}
                    {badge.author && (
                      <div className="flex items-center gap-2 mt-2 pl-8 text-xs text-gray-500">
                        <span>{badge.author}</span>
                        {badge.createdAt && (
                          <>
                            <span>·</span>
                            <span>{new Date(badge.createdAt).toLocaleDateString()}</span>
                          </>
                        )}
                      </div>
                    )}
                  </div>
                )}

                {/* 댓글 - 심플화 */}
                {badge.comments && badge.comments.length > 0 && (
                  <div className="mt-2 pl-8">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setExpandedComments(prev => ({
                          ...prev,
                          [badge.id]: !prev[badge.id]
                        }));
                      }}
                      className="flex items-center gap-1 text-xs text-gray-600 hover:text-black"
                    >
                      <span className={`transition-transform ${expandedComments[badge.id] ? 'rotate-90' : ''}`}>▶</span>
                      <span>댓글 {badge.comments.length}개</span>
                    </button>

                    {/* 댓글 목록 */}
                    {expandedComments[badge.id] && (
                      <div className="mt-2 space-y-2" onClick={(e) => e.stopPropagation()}>
                        {badge.comments.map((comment, idx) => (
                          <div key={comment.id || idx} className="p-2 bg-gray-50 border border-gray-200 rounded text-xs">
                            <div className="flex items-start justify-between gap-2">
                              <p className="text-gray-800 flex-1">{comment.text}</p>
                              {onDeleteComment && (isAdmin || comment.author === userNickname) && (
                                <button
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    onDeleteComment(badge.id, comment.id);
                                  }}
                                  className="text-gray-400 hover:text-red-500 flex-shrink-0 text-lg"
                                  title="삭제"
                                >
                                  ×
                                </button>
                              )}
                            </div>
                            <div className="text-xs text-gray-500 mt-1">
                              {comment.author || '익명'} · {comment.createdAt ? new Date(comment.createdAt).toLocaleDateString('ko-KR') : ''}
                            </div>
                          </div>
                        ))}

                        {/* 댓글 입력 */}
                        {onAddComment && (
                          <div className="flex gap-2 mt-2">
                            <input
                              type="text"
                              value={commentInputs[badge.id] || ''}
                              onChange={(e) => setCommentInputs(prev => ({ ...prev, [badge.id]: e.target.value }))}
                              onKeyDown={(e) => {
                                if (e.key === 'Enter' && (commentInputs[badge.id] || '').trim()) {
                                  e.stopPropagation();
                                  onAddComment(badge.id, commentInputs[badge.id].trim());
                                  setCommentInputs(prev => ({ ...prev, [badge.id]: '' }));
                                }
                              }}
                              onClick={(e) => e.stopPropagation()}
                              placeholder="댓글 입력..."
                              className="flex-1 px-2 py-1.5 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-gray-500 focus:border-gray-500"
                            />
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                if ((commentInputs[badge.id] || '').trim()) {
                                  onAddComment(badge.id, commentInputs[badge.id].trim());
                                  setCommentInputs(prev => ({ ...prev, [badge.id]: '' }));
                                }
                              }}
                              disabled={!(commentInputs[badge.id] || '').trim()}
                              className="px-3 py-1.5 text-xs bg-gray-800 text-white rounded hover:bg-gray-900 disabled:opacity-50"
                            >
                              등록
                            </button>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 사용자 정보 */}
      {userNickname && (
        <div className="flex-shrink-0 px-4 py-3 border-t-2 border-gray-300 bg-gray-50">
          <div className="flex items-center gap-3">
            <div className="w-7 h-7 rounded-full bg-gray-700 flex items-center justify-center text-white text-sm font-bold">
              {userNickname.charAt(0).toUpperCase()}
            </div>
            <span className="text-sm font-medium text-black">{userNickname}</span>
            <button
              onClick={onChangeNickname}
              className="text-xs text-gray-500 hover:text-black"
              title="닉네임 변경"
            >
              변경
            </button>
          </div>
        </div>
      )}

      {/* 뱃지 추가 폼 - 심플화 */}
      {isAddingBadge && (
        <div className="flex-shrink-0 p-4 border-t-2 border-gray-300 bg-white">
          <div className="space-y-4 max-h-[60vh] overflow-y-auto">
            {/* 기본 정보 */}
            <div className="space-y-3">
              <label className="text-sm font-bold text-black">기본 정보</label>
              <input
                type="text"
                placeholder="기능 이름 (필수)"
                value={newBadge.label}
                onChange={(e) => setNewBadge(prev => ({ ...prev, label: e.target.value }))}
                className="w-full px-3 py-2.5 border-2 border-gray-300 rounded-lg text-sm text-black focus:ring-2 focus:ring-gray-500 focus:border-gray-500"
              />
              <div className="flex items-center gap-3">
                <span className="text-sm text-gray-600">색상</span>
                {badgeColors.map(color => (
                  <button
                    key={color.id}
                    onClick={() => setNewBadge(prev => ({ ...prev, color: color.id }))}
                    className={`w-7 h-7 rounded-full ${newBadge.color === color.id ? 'ring-2 ring-offset-2 ring-gray-600' : ''
                      }`}
                    style={{ backgroundColor: color.hex, filter: 'none' }}
                    title={color.label}
                  />
                ))}
              </div>
            </div>

            {/* 설명 */}
            <div className="space-y-2">
              <label className="text-sm font-bold text-black">설명</label>
              <textarea
                placeholder="기능에 대한 설명을 작성하세요..."
                value={newBadge.description}
                onChange={(e) => setNewBadge(prev => ({ ...prev, description: e.target.value }))}
                className="w-full px-3 py-2.5 border-2 border-gray-300 rounded-lg text-sm text-black focus:ring-2 focus:ring-gray-500 focus:border-gray-500 resize-none"
                rows={4}
              />
            </div>

            {/* UI 정보 섹션 */}
            <div className="border-2 border-gray-300 rounded-lg overflow-hidden">
              <button
                onClick={() => toggleSection('uiInfo')}
                className="w-full px-3 py-2.5 bg-gray-100 flex items-center justify-between hover:bg-gray-200"
              >
                <span className="text-sm font-bold text-black">UI 정보</span>
                <span className="text-gray-600 font-bold">{expandedSections.uiInfo ? '−' : '+'}</span>
              </button>
              {expandedSections.uiInfo && (
                <div className="p-3 bg-white space-y-3 border-t border-gray-200">
                  <div className="grid grid-cols-2 gap-3">
                    <select
                      value={newBadge.uiInfo.componentType}
                      onChange={(e) => setNewBadge(prev => ({ ...prev, uiInfo: { ...prev.uiInfo, componentType: e.target.value } }))}
                      className="px-3 py-2 border border-gray-300 rounded text-sm text-black bg-white"
                    >
                      <option value="">컴포넌트 타입</option>
                      {componentTypes.map(t => <option key={t} value={t}>{t}</option>)}
                    </select>
                    <select
                      value={newBadge.uiInfo.interaction}
                      onChange={(e) => setNewBadge(prev => ({ ...prev, uiInfo: { ...prev.uiInfo, interaction: e.target.value } }))}
                      className="px-3 py-2 border border-gray-300 rounded text-sm text-black bg-white"
                    >
                      <option value="">인터랙션</option>
                      {interactionTypes.map(t => <option key={t} value={t}>{t}</option>)}
                    </select>
                  </div>
                  <input
                    type="text"
                    placeholder="위치"
                    value={newBadge.uiInfo.position}
                    onChange={(e) => setNewBadge(prev => ({ ...prev, uiInfo: { ...prev.uiInfo, position: e.target.value } }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded text-sm text-black"
                  />
                  <input
                    type="text"
                    placeholder="스타일"
                    value={newBadge.uiInfo.style}
                    onChange={(e) => setNewBadge(prev => ({ ...prev, uiInfo: { ...prev.uiInfo, style: e.target.value } }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded text-sm text-black"
                  />
                </div>
              )}
            </div>

            {/* 기능 정보 섹션 */}
            <div className="border-2 border-gray-300 rounded-lg overflow-hidden">
              <button
                onClick={() => toggleSection('funcInfo')}
                className="w-full px-3 py-2.5 bg-gray-100 flex items-center justify-between hover:bg-gray-200"
              >
                <span className="text-sm font-bold text-black">기능 정보</span>
                <span className="text-gray-600 font-bold">{expandedSections.funcInfo ? '−' : '+'}</span>
              </button>
              {expandedSections.funcInfo && (
                <div className="p-3 bg-white space-y-3 border-t border-gray-200">
                  <input
                    type="text"
                    placeholder="기능 목적"
                    value={newBadge.funcInfo.purpose}
                    onChange={(e) => setNewBadge(prev => ({ ...prev, funcInfo: { ...prev.funcInfo, purpose: e.target.value } }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded text-sm text-black"
                  />
                  <input
                    type="text"
                    placeholder="실행 조건"
                    value={newBadge.funcInfo.trigger}
                    onChange={(e) => setNewBadge(prev => ({ ...prev, funcInfo: { ...prev.funcInfo, trigger: e.target.value } }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded text-sm text-black"
                  />
                  <textarea
                    placeholder="처리 과정"
                    value={newBadge.funcInfo.process}
                    onChange={(e) => setNewBadge(prev => ({ ...prev, funcInfo: { ...prev.funcInfo, process: e.target.value } }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded text-sm text-black resize-none"
                    rows={2}
                  />
                  <input
                    type="text"
                    placeholder="결과/출력"
                    value={newBadge.funcInfo.result}
                    onChange={(e) => setNewBadge(prev => ({ ...prev, funcInfo: { ...prev.funcInfo, result: e.target.value } }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded text-sm text-black"
                  />
                  <input
                    type="text"
                    placeholder="유효성 검사"
                    value={newBadge.funcInfo.validation}
                    onChange={(e) => setNewBadge(prev => ({ ...prev, funcInfo: { ...prev.funcInfo, validation: e.target.value } }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded text-sm text-black"
                  />
                </div>
              )}
            </div>

            {/* 데이터 연동 섹션 */}
            <div className="border-2 border-gray-300 rounded-lg overflow-hidden">
              <button
                onClick={() => toggleSection('dataInfo')}
                className="w-full px-3 py-2.5 bg-gray-100 flex items-center justify-between hover:bg-gray-200"
              >
                <span className="text-sm font-bold text-black">데이터 연동</span>
                <span className="text-gray-600 font-bold">{expandedSections.dataInfo ? '−' : '+'}</span>
              </button>
              {expandedSections.dataInfo && (
                <div className="p-3 bg-white space-y-3 border-t border-gray-200">
                  <select
                    value={newBadge.dataInfo.source}
                    onChange={(e) => setNewBadge(prev => ({ ...prev, dataInfo: { ...prev.dataInfo, source: e.target.value } }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded text-sm text-black bg-white"
                  >
                    <option value="">데이터 출처</option>
                    {dataSourceTypes.map(t => <option key={t} value={t}>{t}</option>)}
                  </select>
                  <div className="flex gap-2">
                    <select
                      value={newBadge.dataInfo.method}
                      onChange={(e) => setNewBadge(prev => ({ ...prev, dataInfo: { ...prev.dataInfo, method: e.target.value } }))}
                      className="w-24 px-3 py-2 border border-gray-300 rounded text-sm text-black bg-white"
                    >
                      <option value="">Method</option>
                      {httpMethods.map(m => <option key={m} value={m}>{m}</option>)}
                    </select>
                    <input
                      type="text"
                      placeholder="API 엔드포인트"
                      value={newBadge.dataInfo.endpoint}
                      onChange={(e) => setNewBadge(prev => ({ ...prev, dataInfo: { ...prev.dataInfo, endpoint: e.target.value } }))}
                      className="flex-1 px-3 py-2 border border-gray-300 rounded text-sm text-black"
                    />
                  </div>
                  <input
                    type="text"
                    placeholder="관련 필드"
                    value={newBadge.dataInfo.fields}
                    onChange={(e) => setNewBadge(prev => ({ ...prev, dataInfo: { ...prev.dataInfo, fields: e.target.value } }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded text-sm text-black"
                  />
                  <input
                    type="text"
                    placeholder="관련 테이블"
                    value={newBadge.dataInfo.relatedTable}
                    onChange={(e) => setNewBadge(prev => ({ ...prev, dataInfo: { ...prev.dataInfo, relatedTable: e.target.value } }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded text-sm text-black"
                  />
                </div>
              )}
            </div>

            {/* 버튼 - 와이어프레임 스타일 */}
            <div className="flex gap-2 pt-2">
              <button
                onClick={() => {
                  if (newBadge.label.trim()) {
                    onAddBadge({
                      ...newBadge,
                      description: generateDescription(newBadge),
                    });
                    resetNewBadge();
                  }
                }}
                className="flex-1 py-2 bg-gray-800 text-white rounded-lg hover:bg-gray-900 text-sm font-medium border border-gray-600"
              >
                추가
              </button>
              <button
                onClick={() => {
                  setIsAddingBadge(false);
                  resetNewBadge();
                }}
                className="px-4 py-2 bg-gray-200 text-black rounded-lg hover:bg-gray-300 text-sm border border-gray-300"
              >
                취소
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 버전 업그레이드 모달 - 와이어프레임 스타일 */}
      {showVersionModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[60]">
          <div className="bg-white rounded-lg shadow-xl w-96 max-h-[80vh] overflow-hidden border border-gray-300">
            <div className="px-4 py-3 border-b border-gray-300 bg-gray-100">
              <h3 className="font-bold text-black">버전 업그레이드</h3>
              <p className="text-xs text-gray-600 mt-1">현재 버전: v{currentVersion.version}</p>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-black mb-2">변경 이력</label>
                <textarea
                  value={versionChangeLog}
                  onChange={(e) => setVersionChangeLog(e.target.value)}
                  placeholder="이번 버전에서 변경된 내용을 입력하세요..."
                  className="w-full h-32 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-gray-400 focus:border-gray-400"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-black mb-2">버전 유형 선택</label>
                <div className="grid grid-cols-3 gap-2">
                  <button
                    onClick={() => upgradeVersion('patch')}
                    className="px-3 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm border border-gray-300"
                  >
                    <div className="font-medium text-black">패치</div>
                    <div className="text-xs text-gray-600">v{currentVersion.version.split('.').map((v, i) => i === 2 ? Number(v) + 1 : v).join('.')}</div>
                  </button>
                  <button
                    onClick={() => upgradeVersion('minor')}
                    className="px-3 py-2 bg-gray-200 hover:bg-gray-300 rounded-lg text-sm border border-gray-300"
                  >
                    <div className="font-medium text-black">마이너</div>
                    <div className="text-xs text-gray-700">v{currentVersion.version.split('.').map((v, i) => i === 1 ? Number(v) + 1 : i === 2 ? 0 : v).join('.')}</div>
                  </button>
                  <button
                    onClick={() => upgradeVersion('major')}
                    className="px-3 py-2 bg-gray-300 hover:bg-gray-400 rounded-lg text-sm border border-gray-400"
                  >
                    <div className="font-medium text-black">메이저</div>
                    <div className="text-xs text-gray-700">v{(Number(currentVersion.version.split('.')[0]) + 1)}.0.0</div>
                  </button>
                </div>
              </div>
            </div>
            <div className="px-4 py-3 border-t border-gray-300 bg-gray-50 flex justify-end">
              <button
                onClick={() => {
                  setShowVersionModal(false);
                  setVersionChangeLog('');
                }}
                className="px-4 py-2 text-sm text-black hover:bg-gray-100 rounded-lg border border-gray-300"
              >
                취소
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 버전 이력 조회 모달 - 와이어프레임 스타일 */}
      {showVersionHistory && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[60]">
          <div className="bg-white rounded-lg shadow-xl w-[480px] max-h-[80vh] overflow-hidden border border-gray-300">
            <div className="px-4 py-3 border-b border-gray-300 bg-gray-100 flex items-center justify-between">
              <div>
                <h3 className="font-bold text-black">버전 이력</h3>
                <p className="text-xs text-gray-600 mt-1">현재 버전: v{currentVersion.version}</p>
              </div>
              <button
                onClick={() => setShowVersionHistory(false)}
                className="p-1 hover:bg-gray-200 rounded text-black font-bold"
              >
                ✕
              </button>
            </div>
            <div className="p-4 max-h-[60vh] overflow-y-auto">
              {currentVersion.history && currentVersion.history.length > 0 ? (
                <div className="space-y-3">
                  {currentVersion.history.map((entry, idx) => (
                    <div key={idx} className={`p-3 rounded-lg border ${entry.isAutoSave ? 'bg-gray-100 border-gray-300' : 'bg-gray-50 border-gray-200'}`}>
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-2">
                          {entry.isAutoSave ? (
                            <span className="px-2 py-0.5 bg-gray-200 text-black rounded text-xs font-medium border border-gray-400">
                              자동저장
                            </span>
                          ) : (
                            <>
                              <span className="px-2 py-0.5 bg-gray-300 text-black rounded text-xs font-medium border border-gray-400">
                                v{entry.version}
                              </span>
                              {entry.version !== entry.previousVersion && (
                                <>
                                  <span className="text-xs text-gray-500">←</span>
                                  <span className="text-xs text-gray-600">v{entry.previousVersion}</span>
                                </>
                              )}
                            </>
                          )}
                        </div>
                        <span className="text-xs text-gray-500">
                          {new Date(entry.updatedAt).toLocaleString('ko-KR', {
                            month: 'short',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit'
                          })}
                        </span>
                      </div>
                      {entry.changeLog && (
                        <p className="text-sm whitespace-pre-wrap text-black">{entry.changeLog}</p>
                      )}
                      <div className="flex items-center gap-3 mt-2 text-xs text-gray-500">
                        <span>작성자: {entry.updatedBy}</span>
                        <span>뱃지 수: {entry.badgeCount}개</span>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  <p className="text-sm">버전 이력이 없습니다</p>
                  <p className="text-xs mt-1">버전을 업그레이드하면 이력이 기록됩니다</p>
                </div>
              )}
            </div>
            <div className="px-4 py-3 border-t border-gray-300 bg-gray-50 flex justify-end">
              <button
                onClick={() => setShowVersionHistory(false)}
                className="px-4 py-2 text-sm text-black hover:bg-gray-100 rounded-lg border border-gray-300"
              >
                닫기
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 기능정의문서 모달 */}
      <FeatureDocumentModal
        isOpen={showFeatureDocModal}
        onClose={() => setShowFeatureDocModal(false)}
        screenKey={currentScreenKey}
        screenName={screenName}
      />

    </div>
  );
};

// 뱃지 오버레이 컴포넌트 (화면에 표시되는 뱃지들)
const FeatureBadgeOverlay = ({ badges, selectedBadge, onSelectBadge, badgeEditMode, onUpdatePosition, onAnalyzeAndUpdate, onEditBadge }) => {
  const [dragging, setDragging] = useState(null);
  const [dragStart, setDragStart] = useState(null);
  const [hoveredElement, setHoveredElement] = useState(null);
  const containerRef = React.useRef(null);

  // 뱃지 색상 hex 값 (인라인 스타일용) - 컬러로 표시
  const badgeColorHex = {
    red: '#ef4444',
    blue: '#3b82f6',
    green: '#22c55e',
    purple: '#a855f7',
    orange: '#f97316',
    gray: '#6b7280',
  };

  // 드래그 시작 (isFixed가 false인 경우만 드래그 가능)
  const handleMouseDown = (e, badge) => {
    // isFixed인 뱃지는 드래그 불가, 클릭만 가능
    if (badge.isFixed) {
      onSelectBadge(badge);
      return;
    }
    e.preventDefault();
    e.stopPropagation();
    setDragging(badge.id);
    setDragStart({ x: e.clientX, y: e.clientY });
  };

  // 드래그 중
  const handleMouseMove = React.useCallback((e) => {
    if (!dragging || !containerRef.current) return;
    const rect = containerRef.current.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    onUpdatePosition(dragging, {
      x: Math.max(2, Math.min(98, x)),
      y: Math.max(2, Math.min(98, y)),
    });

    // 드래그 중 UI 요소 탐지하여 하이라이트
    const targetElement = getElementAtPoint(e.clientX, e.clientY, containerRef);
    if (targetElement) {
      setHoveredElement(targetElement);
      // 하이라이트 효과 추가
      targetElement.style.outline = '2px dashed #6b7280';
      targetElement.style.outlineOffset = '2px';
    }
  }, [dragging, onUpdatePosition]);

  // 드래그 종료
  const handleMouseUp = React.useCallback((e) => {
    // 하이라이트 제거
    if (hoveredElement) {
      hoveredElement.style.outline = '';
      hoveredElement.style.outlineOffset = '';
      setHoveredElement(null);
    }

    if (dragging && dragStart) {
      const distance = Math.sqrt(
        Math.pow(e.clientX - dragStart.x, 2) + Math.pow(e.clientY - dragStart.y, 2)
      );

      // 이동 거리가 5px 미만이면 클릭으로 간주 → 인라인 수정 모드로 열기
      if (distance < 5) {
        const clickedBadge = badges.find(b => b.id === dragging);
        if (clickedBadge && onEditBadge) {
          onEditBadge(clickedBadge);
        }
      } else {
        // 드래그로 이동한 경우: 해당 위치의 UI 요소 분석
        const targetElement = getElementAtPoint(e.clientX, e.clientY, containerRef);
        if (targetElement && onAnalyzeAndUpdate) {
          const analysis = analyzeElement(targetElement);
          if (analysis) {
            onAnalyzeAndUpdate(dragging, analysis);
          }
        }
        // 드래그 완료 후 해당 뱃지 선택
        const movedBadge = badges.find(b => b.id === dragging);
        if (movedBadge) {
          onSelectBadge(movedBadge);
        }
      }
    }
    setDragging(null);
    setDragStart(null);
  }, [dragging, dragStart, badges, onSelectBadge, hoveredElement, onAnalyzeAndUpdate]);

  React.useEffect(() => {
    if (dragging) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      // 드래그 중 텍스트 선택 방지
      document.body.style.userSelect = 'none';
      return () => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
        document.body.style.userSelect = '';
        // 하이라이트 제거
        if (hoveredElement) {
          hoveredElement.style.outline = '';
          hoveredElement.style.outlineOffset = '';
        }
      };
    }
  }, [dragging, handleMouseMove, handleMouseUp, hoveredElement]);

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

  return (
    <div
      ref={containerRef}
      className="absolute inset-0 pointer-events-none z-30"
      data-badge-overlay="true"
      style={{ minHeight: '100%', filter: 'none', WebkitFilter: 'none' }}
    >
      {badges.map((badge, index) => (
        <div
          key={badge.id}
          className={`absolute pointer-events-auto select-none ${dragging === badge.id ? 'z-50 scale-110' : 'z-40'
            }`}
          style={{
            // 절대 픽셀 좌표가 있으면 사용, 없으면 비율 사용 (레거시 호환)
            left: badge.absoluteX !== undefined ? `${badge.absoluteX}px` : `${badge.x || 10}%`,
            top: badge.absoluteY !== undefined ? `${badge.absoluteY}px` : `${badge.y || 10}%`,
            transform: 'translate(-50%, -50%)',
            cursor: badge.isFixed ? 'pointer' : (dragging === badge.id ? 'grabbing' : 'grab'),
            transition: dragging === badge.id ? 'none' : 'transform 0.1s ease-out',
            filter: 'none',
            WebkitFilter: 'none',
          }}
          onMouseDown={(e) => handleMouseDown(e, badge)}
        >
          <div className="flex items-center gap-1" style={{ filter: 'none' }}>
            <div
              className={`badge-number-circle w-7 h-7 rounded-full shadow-lg flex items-center justify-center text-sm font-bold ${selectedBadge?.id === badge.id ? 'ring-2 ring-offset-2 ring-gray-500' : ''
                } ${dragging === badge.id ? 'shadow-xl scale-110' : 'hover:shadow-xl hover:scale-105'} ${badge.isFixed ? 'ring-1 ring-white/50' : ''
                }`}
              title={badge.isFixed ? `${badge.label} (고정됨)` : badge.label}
              style={{
                backgroundColor: badgeColorHex[badge.color] || badgeColorHex.red,
                color: '#ffffff',
                filter: 'none',
                WebkitFilter: 'none'
              }}
            >
              {badge.number || index + 1}
            </div>
            {badge.label && (
              <span
                className="text-xs px-2 py-0.5 rounded shadow-lg whitespace-nowrap badge-label-text"
                style={{
                  backgroundColor: 'rgba(17, 24, 39, 0.9)',
                  color: '#ffffff',
                  filter: 'none',
                  WebkitFilter: 'none'
                }}
              >
                {badge.label}
              </span>
            )}
          </div>
          {/* 고정 표시 아이콘 - 와이어프레임 스타일 */}
          {badge.isFixed && (
            <div className="absolute -top-1 -right-1 w-3 h-3 bg-white rounded-full shadow flex items-center justify-center">
              <div className="w-1.5 h-1.5 bg-gray-600 rounded-full" />
            </div>
          )}
          {/* 연결선 (선택된 경우) - 와이어프레임 스타일 */}
          {selectedBadge?.id === badge.id && !dragging && (
            <div className="absolute top-full left-1/2 transform -translate-x-1/2 w-0.5 h-4 bg-gray-500" />
          )}
        </div>
      ))}
      {/* 드래그 중 안내 */}
      {dragging && (
        <div className="fixed bottom-4 left-1/2 transform -translate-x-1/2 bg-gray-800 text-white px-4 py-2 rounded-full text-sm shadow-lg z-50">
          UI 요소 위에 드롭하면 자동으로 분석됩니다
        </div>
      )}
    </div>
  );
};

// 모달용 뱃지 오버레이 컴포넌트 (기능정의서 모드에서 모달 위에 뱃지 표시)
const ModalFeatureBadgeOverlay = ({
  badges,
  selectedBadge,
  onSelectBadge,
  badgeEditMode,
  onUpdatePosition,
  onAnalyzeAndUpdate,
  onEditBadge,
  modalId,
  screenId
}) => {
  const [dragging, setDragging] = useState(null);
  const [dragStart, setDragStart] = useState(null);
  const overlayRef = React.useRef(null);

  // 뱃지 색상 hex 값 - 컬러로 표시
  const badgeColorHex = {
    red: '#ef4444',
    blue: '#3b82f6',
    green: '#22c55e',
    purple: '#a855f7',
    orange: '#f97316',
    gray: '#6b7280',
  };

  // 드래그 시작
  const handleMouseDown = (e, badge) => {
    if (badge.isFixed) {
      onSelectBadge(badge);
      return;
    }
    e.preventDefault();
    e.stopPropagation();
    setDragging(badge.id);
    setDragStart({ x: e.clientX, y: e.clientY });
  };

  // 드래그 중
  const handleMouseMove = React.useCallback((e) => {
    if (!dragging || !overlayRef.current) return;
    const rect = overlayRef.current.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    onUpdatePosition(dragging, {
      x: Math.max(2, Math.min(98, x)),
      y: Math.max(2, Math.min(98, y)),
    });
  }, [dragging, onUpdatePosition]);

  // 드래그 종료
  const handleMouseUp = React.useCallback((e) => {
    if (dragging && dragStart) {
      const distance = Math.sqrt(
        Math.pow(e.clientX - dragStart.x, 2) + Math.pow(e.clientY - dragStart.y, 2)
      );
      if (distance < 5) {
        const clickedBadge = badges.find(b => b.id === dragging);
        if (clickedBadge && onEditBadge) {
          onEditBadge(clickedBadge);
        }
      } else {
        const movedBadge = badges.find(b => b.id === dragging);
        if (movedBadge) {
          onSelectBadge(movedBadge);
        }
      }
    }
    setDragging(null);
    setDragStart(null);
  }, [dragging, dragStart, badges, onSelectBadge, onEditBadge]);

  React.useEffect(() => {
    if (dragging) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      document.body.style.userSelect = 'none';
      return () => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
        document.body.style.userSelect = '';
      };
    }
  }, [dragging, handleMouseMove, handleMouseUp]);

  return (
    <div
      ref={overlayRef}
      className="absolute inset-0 pointer-events-none z-[9999]"
      data-modal-badge-overlay="true"
      style={{ filter: 'none', WebkitFilter: 'none' }}
    >
      {/* 모달 ID 표시 - 항상 표시 (와이어프레임 스타일) */}
      <div
        className="absolute top-2 left-2 px-2 py-1 rounded text-xs font-mono pointer-events-auto"
        style={{
          backgroundColor: 'rgba(75, 85, 99, 0.9)',
          color: '#ffffff',
          filter: 'none'
        }}
      >
        {screenId}
      </div>

      {badges.map((badge, index) => (
        <div
          key={badge.id}
          className={`absolute pointer-events-auto select-none ${dragging === badge.id ? 'z-50 scale-110' : 'z-40'
            }`}
          style={{
            left: `${badge.x || 50}%`,
            top: `${badge.y || 50}%`,
            transform: 'translate(-50%, -50%)',
            cursor: badge.isFixed ? 'pointer' : (dragging === badge.id ? 'grabbing' : 'grab'),
            transition: dragging === badge.id ? 'none' : 'transform 0.1s ease-out',
            filter: 'none',
          }}
          onMouseDown={(e) => handleMouseDown(e, badge)}
        >
          <div className="flex items-center gap-1" style={{ filter: 'none' }}>
            <div
              className={`w-7 h-7 rounded-full shadow-lg flex items-center justify-center text-sm font-bold ${selectedBadge?.id === badge.id ? 'ring-2 ring-offset-2 ring-gray-500' : ''
                }`}
              style={{
                backgroundColor: badgeColorHex[badge.color] || badgeColorHex.red,
                color: '#ffffff',
                filter: 'none'
              }}
            >
              {badge.number || index + 1}
            </div>
            {badge.label && (
              <span
                className="text-xs px-2 py-0.5 rounded shadow-lg whitespace-nowrap"
                style={{
                  backgroundColor: 'rgba(17, 24, 39, 0.9)',
                  color: '#ffffff',
                  filter: 'none'
                }}
              >
                {badge.label}
              </span>
            )}
          </div>
        </div>
      ))}
    </div>
  );
};

// 수주 카드 컴포넌트 (태블릿/모바일용)
const OrderCard = ({ order, onClick }) => {
  const getStatusStyle = (status) => {
    const styles = {
      '수주확정': 'bg-gray-100 text-gray-700',
      '생산중': 'bg-orange-100 text-orange-700',
      '생산완료': 'bg-green-100 text-green-700',
      '출하완료': 'bg-blue-100 text-blue-700',
      '취소': 'bg-red-100 text-red-700',
    };
    return styles[status] || 'bg-gray-100 text-gray-700';
  };

  const getQuoteStatusBadge = (order) => {
    if (order.quoteStatus === '최종확정') {
      return <span className="px-2 py-0.5 rounded text-xs font-medium bg-blue-500 text-white">최종확정</span>;
    }
    if (order.modificationCount > 0) {
      return <span className="px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-700">{order.modificationCount}차 수정</span>;
    }
    return null;
  };

  return (
    <div
      onClick={onClick}
      className="bg-white rounded-xl border border-gray-200 p-4 hover:shadow-md transition-shadow cursor-pointer"
    >
      {/* 상단: 번호, 상태 */}
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center gap-2">
          <input type="checkbox" className="w-5 h-5 rounded border-gray-300" onClick={(e) => e.stopPropagation()} />
          <span className="text-sm text-gray-500">#{order.id}</span>
        </div>
        <span className={`px-2.5 py-1 rounded-full text-xs font-medium ${getStatusStyle(order.status)}`}>
          {order.status}
        </span>
      </div>

      {/* 로트번호 */}
      <div className="mb-3">
        <span className="inline-block px-3 py-1 bg-blue-50 text-blue-600 rounded-lg text-sm font-mono">
          {order.orderNo}
        </span>
      </div>

      {/* 발주처 (큰 텍스트) */}
      <h3 className="text-xl font-bold text-gray-900 mb-4">{order.customerName}</h3>

      {/* 견적번호, 현장명 */}
      <div className="grid grid-cols-2 gap-4 text-sm mb-4">
        <div>
          <p className="text-gray-500 mb-1">견적번호</p>
          <p className="font-mono text-gray-700 bg-gray-50 px-2 py-1 rounded">{order.quoteNo || '-'}</p>
        </div>
        <div>
          <p className="text-gray-500 mb-1">현장명</p>
          <p className="text-gray-900 font-medium truncate">{order.siteName}</p>
        </div>
      </div>

      {/* 견적 상태 뱃지 */}
      {getQuoteStatusBadge(order) && (
        <div className="mb-4">
          {getQuoteStatusBadge(order)}
        </div>
      )}

      {/* 생산지시 */}
      <div className="text-sm pt-3 border-t">
        <div>
          <p className="text-gray-500 mb-1">생산지시</p>
          <span className={`px-2 py-0.5 rounded text-xs font-medium ${order.productionOrdered ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600'
            }`}>
            {order.productionOrdered ? '완료' : '아니요'}
          </span>
        </div>
      </div>
    </div>
  );
};

const Card = ({ title, children, className = '' }) => (
  <div className={`bg-white rounded-xl border border-gray-100 shadow-sm ${className}`}>
    {title && (
      <div className="px-5 py-4 border-b border-gray-100">
        <h3 className="font-semibold text-gray-900">{title}</h3>
      </div>
    )}
    <div className="p-5">{children}</div>
  </div>
);

// 슬라이드 패널 (오른쪽에서 열림)
const SlidePanel = ({ isOpen, onClose, title, width = 'max-w-2xl', children }) => {
  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 overflow-hidden">
      {/* 배경 오버레이 */}
      <div
        className="absolute inset-0 bg-black/30 transition-opacity"
        onClick={onClose}
      />

      {/* 패널 */}
      <div className={`absolute right-0 top-0 h-full w-full ${width} bg-white shadow-2xl transform transition-transform duration-300 ease-out`}>
        {/* 헤더 */}
        <div className="flex items-center justify-between px-6 py-4 border-b bg-gray-50">
          <h2 className="text-lg font-bold text-gray-900">{title}</h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-200 rounded-full transition-colors"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* 내용 */}
        <div className="h-[calc(100%-65px)] overflow-y-auto">
          {children}
        </div>
      </div>
    </div>
  );
};

// 폼 필드 (에러 상태 지원)
const FormField = ({ label, required, children, hint, error, errorMessage }) => (
  <div className="space-y-1.5">
    <label className="block text-sm font-medium text-gray-700">
      {label}
      {required && <span className="text-red-500 ml-0.5">*</span>}
    </label>
    <div className={error ? 'form-field-error' : ''}>
      {children}
    </div>
    {error && errorMessage && (
      <p className="text-xs text-red-500 flex items-center gap-1">
        <span>⚠</span> {errorMessage}
      </p>
    )}
    {!error && hint && <p className="text-xs text-gray-500">{hint}</p>}
  </div>
);

// 유효성 검사 훅
const useFormValidation = (formData, validationRules) => {
  const [errors, setErrors] = useState({});
  const [touched, setTouched] = useState({});

  // 단일 필드 유효성 검사
  const validateField = (fieldName, value) => {
    const rule = validationRules[fieldName];
    if (!rule) return null;

    // 필수 항목 체크
    if (rule.required) {
      if (value === undefined || value === null || value === '' ||
        (Array.isArray(value) && value.length === 0)) {
        return rule.message || `${rule.label || fieldName}은(는) 필수 항목입니다.`;
      }
    }

    // 최소 길이 체크
    if (rule.minLength && typeof value === 'string' && value.length < rule.minLength) {
      return `${rule.label || fieldName}은(는) 최소 ${rule.minLength}자 이상이어야 합니다.`;
    }

    // 패턴 체크
    if (rule.pattern && typeof value === 'string' && !rule.pattern.test(value)) {
      return rule.patternMessage || `${rule.label || fieldName} 형식이 올바르지 않습니다.`;
    }

    // 커스텀 유효성 검사
    if (rule.validate && typeof rule.validate === 'function') {
      const customError = rule.validate(value, formData);
      if (customError) return customError;
    }

    return null;
  };

  // 전체 폼 유효성 검사
  const validateForm = () => {
    const newErrors = {};
    let isValid = true;

    Object.keys(validationRules).forEach(fieldName => {
      const error = validateField(fieldName, formData[fieldName]);
      if (error) {
        newErrors[fieldName] = error;
        isValid = false;
      }
    });

    setErrors(newErrors);
    // 모든 필드를 touched로 표시
    const allTouched = {};
    Object.keys(validationRules).forEach(key => { allTouched[key] = true; });
    setTouched(allTouched);

    return isValid;
  };

  // 필드 터치 처리
  const handleBlur = (fieldName) => {
    setTouched(prev => ({ ...prev, [fieldName]: true }));
    const error = validateField(fieldName, formData[fieldName]);
    setErrors(prev => ({ ...prev, [fieldName]: error }));
  };

  // 필드 변경 시 에러 클리어
  const clearFieldError = (fieldName) => {
    if (errors[fieldName]) {
      setErrors(prev => ({ ...prev, [fieldName]: null }));
    }
  };

  // 에러 상태 확인 (터치된 필드만)
  const getFieldError = (fieldName) => {
    return touched[fieldName] ? errors[fieldName] : null;
  };

  // 에러가 있는지 확인
  const hasError = (fieldName) => {
    return touched[fieldName] && !!errors[fieldName];
  };

  // 모든 에러 초기화
  const resetErrors = () => {
    setErrors({});
    setTouched({});
  };

  return {
    errors,
    touched,
    validateForm,
    validateField,
    handleBlur,
    clearFieldError,
    getFieldError,
    hasError,
    resetErrors,
    setErrors,
    setTouched,
  };
};

// 에러 상태 input 스타일 클래스
const getInputClassName = (hasError, baseClass = '') => {
  const base = baseClass || 'w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:border-transparent';
  if (hasError) {
    return `${base} border-red-500 focus:ring-red-500 bg-red-50`;
  }
  return `${base} border-gray-200 focus:ring-blue-500`;
};

// 텍스트 입력
const TextInput = ({ placeholder, value, onChange, disabled }) => (
  <input
    type="text"
    placeholder={placeholder}
    value={value}
    onChange={(e) => onChange(e.target.value)}
    disabled={disabled}
    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-50 disabled:text-gray-500"
  />
);

// 셀렉트
const Select = ({ options, value, onChange, placeholder }) => (
  <select
    value={value}
    onChange={(e) => onChange(e.target.value)}
    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none bg-white"
  >
    <option value="">{placeholder || '선택하세요'}</option>
    {options.map(opt => (
      <option key={opt.value} value={opt.value}>{opt.label}</option>
    ))}
  </select>
);

// 정보 행
const InfoRow = ({ label, value }) => (
  <div>
    <p className="text-sm text-gray-500 mb-1">{label}</p>
    <p className="font-medium text-gray-900">{value || '-'}</p>
  </div>
);

// 페이지 헤더 - 타이틀과 버튼 영역 분리 (타이틀 아래에 버튼)
const PageHeader = ({ icon: Icon, title, onBack, actions, leftActions }) => (
  <div className="mb-6 space-y-3">
    {/* 타이틀 영역 */}
    <div className="flex items-center gap-3">
      {onBack && (
        <button onClick={onBack} className="p-2 hover:bg-gray-100 rounded-lg">
          <ArrowLeft className="w-5 h-5 text-gray-500" />
        </button>
      )}
      {Icon && <Icon className="w-6 h-6 text-blue-500" />}
      <h1 className="text-xl font-bold text-gray-900">{title}</h1>
    </div>
    {/* 버튼 영역 - 타이틀 아래, 좌측/우측 분리 */}
    {(actions || leftActions) && (
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">{leftActions}</div>
        <div className="flex items-center gap-2">{actions}</div>
      </div>
    )}
  </div>
);

// 상세 페이지 탭
const DetailTabs = ({ tabs, activeTab, onTabChange }) => (
  <div className="flex gap-4 border-b mb-6">
    {tabs.map(tab => (
      <button
        key={tab.id}
        onClick={() => onTabChange(tab.id)}
        className={`flex items-center gap-2 px-1 py-3 text-sm font-medium border-b-2 transition-colors
          ${activeTab === tab.id
            ? 'border-blue-500 text-blue-600'
            : 'border-transparent text-gray-500 hover:text-gray-700'}`}
      >
        {tab.icon && <tab.icon className="w-4 h-4" />}
        {tab.label}
      </button>
    ))}
  </div>
);

// ============ 더미 데이터 ============

// ============ 거래처 데이터 ============
/*
 * 신용등급별 프로세스 제어
 * A등급(우량): 수주→생산→출고 자동, 세금계산서 자동
 * B등급(관리): 생산 자동, 입금확인 후 출고
 * C등급(위험): 경리승인 후 생산, 입금확인 후 출고
 */
const customers = [
  {
    id: 1,
    code: 'CUS-001',
    name: '삼성물산(주)',
    ceo: '김삼성',
    bizNo: '123-45-67890',
    type: '고객',
    bizType: '건설업',
    bizItem: '종합건설',
    address: '서울시 강남구 테헤란로 100',
    phone: '02-1111-1111',
    fax: '02-1111-1112',
    email: 'samsung@samsung-const.co.kr',
    manager: '이건설',
    managerPhone: '010-1111-1111',
    creditGrade: 'A',  // 우량
    creditNote: '정상거래처, 입금지연 없음',
    paymentTerms: '월말마감 익월15일',
    requireApproval: false,  // 경리승인 불필요
    requirePaymentBeforeShip: false,  // 입금 전 출고 가능
  },
  {
    id: 2,
    code: 'CUS-002',
    name: '현대건설(주)',
    ceo: '박현대',
    bizNo: '234-56-78901',
    type: '고객',
    bizType: '건설업',
    bizItem: '시설물관리',
    address: '인천시 연수구 송도동 200',
    phone: '032-2222-2222',
    fax: '032-2222-2223',
    email: 'hyundai@hyundai-dev.co.kr',
    manager: '최개발',
    managerPhone: '010-2222-2222',
    creditGrade: 'B',  // 관리
    creditNote: '가끔 입금 지연, 할인 요청 발생',
    paymentTerms: '입금확인 후 출고',
    requireApproval: false,  // 경리승인 불필요
    requirePaymentBeforeShip: true,  // 입금 후 출고
  },
  {
    id: 3,
    code: 'CUS-003',
    name: '대우건설(주)',
    ceo: '정한화',
    bizNo: '345-67-89012',
    type: '고객',
    bizType: '건설업',
    bizItem: '인테리어',
    address: '대전시 서구 둔산동 300',
    phone: '042-3333-3333',
    fax: '042-3333-3334',
    email: 'hanwha@hanwha-const.co.kr',
    manager: '강시공',
    managerPhone: '010-3333-3333',
    creditGrade: 'C',  // 위험
    creditNote: '입금약속 미이행 이력 2회, 주의 필요',
    paymentTerms: '선입금 50% + 잔금 출고 전',
    requireApproval: true,  // 경리승인 필요
    requirePaymentBeforeShip: true,  // 입금 후 출고
  },
  {
    id: 4,
    code: 'CUS-004',
    name: '(주)서울인테리어',
    ceo: '이부산',
    bizNo: '456-78-90123',
    type: '고객',
    bizType: '건설업',
    bizItem: '종합건설',
    address: '부산시 해운대구 우동 400',
    phone: '051-4444-4444',
    fax: '051-4444-4445',
    email: 'busan@busan-const.co.kr',
    manager: '박해운',
    managerPhone: '010-4444-4444',
    creditGrade: 'A',  // 우량
    creditNote: '우량 거래처',
    paymentTerms: '월말마감 익월말',
    requireApproval: false,
    requirePaymentBeforeShip: false,
  },
];

// 신용등급 색상 매핑
const creditGradeColors = {
  'A': { bg: 'bg-green-100', text: 'text-green-700', label: '우량' },
  'B': { bg: 'bg-yellow-100', text: 'text-yellow-700', label: '관리' },
  'C': { bg: 'bg-red-100', text: 'text-red-700', label: '위험' },
};

/*
 * ============================================================
 * 📋 발주서/생산지시서 상세 데이터 구조 (발주서 양식 기반)
 * ============================================================
 * 
 * 1. productionSpec: 스크린 품목별 제작 사양
 * 2. bomData: 절곡물 BOM (자재 소요량)
 * 3. motorSpec: 모터/전장품 사양
 * 
 * ============================================================
 */

// 제작 스펙 자동 생성 함수 (��라메트릭 계산)
const generateProductionSpec = (item, index = 0) => {
  // spec에서 크기 파싱 (예: "7660×2550")
  const [openW, openH] = (item.spec || item.width && item.height ? `${item.width}×${item.height}` : '3000×2400')
    .split('×').map(s => parseInt(s) || 0);

  // 제작 사이즈 계산 (오픈 사이즈 + 여유분)
  const prodWidth = openW + 140;  // 가로 140mm 추가
  const prodHeight = Math.max(openH + 400, 2950);  // 세로 최소 2950mm

  // 샤프트 인치 결정 (가로 기준)
  const shaft = openW > 6000 ? 5 : 4;

  // 모터 용량 결정
  const capacity = openW > 6000 ? 300 : 160;

  // 가이드레일 타입 결정 (기본: 백면형)
  const guideRailType = '백면형';
  const guideRailSpec = '120-70';

  return {
    type: '와이어',
    drawingNo: `${item.floor || '1층'} ${item.location || `FSS${index + 1}`}`,
    openWidth: openW,
    openHeight: openH,
    prodWidth,
    prodHeight,
    guideRailType,
    guideRailSpec,
    shaft,
    caseSpec: '500-330',
    motorBracket: '380-180',
    capacity,
    finish: 'SUS마감',
  };
};

// 모터 스펙 자동 계산
const generateMotorSpec = (items) => {
  const specs = items.map(item => item.productionSpec || generateProductionSpec(item));

  const motor150Count = specs.filter(s => s.capacity <= 160).length;
  const motor300Count = specs.filter(s => s.capacity > 160 && s.capacity <= 300).length;
  const motor400Count = specs.filter(s => s.capacity > 300).length;

  return {
    motors220V: [
      { model: 'KD-150K', qty: 0 },
      { model: 'KD-300K', qty: 0 },
      { model: 'KD-400K', qty: 0 },
    ],
    motors380V: [
      { model: 'KD-150K', qty: motor150Count },
      { model: 'KD-300K', qty: motor300Count },
      { model: 'KD-400K', qty: motor400Count },
    ],
    brackets: [
      { spec: '380-180 [2-4"]', qty: 0 },
      { spec: '380-180 [2-5"]', qty: items.length },
    ],
    heatSinks: [
      { spec: '40-60', qty: items.length * 2 },
      { spec: 'L-380', qty: 0 },
    ],
    controllers: [
      { type: '매입형', qty: 0 },
      { type: '노출형', qty: 0 },
      { type: '핫라스', qty: 0 },
    ],
  };
};

// BOM 자동 계산
const generateBomData = (items) => {
  const totalItems = items.length;

  return {
    guideRails: {
      description: '가이드레일 - EGI 1.55T + 마감재 EGI 1.15T + 별도마감재 SUS 1.15T',
      items: [
        {
          type: '백면형', spec: '120-70', code: 'KSE01/KWE01', lengths: [
            { length: 3000, qty: totalItems * 2 },
          ]
        },
        {
          type: '측면형', spec: '120-120', code: 'KSS01', lengths: [
            { length: 4300, qty: 0 },
            { length: 4000, qty: 0 },
            { length: 3500, qty: 0 },
            { length: 3000, qty: 0 },
          ]
        },
        {
          type: '하부BASE', spec: '130-80', code: '', lengths: [
            { length: 0, qty: totalItems * 2 },
          ]
        },
      ],
      smokeBarrier: {
        spec: 'W80',
        material: '원 0.8T 화이바글라스크탑직물',
        lengths: [{ length: 2950, qty: totalItems * 2 }],
        note: '* 전면부, 린텔부 양쪽에 설치',
      },
    },
    cases: {
      description: '케이스(셔터박스) - EGI 1.55T',
      mainSpec: '500-330 (150,300,400/K용)',
      items: [
        { length: 4150, qty: Math.ceil(totalItems * 0.1) },
        { length: 4000, qty: Math.ceil(totalItems * 0.4) },
        { length: 3500, qty: Math.ceil(totalItems * 0.3) },
        { length: 3000, qty: Math.ceil(totalItems * 0.2) },
      ],
      sideCover: { spec: '500-355', qty: totalItems * 2 },
      topCover: { qty: Math.ceil(totalItems * 0.1) },
      extension: { spec: '1219+무게', qty: totalItems * 3 },
      smokeBarrier: { spec: 'W80', length: 3000, qty: totalItems * 2 },
    },
    bottomFinish: {
      description: '하단마감재 - 마단마감재(EGI 1.55T) + 하단보강별바(EGI 1.55T) + 하단 보강횡철(EGI 1.15T) + 하단 부재횡철(50-12T)',
      items: [
        {
          name: '하단마감재', spec: '50-40', lengths: [
            { length: 4000, qty: totalItems },
            { length: 3000, qty: 0 },
          ]
        },
        {
          name: '하단보강빔바', spec: '80-17', lengths: [
            { length: 4000, qty: totalItems * 2 },
            { length: 3000, qty: 0 },
          ]
        },
        {
          name: '하단보강철', spec: '', lengths: [
            { length: 4000, qty: totalItems },
            { length: 3000, qty: 0 },
          ]
        },
        {
          name: '하단부재횡철', spec: '50-12T', lengths: [
            { length: 2000, qty: totalItems * 4 },
          ]
        },
      ],
    },
  };
};

// ============ 견적수식관리 마스터 데이터 ============

// 제품 유형 정의
const quoteProducts = [
  { id: 'common', name: '공통', formulaCount: 24 },
  { id: 'screen-basic', name: '스크린 셔터 기본형', formulaCount: 0 },
  { id: 'screen-open', name: '스크린 셔터 오픈형', formulaCount: 0 },
  { id: 'steel-basic', name: '철재 셔터 기본형', formulaCount: 0 },
  { id: 'slat', name: '슬랫', formulaCount: 6 },
];

// 수식 카테고리 정의 (스크린샷 기준 전체 확장)
const formulaCategories = [
  { id: 'basic-info', name: '기본정보', order: 1, description: '입력 변수 정의' },
  { id: 'production-size', name: '제작사이즈', order: 2, description: '제작 가로/세로 산출' },
  { id: 'area-weight', name: '면적&중량', order: 3, description: '면적(M) 및 중량(K) 산출' },
  { id: 'motor-calc', name: '모터용량산출', order: 4, description: '샤프트 인치별 모터 선정' },
  { id: 'bracket-angle', name: '브라켓&받침용앵글', order: 5, description: '모터용량별 브라켓/앵글 산출' },
  { id: 'shaft', name: '감기샤프트', order: 6, description: '메인샤프트/보조샤프트 산출' },
  { id: 'guide-rail', name: '가이드레일', order: 7, description: '가이드레일 자재/수량 산출' },
  { id: 'smoke-block', name: '연기차단재', order: 8, description: '연기차단재 산출' },
  { id: 'shutter-box', name: '셔터박스(케이스)', order: 9, description: '케이스 구성품 산출' },
  { id: 'bottom-finish', name: '하단마감재', order: 10, description: '하장바/엘바/보강평철/무게평철' },
  { id: 'sub-material', name: '부자재', order: 11, description: '환봉/조인트바/각파이프' },
  { id: 'purchased-parts', name: '구매부품', order: 12, description: '모터/연동제어기/앵글 등' },
  { id: 'sheet-count', name: '장수산출', order: 13, description: '스크린 원단 장수/슬랫 매수 계산' },
];

// ═══════════════════════════════════════════════════════════════════
// 품목 수식 데이터 (스크린샷 기반 완전 구현)
// ═══════════════════════════════════════════════════════════════════
const initialQuoteFormulas = [
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 1. 기본정보 (입력 변수)
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  { id: 1, productId: 'common', categoryId: 'basic-info', order: 1, name: '제품구분', variable: 'PC', type: 'input', formula: '', resultType: 'variable', description: '스크린/철재', unit: '', options: ['스크린', '철재'] },
  { id: 2, productId: 'common', categoryId: 'basic-info', order: 2, name: '오픈사이즈 가로', variable: 'W0', type: 'input', formula: '', resultType: 'variable', description: '고객 주문 가로 (mm)', unit: 'mm' },
  { id: 3, productId: 'common', categoryId: 'basic-info', order: 3, name: '오픈사이즈 세로', variable: 'H0', type: 'input', formula: '', resultType: 'variable', description: '고객 주문 세로 (mm)', unit: 'mm' },
  { id: 4, productId: 'common', categoryId: 'basic-info', order: 4, name: '샤프트 규격', variable: 'SHAFT_INCH', type: 'input', formula: '', resultType: 'variable', description: '4"/5"/6"/8"', unit: '', options: ['4', '5', '6', '8'] },
  { id: 5, productId: 'common', categoryId: 'basic-info', order: 5, name: '설치유형', variable: 'INSTALL_TYPE', type: 'input', formula: '', resultType: 'variable', description: '벽면형/측면형/혼합형', unit: '', options: ['벽면형', '측면형', '혼합형'] },
  { id: 6, productId: 'common', categoryId: 'basic-info', order: 6, name: '모터 전원', variable: 'MP', type: 'input', formula: '', resultType: 'variable', description: '220V/380V', unit: 'V', options: ['220', '380'] },
  { id: 7, productId: 'common', categoryId: 'basic-info', order: 7, name: '유선/무선', variable: 'WIRE', type: 'input', formula: '', resultType: 'variable', description: '유선/무선', unit: '', options: ['유선', '무선'] },
  { id: 8, productId: 'common', categoryId: 'basic-info', order: 8, name: '연동제어기 타입', variable: 'CT', type: 'input', formula: '', resultType: 'variable', description: '매립/노출', unit: '', options: ['매립', '노출'] },
  { id: 9, productId: 'common', categoryId: 'basic-info', order: 9, name: '수량', variable: 'QTY', type: 'input', formula: '', resultType: 'variable', description: '주문 수량', unit: 'SET' },
  { id: 10, productId: 'common', categoryId: 'basic-info', order: 10, name: '케이스 사이즈', variable: 'CASE_SIZE', type: 'input', formula: '', resultType: 'variable', description: '스크린500*350/철재650*500', unit: 'mm' },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 2. 제작사이즈 산출 (스크린샷: 오픈사이즈 기반 제작사이즈)
  // 스크린: W1 = W0+140, H1 = H0+350 (일부 케이스는 고정값 900 사용)
  // 철재: W1 = W0+110, H1 = H0+350
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  { id: 11, productId: 'screen', categoryId: 'production-size', order: 1, name: '제작가로(스크린)', variable: 'W1', type: 'formula', formula: 'W0 + 140', resultType: 'variable', description: '스크린(실리카/와이어) 제작가로', unit: 'mm', condition: "PC === '스크린'" },
  { id: 12, productId: 'screen', categoryId: 'production-size', order: 2, name: '제작세로(스크린)', variable: 'H1', type: 'formula', formula: 'H0 + 350', resultType: 'variable', description: '스크린 제작세로 (일부케이스 고정값 900)', unit: 'mm', condition: "PC === '스크린'" },
  { id: 13, productId: 'steel', categoryId: 'production-size', order: 3, name: '제작가로(철재)', variable: 'W1', type: 'formula', formula: 'W0 + 110', resultType: 'variable', description: '철재 셔터 제작가로', unit: 'mm', condition: "PC === '철재'" },
  { id: 14, productId: 'steel', categoryId: 'production-size', order: 4, name: '제작세로(철재)', variable: 'H1', type: 'formula', formula: 'H0 + 350', resultType: 'variable', description: '철재 셔터 제작세로', unit: 'mm', condition: "PC === '철재'" },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 3. 면적(M) & 중량(K) 계산 (스크린샷: 면적 및 중량 산출)
  // M = W1 × H1 ÷ 1,000,000 (㎡)
  // 스크린: K = (M × 2) + (W0 × 14.17 ÷ 1000)
  // 철재: K = M × 25
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  { id: 15, productId: 'common', categoryId: 'area-weight', order: 1, name: '면적(M)', variable: 'M', type: 'formula', formula: '(W1 * H1) / 1000000', resultType: 'variable', description: '면적 = W1 × H1 ÷ 1,000,000', unit: '㎡' },
  { id: 16, productId: 'screen', categoryId: 'area-weight', order: 2, name: '중량(스크린)', variable: 'K', type: 'formula', formula: '(M * 2) + (W0 * 14.17 / 1000)', resultType: 'variable', description: 'K = (M×2) + (W0×14.17÷1000)', unit: 'kg', condition: "PC === '스크린'" },
  { id: 17, productId: 'steel', categoryId: 'area-weight', order: 3, name: '중량(철재)', variable: 'K', type: 'formula', formula: 'M * 25', resultType: 'variable', description: 'K = M × 25', unit: 'kg', condition: "PC === '철재'" },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 4. 모터용량 산출 (스크린샷: 모터 용량 산정 기준)
  // [스크린] 샤프트 인치 + 산출중량(K) → 적용모터
  // [철재] 샤프트 인치 + 산출중량(K) → 적용모터
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  {
    id: 20, productId: 'common', categoryId: 'motor-calc', order: 1, name: '모터용량(KG)', variable: 'MOTOR_KG', type: 'lookup',
    formula: 'MOTOR_LOOKUP', resultType: 'variable', description: '샤프트인치+중량K로 모터용량 결정', unit: 'KG',
    lookupTable: 'motorCapacityTable'
  },
  {
    id: 21, productId: 'common', categoryId: 'motor-calc', order: 2, name: '모터코드', variable: 'MOTOR_CODE', type: 'formula',
    formula: "'E-' + MOTOR_KG + 'K' + MP + 'V-' + (WIRE === '유선' ? 'W' : 'R')", resultType: 'variable', description: '모터 품목코드 생성', unit: ''
  },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 5. 브라켓 & 받침용앵글 산출 (스크린샷: 모터용량별 기준표)
  // [스크린용] 150K:380×180/40×40×380, 300K:380×180/40×40×380, 400K:530×320/50×50×530
  // [철재용] 300K:530×320/50×50×530, 400K:530×320/50×50×530, 500K~:600×350/50×50×600
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  {
    id: 25, productId: 'common', categoryId: 'bracket-angle', order: 1, name: '브라켓 규격', variable: 'BRACKET_SPEC', type: 'lookup',
    formula: 'BRACKET_LOOKUP', resultType: 'variable', description: '모터용량별 브라켓 규격', unit: 'mm',
    lookupTable: 'bracketTable'
  },
  {
    id: 26, productId: 'common', categoryId: 'bracket-angle', order: 2, name: '받침용앵글 규격', variable: 'ANGLE_SPEC', type: 'lookup',
    formula: 'ANGLE_LOOKUP', resultType: 'variable', description: '모터용량별 받침용앵글 규격', unit: 'mm',
    lookupTable: 'angleTable'
  },
  // 구매부품 - 규칙: 품목명-규격
  {
    id: 27, productId: 'common', categoryId: 'bracket-angle', order: 3, name: '브라켓', variable: 'BRACKET', type: 'output',
    formula: 'BRACKET_SPEC', resultType: 'item', description: '브라켓 품목', itemCode: '브라켓', itemName: '브라켓', unit: 'SET', qtyFormula: 'QTY'
  },
  {
    id: 28, productId: 'common', categoryId: 'bracket-angle', order: 4, name: '받침용앵글', variable: 'SUPPORT_ANGLE', type: 'output',
    formula: 'ANGLE_SPEC', resultType: 'item', description: '받침용앵글', itemCode: '받침용앵글', itemName: '받침용앵글', unit: 'SET', qtyFormula: 'QTY'
  },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 6. 감기샤프트 산출 (문서: 감기샤프트(스크린용/철재용) 산출 로직)
  // 스크린: W1 기준 샤프트 규격 결정 (기본 5인치)
  // 철재: W1과 K(산출중량) 두 조건을 모두 만족해야 함
  // 메인샤프트: 자재단위 3000/4500/6000/7000/8000/8200, 통자재 1개만 납품(길이조합 불가)
  // 보조샤프트(스크린전용): 항상 3인치, W1≤8200→300자재, W1>8200→500자재, 수량 무조건 1개
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  {
    id: 30, productId: 'steel', categoryId: 'shaft', order: 1, name: '메인샤프트 규격(철재)', variable: 'MAIN_SHAFT_INCH_STEEL', type: 'lookup',
    formula: 'SHAFT_INCH_STEEL_LOOKUP', resultType: 'variable', description: '철재: W1,K 두 조건으로 샤프트인치 결정 (4/5/6/8인치)',
    lookupTable: 'shaftInchTableSteel', condition: "PC === '철재'"
  },
  {
    id: 97, productId: 'screen', categoryId: 'shaft', order: 1, name: '메인샤프트 규격(스크린)', variable: 'MAIN_SHAFT_INCH_SCREEN', type: 'lookup',
    formula: 'SHAFT_INCH_SCREEN_LOOKUP', resultType: 'variable', description: '스크린: W1 기준 샤프트인치 결정 (기본 5인치)',
    lookupTable: 'shaftInchTableScreen', condition: "PC === '스크린'"
  },
  {
    id: 31, productId: 'common', categoryId: 'shaft', order: 2, name: '메인샤프트 자재길이', variable: 'MAIN_SHAFT_LEN', type: 'lookup',
    formula: 'SHAFT_LEN_LOOKUP', resultType: 'variable', description: '인치별 W1구간에 따라 자재길이 선택 (항상 W1 이상 길이)',
    lookupTable: 'shaftLengthTable'
  },
  // 구매부품 - 규칙: 품목명-규격
  {
    id: 32, productId: 'common', categoryId: 'shaft', order: 3, name: '메인샤프트', variable: 'MAIN_SHAFT', type: 'output',
    formula: 'MAIN_SHAFT_LEN', resultType: 'item', description: '메인샤프트(통자재 1개)',
    itemCode: '감기샤프트', itemName: '감기샤프트(메인)', unit: 'EA', qtyFormula: 'QTY'
  },
  {
    id: 33, productId: 'screen', categoryId: 'shaft', order: 4, name: '보조샤프트 자재', variable: 'SUB_SHAFT_MAT', type: 'lookup',
    formula: 'SUB_SHAFT_LOOKUP', resultType: 'variable', description: '보조샤프트(스크린전용, 항상 3인치) W1≤8200→300, W1>8200→500',
    lookupTable: 'subShaftTable', condition: "PC === '스크린'"
  },
  {
    id: 34, productId: 'screen', categoryId: 'shaft', order: 5, name: '보조샤프트', variable: 'SUB_SHAFT', type: 'output',
    formula: 'SUB_SHAFT_MAT.length', resultType: 'item', description: '보조샤프트(스크린전용, 3인치, 수량 무조건 1개)',
    itemCode: '감기샤프트-보조3인치', itemName: '감기샤프트(보조3인치)', unit: 'EA', qtyFormula: 'QTY', condition: "PC === '스크린'"
  },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 7. 가이드레일 산출 (스크린샷: 가이드레일 및 연기차단재 산출 기준서)
  // G(제작길이) = H0 + 250
  // 스크린: 가이드레일 내부 삽입 2개 (가이드레일1랑과 동일한 길이)
  // 철재: 가이드레일 내부 삽입 1개
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  {
    id: 40, productId: 'common', categoryId: 'guide-rail', order: 1, name: '가이드레일 제작길이', variable: 'G', type: 'formula',
    formula: 'H0 + 250', resultType: 'variable', description: 'G(제작길이) = H0 + 250', unit: 'mm'
  },
  {
    id: 41, productId: 'common', categoryId: 'guide-rail', order: 2, name: '가이드레일 자재길이', variable: 'GR_MAT_LEN', type: 'lookup',
    formula: 'GR_LENGTH_LOOKUP', resultType: 'variable', description: 'G값으로 자재길이 결정(2438/3000/3500/4000/4300)', unit: 'mm',
    lookupTable: 'guideRailLengthTable'
  },
  // 절곡부품 - 규칙: 품목코드+종류코드+모양&길이코드
  {
    id: 42, productId: 'common', categoryId: 'guide-rail', order: 3, name: '가이드레일', variable: 'GUIDE_RAIL', type: 'output',
    formula: 'GR_MAT_LEN', resultType: 'item', description: '가이드레일(벽면형)',
    itemCode: 'RC', itemName: '가이드레일', unit: 'EA', qtyFormula: 'QTY * 2'
  },
  {
    id: 43, productId: 'common', categoryId: 'guide-rail', order: 4, name: '하부BASE1 규격', variable: 'BASE1_SPEC', type: 'lookup',
    formula: 'BASE1_LOOKUP', resultType: 'variable', description: '제품구분+설치유형별 하부BASE1 규격',
    lookupTable: 'baseSpecTable'
  },
  {
    id: 44, productId: 'common', categoryId: 'guide-rail', order: 5, name: '하부BASE2 규격', variable: 'BASE2_SPEC', type: 'lookup',
    formula: 'BASE2_LOOKUP', resultType: 'variable', description: '제품구분+설치유형별 하부BASE2 규격',
    lookupTable: 'baseSpecTable'
  },
  // 부자재 - 규칙: 품목명-규격
  {
    id: 95, productId: 'common', categoryId: 'guide-rail', order: 6, name: '하부BASE1', variable: 'GR_BASE1', type: 'output',
    formula: 'BASE1_SPEC', resultType: 'item', description: '하부BASE1(스크린:130×80/130×130, 철재:140×85/140×135)',
    itemCode: '하부BASE-벽면형', itemName: '하부BASE1', unit: 'SET', qtyFormula: 'QTY'
  },
  {
    id: 96, productId: 'common', categoryId: 'guide-rail', order: 7, name: '하부BASE2', variable: 'GR_BASE2', type: 'output',
    formula: 'BASE2_SPEC', resultType: 'item', description: '하부BASE2(설치유형별 규격)',
    itemCode: '하부BASE-코너형', itemName: '하부BASE2', unit: 'SET', qtyFormula: 'QTY'
  },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 8. 연기차단재 산출 (문서: 가이드레일 1량과 동일한 길이로 제작)
  // 스크린: 가이드레일 내부 삽입 2개/1량당 (1SET=2량, 총4개)
  // 철재: 가이드레일 내부 삽입 1개/1량당 (1SET=2량, 총2개)
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 절곡부품 - 규칙: 품목코드+종류코드+모양&길이코드 (GI: 연기차단재 화이바원단)
  {
    id: 45, productId: 'screen', categoryId: 'smoke-block', order: 1, name: '연기차단재(스크린)', variable: 'SMOKE_BLOCK', type: 'output',
    formula: 'G', resultType: 'item', description: '연기차단재(스크린) 2개/1량당×2량',
    itemCode: 'GI', itemName: '연기차단재', unit: 'EA', qtyFormula: 'QTY * 2 * 2', condition: "PC === '스크린'"
  },
  {
    id: 46, productId: 'steel', categoryId: 'smoke-block', order: 2, name: '연기차단재(철재)', variable: 'SMOKE_BLOCK', type: 'output',
    formula: 'G', resultType: 'item', description: '연기차단재(철재) 1개/1량당×2량',
    itemCode: 'GI', itemName: '연기차단재', unit: 'EA', qtyFormula: 'QTY * 2 * 1', condition: "PC === '철재'"
  },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 9. 셔터박스(케이스) 구성품 산출 (스크린샷: 케이스 구성품 산출 기준서)
  // 제작사이즈(S) = 케이스 제작사이즈, 적용자재 규칙
  // 케이스판재/상부덮개: ceil(S / 1219)
  // 마구리: 1SET = 2EA (제작사이즈 무관하게 1SET)
  // 케이스용 연기차단재: ceil(S / 3000) * 2
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  {
    id: 50, productId: 'common', categoryId: 'shutter-box', order: 1, name: '케이스 제작사이즈', variable: 'S', type: 'formula',
    formula: 'W1', resultType: 'variable', description: '케이스 제작사이즈 = W1', unit: 'mm'
  },
  {
    id: 51, productId: 'common', categoryId: 'shutter-box', order: 2, name: '케이스판재 자재길이', variable: 'CASE_MAT_LEN', type: 'lookup',
    formula: 'CASE_LENGTH_LOOKUP', resultType: 'variable', description: 'S값으로 자재길이 결정', unit: 'mm',
    lookupTable: 'caseLengthTable'
  },
  {
    id: 52, productId: 'common', categoryId: 'shutter-box', order: 3, name: '케이스판재 수량', variable: 'CASE_MAT_QTY', type: 'lookup',
    formula: 'CASE_QTY_LOOKUP', resultType: 'variable', description: 'S범위별 수량 (1~2개)', unit: 'EA',
    lookupTable: 'caseQtyTable'
  },
  // 절곡부품 - 규칙: 품목코드+종류코드+모양&길이코드 (CB: 케이스)
  {
    id: 53, productId: 'common', categoryId: 'shutter-box', order: 4, name: '케이스판재', variable: 'CASE_PANEL', type: 'output',
    formula: 'CASE_MAT_LEN', resultType: 'item', description: '케이스판재',
    itemCode: 'CB', itemName: '케이스판재', unit: 'EA', qtyFormula: 'CASE_MAT_QTY * QTY'
  },
  // 부자재 - 규칙: 품목명-규격
  {
    id: 54, productId: 'common', categoryId: 'shutter-box', order: 5, name: '마구리', variable: 'MARGURI', type: 'output',
    formula: '', resultType: 'item', description: '마구리(1SET=2EA, 제작사이즈 무관)',
    itemCode: '마구리-', itemName: '마구리', unit: 'SET', qtyFormula: 'QTY'
  },
  {
    id: 55, productId: 'common', categoryId: 'shutter-box', order: 6, name: '상부덮개 자재길이', variable: 'TOP_COVER_LEN', type: 'lookup',
    formula: 'TOP_COVER_LOOKUP', resultType: 'variable', description: '상부덮개 자재길이(케이스판재와 동일 테이블)', unit: 'mm',
    lookupTable: 'caseLengthTable'
  },
  // 부자재 - 규칙: 품목명-규격
  {
    id: 56, productId: 'common', categoryId: 'shutter-box', order: 7, name: '상부덮개', variable: 'TOP_COVER', type: 'output',
    formula: 'TOP_COVER_LEN', resultType: 'item', description: '상부덮개(케이스판재와 동일 규격, EGI 1.5ST)',
    itemCode: '상부덮개', itemName: '상부덮개', unit: 'EA', qtyFormula: 'CASE_MAT_QTY * QTY'
  },
  {
    id: 57, productId: 'common', categoryId: 'shutter-box', order: 8, name: '케이스연기차단재 수량', variable: 'CASE_SMOKE_QTY', type: 'formula',
    formula: 'Math.ceil(S / 3000) * 2', resultType: 'variable', description: '케이스용 연기차단재 = ceil(S/3000)*2', unit: 'EA'
  },
  // 절곡부품 - 규칙: 품목코드+종류코드+모양&길이코드 (GI: 연기차단재)
  {
    id: 58, productId: 'common', categoryId: 'shutter-box', order: 9, name: '케이스연기차단재', variable: 'CASE_SMOKE', type: 'output',
    formula: '3000', resultType: 'item', description: '케이스용 연기차단재(3000mm)',
    itemCode: 'GI30', itemName: '케이스용연기차단재', unit: 'EA', qtyFormula: 'CASE_SMOKE_QTY * QTY'
  },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 10. 하단마감재 구성품 산출 (스크린샷: 하단마감재 구성품 산출 기준서)
  // B = W0 (하단마감재 제작사이즈)
  // 하장바: 철재60×30, 스크린60×40, B범위별 3000/4000 자재
  // 엘바(스크린전용): 17×60 / 2량 1세트
  // 보강평철(스크린전용): 50mm
  // 무게평철(스크린전용): 50×12T / 오픈사이즈 기준 두줄 삽입
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  {
    id: 60, productId: 'common', categoryId: 'bottom-finish', order: 1, name: '하단마감재 제작사이즈', variable: 'B', type: 'formula',
    formula: 'W0', resultType: 'variable', description: 'B = W0 (오픈사이즈 가로)', unit: 'mm'
  },
  // 하장바: 철재(60×30), 스크린(60×40) - bottomBarTable 참조
  {
    id: 61, productId: 'common', categoryId: 'bottom-finish', order: 2, name: '하장바 자재', variable: 'HJ_MAT', type: 'lookup',
    formula: 'HJ_LOOKUP', resultType: 'variable', description: 'B범위별 하장바 자재길이 및 수량 결정',
    lookupTable: 'bottomBarTable'
  },
  // 부자재 - 규칙: 품목명-규격
  {
    id: 62, productId: 'steel', categoryId: 'bottom-finish', order: 3, name: '하장바(철재)', variable: 'HAJANGBAR_STEEL', type: 'output',
    formula: 'HJ_MAT', resultType: 'item', description: '하장바(철재 60×30)',
    itemCode: '하장바-60×30', itemName: '하장바 60×30', unit: 'EA', qtyFormula: 'HJ_MAT.qty * QTY', condition: "PC === '철재'"
  },
  {
    id: 63, productId: 'screen', categoryId: 'bottom-finish', order: 4, name: '하장바(스크린)', variable: 'HAJANGBAR_SCREEN', type: 'output',
    formula: 'HJ_MAT', resultType: 'item', description: '하장바(스크린 60×40)',
    itemCode: '하장바-60×40', itemName: '하장바 60×40', unit: 'EA', qtyFormula: 'HJ_MAT.qty * QTY', condition: "PC === '스크린'"
  },
  // 엘바: 스크린전용, 규격 17×60, 2량 1세트 - elbarTable 참조
  {
    id: 64, productId: 'screen', categoryId: 'bottom-finish', order: 5, name: '엘바 자재', variable: 'ELBAR_MAT', type: 'lookup',
    formula: 'ELBAR_LOOKUP', resultType: 'variable', description: '엘바(스크린전용) B범위별 자재',
    lookupTable: 'elbarTable', condition: "PC === '스크린'"
  },
  // 부자재 - 규칙: 품목명-규격
  {
    id: 65, productId: 'screen', categoryId: 'bottom-finish', order: 6, name: '엘바', variable: 'ELBAR', type: 'output',
    formula: 'ELBAR_MAT', resultType: 'item', description: '엘바(스크린전용 17×60, 2량1세트)',
    itemCode: '엘바-17×60', itemName: '엘바 17×60', unit: 'EA', qtyFormula: 'ELBAR_MAT.qty * QTY', condition: "PC === '스크린'"
  },
  // 보강평철: 스크린전용, 규격 50mm - reinforceTable 참조
  {
    id: 66, productId: 'screen', categoryId: 'bottom-finish', order: 7, name: '보강평철 자재', variable: 'REINFORCE_MAT', type: 'lookup',
    formula: 'REINFORCE_LOOKUP', resultType: 'variable', description: '보강평철(스크린전용) B범위별 자재',
    lookupTable: 'reinforceTable', condition: "PC === '스크린'"
  },
  // 부자재 - 규칙: 품목명-규격
  {
    id: 67, productId: 'screen', categoryId: 'bottom-finish', order: 8, name: '보강평철', variable: 'REINFORCE', type: 'output',
    formula: 'REINFORCE_MAT', resultType: 'item', description: '보강평철(스크린전용 50mm)',
    itemCode: '보강평철-50mm', itemName: '보강평철 50mm', unit: 'EA', qtyFormula: 'REINFORCE_MAT.qty * QTY', condition: "PC === '스크린'"
  },
  // 무게평철: 스크린전용, 규격 50×12T, 단위 2000mm, 두줄 삽입 - weightFlatTable 참조
  {
    id: 68, productId: 'screen', categoryId: 'bottom-finish', order: 9, name: '무게평철 자재', variable: 'WEIGHT_MAT', type: 'lookup',
    formula: 'WEIGHT_LOOKUP', resultType: 'variable', description: '무게평철(스크린전용) B범위별 자재(두줄 삽입)',
    lookupTable: 'weightFlatTable', condition: "PC === '스크린'"
  },
  // 부자재 - 규칙: 품목명-규격
  {
    id: 69, productId: 'screen', categoryId: 'bottom-finish', order: 10, name: '무게평철', variable: 'WEIGHT_FLAT', type: 'output',
    formula: '2000', resultType: 'item', description: '무게평철(스크린전용 50×12T, 2000단위, 두줄)',
    itemCode: '무게평철-50×12TL2000', itemName: '무게평철 50×12T', unit: 'EA', qtyFormula: 'WEIGHT_MAT.qty * QTY', condition: "PC === '스크린'"
  },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 11. 부자재 산출 (문서: 환봉, 조인트바 산출 기준 / 각파이프 자재 수량 산출 기준)
  // 환봉(스크린전용): 3000mm고정, W1구간별 수량 결정
  // 조인트바: 기본2개(양 끝 250mm 지점) + FLOOR((W1-500)/1000) 추가
  // 각파이프: 스크린용(500*350), 철재용(650*500) 케이스 제작사이즈별 산출
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  {
    id: 70, productId: 'screen', categoryId: 'sub-material', order: 1, name: '환봉 자재', variable: 'HWANBONG_MAT', type: 'lookup',
    formula: 'HWANBONG_LOOKUP', resultType: 'variable', description: '환봉(스크린전용) W1구간별 자재 및 수량',
    lookupTable: 'hwanbongQtyTable', condition: "PC === '스크린'"
  },
  // 부자재 - 규칙: 품목명-규격
  {
    id: 71, productId: 'screen', categoryId: 'sub-material', order: 2, name: '환봉', variable: 'HWANBONG', type: 'output',
    formula: '3000', resultType: 'item', description: '환봉(스크린전용, 3000mm고정)',
    itemCode: '환봉-3000', itemName: '환봉 3000', unit: 'EA', qtyFormula: 'HWANBONG_MAT.qty * QTY', condition: "PC === '스크린'"
  },
  {
    id: 72, productId: 'common', categoryId: 'sub-material', order: 3, name: '조인트바 수량', variable: 'JOINTBAR_QTY', type: 'formula',
    formula: '2 + Math.floor((W1 - 500) / 1000)', resultType: 'variable', description: '조인트바 = 기본2개 + FLOOR((W1-500)/1000) (중앙여유공간 내 1000mm당 추가)', unit: 'EA'
  },
  // 부자재 - 규칙: 품목명-규격
  {
    id: 73, productId: 'common', categoryId: 'sub-material', order: 4, name: '조인트바', variable: 'JOINTBAR', type: 'output',
    formula: '', resultType: 'item', description: '조인트바(양끝 250mm 지점 설치, 중앙 1000mm 간격 추가)',
    itemCode: '조인트바-', itemName: '조인트바', unit: 'EA', qtyFormula: 'JOINTBAR_QTY * QTY'
  },
  // 각파이프: 스크린용(squarePipeTableScreen), 철재용(squarePipeTableSteel) 별도 참조
  {
    id: 74, productId: 'screen', categoryId: 'sub-material', order: 5, name: '각파이프 자재(스크린)', variable: 'SQP_MAT_SCREEN', type: 'lookup',
    formula: 'SQP_SCREEN_LOOKUP', resultType: 'variable', description: '각파이프(스크린용 500*350) L구간별 3000/6000 자재 수량',
    lookupTable: 'squarePipeTableScreen', condition: "PC === '스크린'"
  },
  {
    id: 98, productId: 'steel', categoryId: 'sub-material', order: 5, name: '각파이프 자재(철재)', variable: 'SQP_MAT_STEEL', type: 'lookup',
    formula: 'SQP_STEEL_LOOKUP', resultType: 'variable', description: '각파이프(철재용 650*500) L구간별 3000/6000 자재 수량',
    lookupTable: 'squarePipeTableSteel', condition: "PC === '철재'"
  },
  // 부자재 - 규칙: 품목명-규격
  {
    id: 76, productId: 'common', categoryId: 'sub-material', order: 6, name: '각파이프 3000', variable: 'SQP3000', type: 'output',
    formula: '3000', resultType: 'item', description: '각파이프(3000mm)',
    itemCode: '각파이프-30×30L3000', itemName: '각파이프 30×30 3000', unit: 'EA', qtyFormula: "(PC === '스크린' ? SQP_MAT_SCREEN.mat3000 : SQP_MAT_STEEL.mat3000) * QTY"
  },
  {
    id: 77, productId: 'common', categoryId: 'sub-material', order: 7, name: '각파이프 6000', variable: 'SQP6000', type: 'output',
    formula: '6000', resultType: 'item', description: '각파이프(6000mm)',
    itemCode: '각파이프-30×30L6000', itemName: '각파이프 30×30 6000', unit: 'EA', qtyFormula: "(PC === '스크린' ? SQP_MAT_SCREEN.mat6000 : SQP_MAT_STEEL.mat6000) * QTY"
  },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 12. 구매부품 산출 (전동개폐기, 연동제어기)
  // 구매부품 - 규칙: 품목명-규격 (규격 = 전원+용량, 공백제거)
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  {
    id: 80, productId: 'common', categoryId: 'purchased-parts', order: 1, name: '전동개폐기', variable: 'MOTOR', type: 'output',
    formula: 'MOTOR_CODE', resultType: 'item', description: '전동개폐기(모터)',
    itemCode: '전동개폐기', itemName: '전동개폐기', unit: 'EA', qtyFormula: 'QTY', isDynamic: true
  },
  {
    id: 81, productId: 'common', categoryId: 'purchased-parts', order: 2, name: '연동제어기 코드', variable: 'CTL_CODE', type: 'formula',
    formula: "'연동제어기-' + (CT === '매립' ? '매립형' : '노출형') + (WIRE === '유선' ? '유선' : '무선')", resultType: 'variable', description: '연동제어기 품목코드 생성', unit: ''
  },
  {
    id: 82, productId: 'common', categoryId: 'purchased-parts', order: 3, name: '연동제어기', variable: 'CONTROLLER', type: 'output',
    formula: 'CTL_CODE', resultType: 'item', description: '연동제어기',
    itemCode: '연동제어기', itemName: '연동제어기', unit: 'EA', qtyFormula: 'QTY', isDynamic: true
  },

  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 13. 장수산출 (스크린 원단 장수 / 슬랫 매수 계산)
  // 스크린 원단 장수: 총 중량(kg) ÷ 장당 중량 = 투입 장수
  // 슬랫 매수: 코일 길이 ÷ 제품 높이 = 절단 매수
  // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  // 스크린 원단 계산용 입력값
  {
    id: 83, productId: 'screen', categoryId: 'sheet-count', order: 1, name: '원단 롤 중량', variable: 'FABRIC_ROLL_KG', type: 'input',
    formula: '', resultType: 'variable', description: '원단 롤 1개당 중량 (기본 25kg)', unit: 'kg', defaultValue: 25,
    condition: "PC === '스크린'"
  },
  {
    id: 84, productId: 'screen', categoryId: 'sheet-count', order: 2, name: '장당 중량', variable: 'FABRIC_SHEET_KG', type: 'formula',
    formula: '(W1 * H1 * 0.00035) / 1000', resultType: 'variable', description: '장당 중량 = 제작가로(mm) × 제작세로(mm) × 원단밀도(0.00035) ÷ 1000', unit: 'kg',
    condition: "PC === '스크린'"
  },
  {
    id: 85, productId: 'screen', categoryId: 'sheet-count', order: 3, name: '스크린 원단 장수', variable: 'SCREEN_SHEET_CNT', type: 'formula',
    formula: 'Math.floor(FABRIC_ROLL_KG / FABRIC_SHEET_KG)', resultType: 'variable', description: '원단 롤 중량 ÷ 장당 중량 = 투입 장수 (소수점 버림)', unit: '장',
    condition: "PC === '스크린'"
  },
  {
    id: 86, productId: 'screen', categoryId: 'sheet-count', order: 4, name: '필요 롤 수량', variable: 'SCREEN_ROLL_QTY', type: 'formula',
    formula: 'Math.ceil(QTY / SCREEN_SHEET_CNT)', resultType: 'variable', description: '주문수량 ÷ 롤당 장수 = 필요 롤 수량 (올림)', unit: '롤',
    condition: "PC === '스크린'"
  },

  // 슬랫 매수 계산용 입력값
  {
    id: 87, productId: 'slat', categoryId: 'sheet-count', order: 5, name: '코일 길이', variable: 'COIL_LENGTH', type: 'input',
    formula: '', resultType: 'variable', description: '슬랫 코일 1롤 길이 (기본 305000mm = 305m)', unit: 'mm', defaultValue: 305000,
    condition: "PC === '슬랫'"
  },
  {
    id: 88, productId: 'slat', categoryId: 'sheet-count', order: 6, name: '슬랫 피치', variable: 'SLAT_PITCH', type: 'input',
    formula: '', resultType: 'variable', description: '슬랫 1단 피치 높이 (기본 76mm)', unit: 'mm', defaultValue: 76,
    condition: "PC === '슬랫'"
  },
  {
    id: 89, productId: 'slat', categoryId: 'sheet-count', order: 7, name: '제품 높이별 슬랫 단수', variable: 'SLAT_ROW_CNT', type: 'formula',
    formula: 'Math.ceil(H0 / SLAT_PITCH)', resultType: 'variable', description: '제품 높이 ÷ 피치 = 슬랫 단수 (올림)', unit: '단',
    condition: "PC === '슬랫'"
  },
  {
    id: 90, productId: 'slat', categoryId: 'sheet-count', order: 8, name: '슬랫 절단 매수', variable: 'SLAT_SHEET_CNT', type: 'formula',
    formula: 'Math.floor(COIL_LENGTH / H0)', resultType: 'variable', description: '코일 길이 ÷ 제품 높이 = 절단 매수 (소수점 버림)', unit: '매',
    condition: "PC === '슬랫'"
  },
  {
    id: 91, productId: 'slat', categoryId: 'sheet-count', order: 9, name: '1SET 슬랫 총매수', variable: 'SLAT_TOTAL_SHEET', type: 'formula',
    formula: 'SLAT_ROW_CNT * 2', resultType: 'variable', description: '1SET = 2량이므로 슬랫 단수 × 2', unit: '매',
    condition: "PC === '슬랫'"
  },
  {
    id: 92, productId: 'slat', categoryId: 'sheet-count', order: 10, name: '필요 코일 수량', variable: 'SLAT_COIL_QTY', type: 'formula',
    formula: 'Math.ceil((SLAT_TOTAL_SHEET * QTY) / SLAT_SHEET_CNT)', resultType: 'variable', description: '총 필요매수 ÷ 코일당 절단매수 = 필요 코일 수량 (올림)', unit: '롤',
    condition: "PC === '슬랫'"
  },
];

// ═══════════════════════════════════════════════════════════════════
// 장수 계산 유틸리티 함수 (작업일지 데이터 연동용)
// ═══════════════════════════════════════════════════════════════════

/**
 * 스크린 원단 장수 계산
 * @param {number} width - 제작 가로 (mm)
 * @param {number} height - 제작 세로 (mm)
 * @param {number} fabricRollKg - 원단 롤 중량 (기본 25kg)
 * @param {number} fabricDensity - 원단 밀도 (기본 0.00035)
 * @returns {object} { sheetPerRoll: 롤당 장수, sheetKg: 장당 중량 }
 */
const calculateScreenSheetCount = (width, height, fabricRollKg = 25, fabricDensity = 0.00035) => {
  // 장당 중량 = 제작가로(mm) × 제작세로(mm) × 원단밀도 ÷ 1000
  const sheetKg = (width * height * fabricDensity) / 1000;
  // 롤당 장수 = 롤 중량 ÷ 장당 중량 (소수점 버림)
  const sheetPerRoll = sheetKg > 0 ? Math.floor(fabricRollKg / sheetKg) : 0;
  return { sheetPerRoll, sheetKg: sheetKg.toFixed(3) };
};

/**
 * 슬랫 매수(절단 매수) 계산
 * @param {number} productHeight - 제품 높이 (mm) - H0
 * @param {number} coilLength - 코일 길이 (기본 305000mm = 305m)
 * @param {number} slatPitch - 슬랫 피치 (기본 76mm)
 * @returns {object} { sheetCount: 절단 매수, rowCount: 슬랫 단수, totalSheetPerSet: 1SET당 총매수 }
 */
const calculateSlatSheetCount = (productHeight, coilLength = 305000, slatPitch = 76) => {
  // 절단 매수 = 코일 길이 ÷ 제품 높이 (소수점 버림)
  const sheetCount = productHeight > 0 ? Math.floor(coilLength / productHeight) : 0;
  // 슬랫 단수 = 제품 높이 ÷ 피치 (올림)
  const rowCount = slatPitch > 0 ? Math.ceil(productHeight / slatPitch) : 0;
  // 1SET = 2량이므로 슬랫 단수 × 2
  const totalSheetPerSet = rowCount * 2;
  return { sheetCount, rowCount, totalSheetPerSet };
};

/**
 * 작업일지용 슬랫 매수 자동 계산 (수주 품목 데이터 기반)
 * @param {object} orderItem - 수주 품목 데이터 (width, height 포함)
 * @returns {number} 계산된 매수(세로)
 */
const calculateWorkLogSlatSheetCount = (orderItem) => {
  if (!orderItem || !orderItem.height) return 0;
  const { sheetCount } = calculateSlatSheetCount(orderItem.height);
  return sheetCount;
};

/**
 * 작업일지용 스크린 규격별 장수 자동 계산
 * @param {number} totalHeight - 제품 총 높이 (mm)
 * @param {Array} standardHeights - 규격 높이 배열 [1180, 900, 600, 400, 300]
 * @returns {object} { spec1180: n, spec900: n, spec600: n, spec400: n, spec300: n, remainHeight: n }
 */
const calculateScreenSpecSheetCount = (totalHeight, standardHeights = [1180, 900, 600, 400, 300]) => {
  let remaining = totalHeight;
  const result = {
    spec1180: 0,
    spec900: 0,
    spec600: 0,
    spec400: 0,
    spec300: 0,
    remainHeight: 0
  };

  // 큰 규격부터 순차적으로 배분
  standardHeights.forEach(specHeight => {
    const specKey = `spec${specHeight}`;
    if (remaining >= specHeight) {
      result[specKey] = Math.floor(remaining / specHeight);
      remaining = remaining % specHeight;
    }
  });

  result.remainHeight = remaining;
  return result;
};

/**
 * 절곡 부품 수량 자동 계산 (1SET = 2량 기준)
 * @param {string} partType - 부품 유형 (가이드레일, 하부BASE, 연기차단재 등)
 * @param {number} productHeight - 제품 높이 (mm) - H0
 * @param {number} productWidth - 제품 가로 (mm) - W0
 * @param {number} qty - 주문 수량 (SET)
 * @returns {number} 필요 수량
 */
const calculateBendingPartQty = (partType, productHeight, productWidth, qty = 1) => {
  // 1SET = 2량 기준
  const setMultiplier = 2;

  switch (partType) {
    case '가이드레일':
    case '가이드레일(본체)':
    case '가이드레일(C형)':
    case '가이드레일(D형)':
      // 가이드레일: 1SET당 2개 (좌우 각 1개)
      return qty * setMultiplier;

    case '하부BASE1':
    case '하부BASE2':
      // 하부BASE: 1SET당 2개 (좌우 각 1개)
      return qty * setMultiplier;

    case '연기차단재':
      // 연기차단재: 1량당 2개 (상하) → 1SET당 4개
      return qty * setMultiplier * 2;

    case '케이스':
    case '케이스판재':
      // 케이스: 가로 기준으로 1219mm당 1개
      const casePanelQty = Math.ceil(productWidth / 1219);
      return casePanelQty * qty;

    case '마구리':
      // 마구리: 1SET당 1세트 (좌우 한쌍)
      return qty;

    case '상부덮개':
      // 상부덮개: 케이스와 동일
      const topCoverQty = Math.ceil(productWidth / 1219);
      return topCoverQty * qty;

    default:
      // 기본: 1SET당 2개
      return qty * setMultiplier;
  }
};

/**
 * 절곡 작업일지용 부품 목록 자동 생성
 * @param {object} orderData - 수주 데이터 (productHeight, productWidth, qty 포함)
 * @returns {Array} 절곡 부품 목록 (name, material, spec, qty)
 */
const generateBendingWorkLogParts = (orderData) => {
  const { productHeight = 3000, productWidth = 3000, qty = 1 } = orderData;

  // 가이드레일 제작 길이 = H0 + 250
  const guideRailLength = productHeight + 250;

  return [
    {
      name: '가이드레일(본체)',
      material: 'EGI 1.5T',
      spec: `${guideRailLength}mm`,
      qty: calculateBendingPartQty('가이드레일', productHeight, productWidth, qty)
    },
    {
      name: '가이드레일(C형)',
      material: 'EGI 1.5T',
      spec: `${guideRailLength}mm`,
      qty: calculateBendingPartQty('가이드레일', productHeight, productWidth, qty)
    },
    {
      name: '가이드레일(D형)',
      material: 'EGI 1.5T',
      spec: `${guideRailLength}mm`,
      qty: calculateBendingPartQty('가이드레일', productHeight, productWidth, qty)
    },
    {
      name: '하부BASE1',
      material: 'EGI 1.5T',
      spec: '130×80',
      qty: calculateBendingPartQty('하부BASE1', productHeight, productWidth, qty)
    },
    {
      name: '하부BASE2',
      material: 'EGI 1.5T',
      spec: '130×130',
      qty: calculateBendingPartQty('하부BASE2', productHeight, productWidth, qty)
    },
    {
      name: '연기차단재',
      material: '화이바',
      spec: `${guideRailLength}mm`,
      qty: calculateBendingPartQty('연기차단재', productHeight, productWidth, qty)
    },
  ];
};

// ═══════════════════════════════════════════════════════════════════
// 조회 테이블 (Lookup Tables) - 스크린샷 기반
// ═══════════════════════════════════════════════════════════════════

// 모터 용량 산출 테이블 (스크린샷: 모터 용량 산정 기준)
const motorCapacityTable = {
  // [스크린] 제품 기준 (샤프트인치 → 산출중량범위 → 적용모터)
  screen: {
    '4': [
      { min: 0, max: 123, motor: 150 },
      { min: 124, max: 208, motor: 300 },
    ],
    '5': [
      { min: 0, max: 150, motor: 150 },
      { min: 151, max: 246, motor: 300 },
      { min: 247, max: 277, motor: 400 },
    ],
    '6': [
      { min: 0, max: 208, motor: 150 },
      { min: 209, max: 246, motor: 300 },
      { min: 247, max: 324, motor: 400 },
      { min: 325, max: 388, motor: 500 },
      { min: 389, max: 494, motor: 600 },
    ],
  },
  // [철재] 제품 기준
  steel: {
    '4': [
      { min: 0, max: 277, motor: 300 },
      { min: 278, max: 327, motor: 400 },
      { min: 328, max: 400, motor: 500 },
    ],
    '5': [
      { min: 0, max: 300, motor: 300 },
      { min: 301, max: 424, motor: 400 },
      { min: 425, max: 600, motor: 500 },
    ],
    '6': [
      { min: 0, max: 327, motor: 300 },
      { min: 328, max: 494, motor: 400 },
      { min: 495, max: 600, motor: 500 },
      { min: 601, max: 800, motor: 600 },
    ],
    '8': [
      { min: 0, max: 600, motor: 500 },
      { min: 601, max: 800, motor: 800 },
      { min: 801, max: 1000, motor: 1000 },
    ],
  },
};

// 브라켓 규격 테이블 (스크린샷: 모터용량별 브라켓 & 받침용앵글 산출 기준서)
const bracketTable = {
  screen: {
    150: { bracket: '380×180', shaft: '3"~4"', angle: '40×40×380' },
    300: { bracket: '380×180', shaft: '3"~5"', angle: '40×40×380' },
    400: { bracket: '530×320', shaft: '3"~6"', angle: '50×50×530' },
  },
  steel: {
    300: { bracket: '530×320', shaft: '4"', angle: '50×50×530' },
    400: { bracket: '530×320', shaft: '5"', angle: '50×50×530' },
    500: { bracket: '600×350', shaft: '5"', angle: '50×50×600' },
    600: { bracket: '600×350', shaft: '6"', angle: '50×50×600' },
    800: { bracket: '600×350', shaft: '6"', angle: '50×50×600' },
    1000: { bracket: '690×390', shaft: '8"', angle: '50×50×690' },
  },
};

// ═══════════════════════════════════════════════════════════════════
// 감기샤프트 산출 로직 (문서: 감기샤프트(스크린용/철재용) 산출 로직)
// ═══════════════════════════════════════════════════════════════════

// 철재용 샤프트 인치 선택 테이블 (W1과 K 두 조건을 모두 만족해야 함)
const shaftInchTableSteel = [
  { w1Min: 0, w1Max: 4500, kMin: 0, kMax: 400, inch: '4' },
  { w1Min: 0, w1Max: 4500, kMin: 400, kMax: 600, inch: '5' },
  { w1Min: 4500, w1Max: 5600, kMin: 0, kMax: 600, inch: '5' },
  { w1Min: 5600, w1Max: 7800, kMin: 0, kMax: 600, inch: '5' },
  { w1Min: 5600, w1Max: 7800, kMin: 600, kMax: 800, inch: '6' },
  { w1Min: 5600, w1Max: 8200, kMin: 800, kMax: 9999, inch: '8' },
];

// 스크린용 샤프트 인치 선택 (W1 기준)
const shaftInchTableScreen = [
  { w1Min: 0, w1Max: 8200, inch: '5' },
  { w1Min: 8200, w1Max: 99999, inch: '6' },
];

// 메인샤프트 자재 길이 테이블 (인치별 W1 구간)
// 자재 규격: 3000 / 4500 / 6000 / 7000 / 8000 / 8200
// 자재는 통자재로 1개만 납품, 길이 조합 불가
// 샤프트 자재는 제작사이즈보다 작으면 안됨 (항상 W1 이상 길이 선택)
const shaftLengthTable = {
  '4': [
    { w1Min: 0, w1Max: 3000, length: 3000, qty: 1 },
    { w1Min: 3000, w1Max: 4500, length: 4500, qty: 1 },
  ],
  '5': [
    { w1Min: 0, w1Max: 3000, length: 3000, qty: 1 },
    { w1Min: 3000, w1Max: 4500, length: 4500, qty: 1 },
    { w1Min: 4500, w1Max: 6000, length: 6000, qty: 1 },
    { w1Min: 6000, w1Max: 7000, length: 7000, qty: 1 },
  ],
  '6': [
    { w1Min: 0, w1Max: 3000, length: 3000, qty: 1 },
    { w1Min: 3000, w1Max: 4500, length: 4500, qty: 1 },
    { w1Min: 4500, w1Max: 6000, length: 6000, qty: 1 },
    { w1Min: 6000, w1Max: 7000, length: 7000, qty: 1 },
    { w1Min: 7000, w1Max: 7800, length: 8000, qty: 1 },
  ],
  '8': [
    { w1Min: 0, w1Max: 3000, length: 3000, qty: 1 },
    { w1Min: 3000, w1Max: 4500, length: 4500, qty: 1 },
    { w1Min: 4500, w1Max: 6000, length: 6000, qty: 1 },
    { w1Min: 6000, w1Max: 7000, length: 7000, qty: 1 },
    { w1Min: 7000, w1Max: 7800, length: 8000, qty: 1 },
    { w1Min: 7800, w1Max: 8200, length: 8200, qty: 1 },
  ],
};

// 보조샤프트 (스크린 전용)
// 규격: 항상 3인치, 수량: 무조건 1개
// 자재 길이: W1 ≤ 8200 → 300 자재, W1 > 8200 → 500 자재
const subShaftTable = [
  { w1Min: 0, w1Max: 8200, length: 300, qty: 1 },
  { w1Min: 8200, w1Max: 99999, length: 500, qty: 1 },
];

// 가이드레일 자재 길이 테이블 (문서: 가이드레일 및 연기차단재 산출 기준서)
// 제작길이 G(mm) 구간별 자재 선택 (1SET = 2량)
const guideRailLengthTable = [
  { gMin: 1219, gMax: 2438, materials: [{ length: 2438, qty: 2 }] },
  { gMin: 2438, gMax: 3000, materials: [{ length: 3000, qty: 2 }] },
  { gMin: 3000, gMax: 3500, materials: [{ length: 3500, qty: 2 }] },
  { gMin: 3500, gMax: 4000, materials: [{ length: 4000, qty: 2 }] },
  { gMin: 4000, gMax: 4300, materials: [{ length: 4300, qty: 2 }] },
  { gMin: 4300, gMax: 5438, materials: [{ length: 3000, qty: 2 }, { length: 2438, qty: 2 }] },
  { gMin: 5438, gMax: 6000, materials: [{ length: 3000, qty: 4 }] },
  { gMin: 6000, gMax: 6500, materials: [{ length: 4000, qty: 2 }] },
  { gMin: 6500, gMax: 7000, materials: [{ length: 4300, qty: 2 }] },
  { gMin: 7000, gMax: 7300, materials: [{ length: 4300, qty: 2 }] },
];

// 하부BASE 규격 테이블 (문서: 가이드레일 설치유형별 하부BASE 규격)
// 스크린용
const baseSpecTableScreen = {
  '벽면형': { base1: '130×80', base2: '130×80', note: '120*70' },
  '측면형': { base1: '130×130', base2: '130×130', note: '120*120' },
  '혼합형': { base1: '130×80', base2: '130×130', note: '' },
};
// 철재용
const baseSpecTableSteel = {
  '벽면형': { base1: '140×85', base2: '140×85', note: '130*75' },
  '측면형': { base1: '140×135', base2: '140×135', note: '130*125' },
  '혼합형': { base1: '140×85', base2: '140×135', note: '' },
};

// 케이스 자재 테이블 (문서: 케이스(셔터박스) 구성품 산출 기준서)
// 케이스판재, 상부덮개 동일 적용, 자재두께: EGI 1.5ST
const caseLengthTable = [
  { sMin: 0, sMax: 1219, length: 1219, qty: 1 },
  { sMin: 1219, sMax: 2438, length: 2438, qty: 1 },
  { sMin: 2438, sMax: 3000, length: 3000, qty: 1 },
  { sMin: 3000, sMax: 3500, length: 3500, qty: 1 },
  { sMin: 3500, sMax: 4000, length: 4000, qty: 1 },
  { sMin: 4000, sMax: 4150, length: 4150, qty: 1 },
  { sMin: 4150, sMax: 4719, materials: [{ length: 2438, qty: 1 }, { length: 1219, qty: 1 }], qty: 2, combo: '2438+1219' },
  { sMin: 4719, sMax: 6000, materials: [{ length: 3000, qty: 2 }], qty: 2, combo: '3000×2' },
  { sMin: 6000, sMax: 7000, materials: [{ length: 3500, qty: 2 }], qty: 2, combo: '3500×2' },
  { sMin: 7000, sMax: 8000, materials: [{ length: 4000, qty: 2 }], qty: 2, combo: '4000×2' },
  { sMin: 8000, sMax: 8300, materials: [{ length: 4150, qty: 2 }], qty: 2, combo: '4150×2' },
];

// ═══════════════════════════════════════════════════════════════════
// 하단마감재 구성품 산출 기준서 (문서 기반)
// B = W0 (오픈사이즈 가로), 자재 단위길이: 3000, 4000 (무게평철은 2000)
// 철재: 하장바만 사용 (60×30)
// 스크린: 하장바(60×40) + 엘바 + 보강평철 + 무게평철
// ═══════════════════════════════════════════════════════════════════

// 하장바 자재 테이블 (철재: 60×30, 스크린: 60×40)
const bottomBarTable = [
  { bMin: 0, bMax: 3000, materials: [{ length: 3000, qty: 1 }] },
  { bMin: 3000, bMax: 4000, materials: [{ length: 4000, qty: 1 }] },
  { bMin: 4000, bMax: 6000, materials: [{ length: 3000, qty: 2 }] },
  { bMin: 6000, bMax: 7000, materials: [{ length: 3000, qty: 1 }, { length: 4000, qty: 1 }], combo: '3000+4000' },
  { bMin: 7000, bMax: 8000, materials: [{ length: 4000, qty: 2 }] },
];

// 엘바 자재 테이블 (스크린 전용, 규격: 17×60 / 2량 1세트)
const elbarTable = [
  { bMin: 0, bMax: 3000, materials: [{ length: 3000, qty: 2 }] },
  { bMin: 3000, bMax: 4000, materials: [{ length: 4000, qty: 2 }] },
  { bMin: 4000, bMax: 6000, materials: [{ length: 3000, qty: 4 }] },
  { bMin: 6000, bMax: 7000, materials: [{ length: 3000, qty: 2 }, { length: 4000, qty: 2 }], combo: '3000+4000×2' },
  { bMin: 7000, bMax: 8000, materials: [{ length: 4000, qty: 4 }] },
];

// 보강평철 자재 테이블 (스크린 전용, 규격: 50mm)
const reinforceTable = [
  { bMin: 0, bMax: 3000, materials: [{ length: 3000, qty: 1 }] },
  { bMin: 3000, bMax: 4000, materials: [{ length: 4000, qty: 1 }] },
  { bMin: 4000, bMax: 6000, materials: [{ length: 3000, qty: 2 }] },
  { bMin: 6000, bMax: 7000, materials: [{ length: 3000, qty: 1 }, { length: 4000, qty: 1 }], combo: '3000+4000' },
  { bMin: 7000, bMax: 8000, materials: [{ length: 4000, qty: 2 }] },
];

// 무게평철 자재 테이블 (스크린 전용, 규격: 50×12T, 단위: 2000mm, 두줄 삽입)
const weightFlatTable = [
  { bMin: 0, bMax: 3000, materials: [{ length: 2000, qty: 2 }] },
  { bMin: 3000, bMax: 4000, materials: [{ length: 2000, qty: 2 }] },
  { bMin: 4000, bMax: 6000, materials: [{ length: 2000, qty: 4 }] },
  { bMin: 6000, bMax: 7000, materials: [{ length: 2000, qty: 4 }] },
  { bMin: 7000, bMax: 8000, materials: [{ length: 2000, qty: 4 }] },
];

// ═══════════════════════════════════════════════════════════════════
// 환봉, 조인트바 산출 기준 (문서: 환봉, 조인트바 산출 기준)
// ═══════════════════════════════════════════════════════════════════

// 환봉 (스크린 전용 부자재)
// 자재 규격: 3000mm 고정, W1 구간별 수량 결정
const hwanbongQtyTable = [
  { w1Min: 0, w1Max: 3000, length: 3000, qty: 1 },
  { w1Min: 3000, w1Max: 6000, length: 3000, qty: 2 },
  { w1Min: 6000, w1Max: 9000, length: 3000, qty: 3 },
  { w1Min: 9000, w1Max: 12000, length: 3000, qty: 4 },
];

// 조인트바 산출 기준
// 기본 2개 고정 (양 끝 250mm 지점 설치)
// 중앙 여유공간 = W1 - 500 (mm)
// 여유 공간 내에 완전히 1000mm가 들어가는 횟수만큼 조인트바 추가
// 공식: 조인트바 수량 = 2 + FLOOR((W1 - 500) / 1000)
// 1000mm가 안 되는 나머지 구간에는 추가하지 않음

// ═══════════════════════════════════════════════════════════════════
// 각파이프 자재 수량 산출 기준 (문서: 각파이프 자재 수량 산출 기준)
// ═══════════════════════════════════════════════════════════════════
// 공통 기준:
// - 각파이프 자재는 3000mm, 6000mm 두 종류
// - 케이스 제작사이즈 L은 자재 수량 계산 기준
// - 자재 수량은 "기본 2개 + 자보강 갯수"에 따라 상수길이(P)를 계산하고,
//   그 길이에 따라 각파이프 자재가 몇 개 들어가는지 결정됨

// 스크린용 케이스 500*350
const squarePipeTableScreen = [
  { lMin: 0, lMax: 1600, mat3000: 3, mat6000: 0 },
  { lMin: 1600, lMax: 2800, mat3000: 4, mat6000: 0 },
  { lMin: 2800, lMax: 3000, mat3000: 5, mat6000: 0 },
  { lMin: 3000, lMax: 4000, mat3000: 1, mat6000: 3 },
  { lMin: 4000, lMax: 5200, mat3000: 1, mat6000: 4 },
  { lMin: 5200, lMax: 6400, mat3000: 1, mat6000: 5 },
];

// 철재용 케이스 650*500
const squarePipeTableSteel = [
  { lMin: 0, lMax: 1600, mat3000: 4, mat6000: 0 },
  { lMin: 1600, lMax: 2800, mat3000: 5, mat6000: 0 },
  { lMin: 2800, lMax: 3000, mat3000: 6, mat6000: 0 },
  { lMin: 3000, lMax: 4000, mat3000: 1, mat6000: 3 },
  { lMin: 4000, lMax: 5200, mat3000: 1, mat6000: 4 },
  { lMin: 5200, lMax: 6400, mat3000: 1, mat6000: 5 },
];

// ═══════════════════════════════════════════════════════════════════
// 품목별 단가 마스터 데이터
// ═══════════════════════════════════════════════════════════════════
const itemPriceMaster = [
  // ═══════════════════════════════════════════════════════════════════
  // 절곡부품 - 규칙: 품목코드+종류코드+모양&길이코드 (예: RC24, CB30)
  // ═══════════════════════════════════════════════════════════════════
  // 절곡부품 - 가이드레일 (R: 가이드레일, C: C형)
  { itemCode: 'RC24', itemName: '가이드레일(벽면형) C형 2438', category: '가이드레일', unitPrice: 15000, sellingPrice: 22000, unit: 'EA' },
  { itemCode: 'RC30', itemName: '가이드레일(벽면형) C형 3000', category: '가이드레일', unitPrice: 18000, sellingPrice: 27000, unit: 'EA' },
  { itemCode: 'RC35', itemName: '가이드레일(벽면형) C형 3500', category: '가이드레일', unitPrice: 21000, sellingPrice: 31500, unit: 'EA' },
  { itemCode: 'RC40', itemName: '가이드레일(벽면형) C형 4000', category: '가이드레일', unitPrice: 24000, sellingPrice: 36000, unit: 'EA' },
  { itemCode: 'RC43', itemName: '가이드레일(벽면형) C형 4300', category: '가이드레일', unitPrice: 26000, sellingPrice: 39000, unit: 'EA' },

  // 절곡부품 - 케이스 (C: 케이스, B: 후면코너부)
  { itemCode: 'CB12', itemName: '케이스(후면코너부) 1219', category: '케이스', unitPrice: 8000, sellingPrice: 12000, unit: 'EA' },
  { itemCode: 'CB24', itemName: '케이스(후면코너부) 2438', category: '케이스', unitPrice: 16000, sellingPrice: 24000, unit: 'EA' },
  { itemCode: 'CB30', itemName: '케이스(후면코너부) 3000', category: '케이스', unitPrice: 20000, sellingPrice: 30000, unit: 'EA' },
  { itemCode: 'CB35', itemName: '케이스(후면코너부) 3500', category: '케이스', unitPrice: 23000, sellingPrice: 34500, unit: 'EA' },
  { itemCode: 'CB40', itemName: '케이스(후면코너부) 4000', category: '케이스', unitPrice: 26000, sellingPrice: 39000, unit: 'EA' },

  // 절곡부품 - 하단마감재 (B: 하단마감재, E: EGI, S: SUS)
  { itemCode: 'BE30', itemName: '하단마감재(스크린) EGI 3000', category: '하단마감재', unitPrice: 12000, sellingPrice: 18000, unit: 'EA' },
  { itemCode: 'BE40', itemName: '하단마감재(스크린) EGI 4000', category: '하단마감재', unitPrice: 16000, sellingPrice: 24000, unit: 'EA' },
  { itemCode: 'BS30', itemName: '하단마감재(스크린) SUS 3000', category: '하단마감재', unitPrice: 18000, sellingPrice: 27000, unit: 'EA' },
  { itemCode: 'BS40', itemName: '하단마감재(스크린) SUS 4000', category: '하단마감재', unitPrice: 24000, sellingPrice: 36000, unit: 'EA' },

  // 절곡부품 - 연기차단재 (G: 연기차단재, I: 화이바원단)
  { itemCode: 'GI24', itemName: '연기차단재 화이바원단 2438', category: '연기차단재', unitPrice: 8000, sellingPrice: 12000, unit: 'EA' },
  { itemCode: 'GI30', itemName: '연기차단재 화이바원단 3000', category: '연기차단재', unitPrice: 10000, sellingPrice: 15000, unit: 'EA' },
  { itemCode: 'GI35', itemName: '연기차단재 화이바원단 3500', category: '연기차단재', unitPrice: 12000, sellingPrice: 18000, unit: 'EA' },
  { itemCode: 'GI40', itemName: '연기차단재 화이바원단 4000', category: '연기차단재', unitPrice: 13000, sellingPrice: 19500, unit: 'EA' },

  // ═══════════════════════════════════════════════════════════════════
  // 구매부품 - 규칙: 품목명-규격 (규격 = 전원+용량, 공백제거)
  // 예: 전동개폐기-220V150KG유선
  // ═══════════════════════════════════════════════════════════════════
  // 구매부품 - 전동개폐기
  { itemCode: '전동개폐기-220V150KG유선', itemName: '전동개폐기 150KG 220V 유선', category: '전동개폐기', unitPrice: 280000, sellingPrice: 380000, unit: 'EA' },
  { itemCode: '전동개폐기-220V150KG무선', itemName: '전동개폐기 150KG 220V 무선', category: '전동개폐기', unitPrice: 320000, sellingPrice: 430000, unit: 'EA' },
  { itemCode: '전동개폐기-220V300KG유선', itemName: '전동개폐기 300KG 220V 유선', category: '전동개폐기', unitPrice: 350000, sellingPrice: 480000, unit: 'EA' },
  { itemCode: '전동개폐기-220V300KG무선', itemName: '전동개폐기 300KG 220V 무선', category: '전동개폐기', unitPrice: 390000, sellingPrice: 530000, unit: 'EA' },
  { itemCode: '전동개폐기-220V400KG유선', itemName: '전동개폐기 400KG 220V 유선', category: '전동개폐기', unitPrice: 420000, sellingPrice: 580000, unit: 'EA' },
  { itemCode: '전동개폐기-220V400KG무선', itemName: '전동개폐기 400KG 220V 무선', category: '전동개폐기', unitPrice: 460000, sellingPrice: 630000, unit: 'EA' },
  { itemCode: '전동개폐기-220V500KG유선', itemName: '전동개폐기 500KG 220V 유선', category: '전동개폐기', unitPrice: 520000, sellingPrice: 720000, unit: 'EA' },
  { itemCode: '전동개폐기-220V600KG유선', itemName: '전동개폐기 600KG 220V 유선', category: '전동개폐기', unitPrice: 620000, sellingPrice: 860000, unit: 'EA' },
  { itemCode: '전동개폐기-220V800KG유선', itemName: '전동개폐기 800KG 220V 유선', category: '전동개폐기', unitPrice: 780000, sellingPrice: 1080000, unit: 'EA' },
  { itemCode: '전동개폐기-220V1000KG유선', itemName: '전동개폐기 1000KG 220V 유선', category: '전동개폐기', unitPrice: 950000, sellingPrice: 1320000, unit: 'EA' },
  { itemCode: '전동개폐기-380V150KG유선', itemName: '전동개폐기 150KG 380V 유선', category: '전동개폐기', unitPrice: 290000, sellingPrice: 395000, unit: 'EA' },
  { itemCode: '전동개폐기-380V300KG유선', itemName: '전동개폐기 300KG 380V 유선', category: '전동개폐기', unitPrice: 360000, sellingPrice: 495000, unit: 'EA' },
  { itemCode: '전동개폐기-380V400KG유선', itemName: '전동개폐기 400KG 380V 유선', category: '전동개폐기', unitPrice: 430000, sellingPrice: 595000, unit: 'EA' },
  { itemCode: '전동개폐기-380V500KG유선', itemName: '전동개폐기 500KG 380V 유선', category: '전동개폐기', unitPrice: 530000, sellingPrice: 735000, unit: 'EA' },
  { itemCode: '전동개폐기-380V600KG유선', itemName: '전동개폐기 600KG 380V 유선', category: '전동개폐기', unitPrice: 630000, sellingPrice: 875000, unit: 'EA' },

  // 구매부품 - 연동제어기
  { itemCode: '연동제어기-매립형유선', itemName: '연동제어기 매립형 유선', category: '연동제어기', unitPrice: 85000, sellingPrice: 120000, unit: 'EA' },
  { itemCode: '연동제어기-매립형무선', itemName: '연동제어기 매립형 무선', category: '연동제어기', unitPrice: 95000, sellingPrice: 135000, unit: 'EA' },
  { itemCode: '연동제어기-노출형유선', itemName: '연동제어기 노출형 유선', category: '연동제어기', unitPrice: 75000, sellingPrice: 105000, unit: 'EA' },
  { itemCode: '연동제어기-노출형무선', itemName: '연동제어기 노출형 무선', category: '연동제어기', unitPrice: 85000, sellingPrice: 120000, unit: 'EA' },

  // 구매부품 - 감기샤프트
  { itemCode: '감기샤프트-60.5×2.9TL3000', itemName: '감기샤프트 60.5×2.9T L:3000', category: '감기샤프트', unitPrice: 45000, sellingPrice: 65000, unit: 'EA' },
  { itemCode: '감기샤프트-60.5×2.9TL4500', itemName: '감기샤프트 60.5×2.9T L:4500', category: '감기샤프트', unitPrice: 65000, sellingPrice: 95000, unit: 'EA' },
  { itemCode: '감기샤프트-76.3×2.8TL3000', itemName: '감기샤프트 76.3×2.8T L:3000', category: '감기샤프트', unitPrice: 55000, sellingPrice: 80000, unit: 'EA' },
  { itemCode: '감기샤프트-76.3×2.8TL4500', itemName: '감기샤프트 76.3×2.8T L:4500', category: '감기샤프트', unitPrice: 75000, sellingPrice: 110000, unit: 'EA' },
  { itemCode: '감기샤프트-89.1×2.8TL6000', itemName: '감기샤프트 89.1×2.8T L:6000', category: '감기샤프트', unitPrice: 95000, sellingPrice: 140000, unit: 'EA' },
  { itemCode: '감기샤프트-101.6×2.8TL6000', itemName: '감기샤프트 101.6×2.8T L:6000', category: '감기샤프트', unitPrice: 110000, sellingPrice: 160000, unit: 'EA' },
  { itemCode: '감기샤프트-114.3×2TL7000', itemName: '감기샤프트 114.3×2T L:7000', category: '감기샤프트', unitPrice: 130000, sellingPrice: 190000, unit: 'EA' },
  { itemCode: '감기샤프트-139.8×2.9TL8000', itemName: '감기샤프트 139.8×2.9T L:8000', category: '감기샤프트', unitPrice: 165000, sellingPrice: 240000, unit: 'EA' },
  { itemCode: '감기샤프트-165.2×3.3TL8200', itemName: '감기샤프트 165.2×3.3T L:8200', category: '감기샤프트', unitPrice: 195000, sellingPrice: 285000, unit: 'EA' },

  // 구매부품 - 브라켓/앵글
  { itemCode: '브라켓-380×180', itemName: '브라켓 380×180', category: '브라켓', unitPrice: 25000, sellingPrice: 38000, unit: 'SET' },
  { itemCode: '브라켓-530×320', itemName: '브라켓 530×320', category: '브라켓', unitPrice: 35000, sellingPrice: 52000, unit: 'SET' },
  { itemCode: '브라켓-600×350', itemName: '브라켓 600×350', category: '브라켓', unitPrice: 42000, sellingPrice: 63000, unit: 'SET' },
  { itemCode: '브라켓-690×390', itemName: '브라켓 690×390', category: '브라켓', unitPrice: 50000, sellingPrice: 75000, unit: 'SET' },
  { itemCode: '받침용앵글-40×40×380', itemName: '받침용앵글 40×40×380', category: '앵글', unitPrice: 18000, sellingPrice: 27000, unit: 'SET' },
  { itemCode: '받침용앵글-50×50×530', itemName: '받침용앵글 50×50×530', category: '앵글', unitPrice: 25000, sellingPrice: 38000, unit: 'SET' },
  { itemCode: '받침용앵글-50×50×600', itemName: '받침용앵글 50×50×600', category: '앵글', unitPrice: 28000, sellingPrice: 42000, unit: 'SET' },
  { itemCode: '받침용앵글-50×50×690', itemName: '받침용앵글 50×50×690', category: '앵글', unitPrice: 32000, sellingPrice: 48000, unit: 'SET' },

  // ═══════════════════════════════════════════════════════════════════
  // 부자재 - 규칙: 품목명-규격
  // 예: 환봉-3000, 각파이프-30×30L3000
  // ═══════════════════════════════════════════════════════════════════
  { itemCode: '환봉-3000', itemName: '환봉 3000', category: '환봉', unitPrice: 5000, sellingPrice: 7500, unit: 'EA' },
  { itemCode: '조인트바-', itemName: '조인트바', category: '조인트바', unitPrice: 3500, sellingPrice: 5200, unit: 'EA' },
  { itemCode: '각파이프-30×30L3000', itemName: '각파이프 30×30 L:3000', category: '각파이프', unitPrice: 8000, sellingPrice: 12000, unit: 'EA' },
  { itemCode: '각파이프-30×30L6000', itemName: '각파이프 30×30 L:6000', category: '각파이프', unitPrice: 15000, sellingPrice: 22500, unit: 'EA' },

  // 하단마감재 부자재
  { itemCode: '하장바-60×30L3000', itemName: '하장바 60×30 L:3000', category: '하장바', unitPrice: 12000, sellingPrice: 18000, unit: 'EA' },
  { itemCode: '하장바-60×30L4000', itemName: '하장바 60×30 L:4000', category: '하장바', unitPrice: 16000, sellingPrice: 24000, unit: 'EA' },
  { itemCode: '엘바-17×60L3000', itemName: '엘바 17×60 L:3000', category: '엘바', unitPrice: 8000, sellingPrice: 12000, unit: 'EA' },
  { itemCode: '엘바-17×60L4000', itemName: '엘바 17×60 L:4000', category: '엘바', unitPrice: 10000, sellingPrice: 15000, unit: 'EA' },
  { itemCode: '보강평철-50mmL3000', itemName: '보강평철 50mm L:3000', category: '보강평철', unitPrice: 6000, sellingPrice: 9000, unit: 'EA' },
  { itemCode: '보강평철-50mmL4000', itemName: '보강평철 50mm L:4000', category: '보강평철', unitPrice: 8000, sellingPrice: 12000, unit: 'EA' },
  { itemCode: '무게평철-50×12TL2000', itemName: '무게평철 50×12T L:2000', category: '무게평철', unitPrice: 15000, sellingPrice: 22500, unit: 'EA' },

  // 마구리/상부덮개
  { itemCode: '마구리-', itemName: '마구리', category: '마구리', unitPrice: 15000, sellingPrice: 22500, unit: 'SET' },
  { itemCode: '상부덮개-1219', itemName: '상부덮개 1219', category: '상부덮개', unitPrice: 8000, sellingPrice: 12000, unit: 'EA' },

  // 하부 BASE
  { itemCode: '하부BASE-벽면형', itemName: '하부BASE(벽면형)', category: 'BASE', unitPrice: 25000, sellingPrice: 37500, unit: 'SET' },
  { itemCode: '하부BASE-코너형', itemName: '하부BASE(코너형)', category: 'BASE', unitPrice: 30000, sellingPrice: 45000, unit: 'SET' },

  // 검사비
  { itemCode: '검사비-', itemName: '검사비', category: '검사비', unitPrice: 0, sellingPrice: 50000, unit: 'SET' },
];

// ═══════════════════════════════════════════════════════════════════════════════
// 통합 샘플 데이터 (거래처→현장→견적→수주→생산→출하→품질→회계 전 과정 연동)
// 100개 프로젝트 기준 완전한 데이터셋
// ═══════════════════════════════════════════════════════════════════════════════

// 1. 거래처 마스터 (10개) - 공통코드관리 규칙 적용: C-###
const integratedCustomerMaster = [
  {
    id: 1, code: 'C-001', name: '삼성물산(주)', bizNo: '124-81-00001', ceo: '오세철', bizType: '건설업', bizItem: '종합건설',
    address: '서울시 강남구 테헤란로 128', tel: '02-2145-5000', fax: '02-2145-5001', email: 'contract@samsung.com',
    creditGrade: 'A', creditLimit: 5000000000, currentBalance: 0, manager: '김건설', managerTel: '010-1234-5678',
    paymentTerms: '월말마감익월25일', discountRate: 5, status: '활성', createdAt: '2020-01-15'
  },
  {
    id: 2, code: 'C-002', name: '현대건설(주)', bizNo: '104-81-00002', ceo: '윤영준', bizType: '건설업', bizItem: '종합건설',
    address: '서울시 종로구 율곡로 75', tel: '02-746-1114', fax: '02-746-1115', email: 'contract@hdec.kr',
    creditGrade: 'A', creditLimit: 5000000000, currentBalance: 0, manager: '이현대', managerTel: '010-2345-6789',
    paymentTerms: '월말마감익월25일', discountRate: 5, status: '활성', createdAt: '2020-02-20'
  },
  {
    id: 3, code: 'C-003', name: '대우건설(주)', bizNo: '117-81-00003', ceo: '백정완', bizType: '건설업', bizItem: '종합건설',
    address: '서울시 중구 을지로 170', tel: '02-2129-3114', fax: '02-2129-3115', email: 'order@daewoo.com',
    creditGrade: 'B', creditLimit: 3000000000, currentBalance: 150000000, manager: '박대우', managerTel: '010-3456-7890',
    paymentTerms: '입금후출고', discountRate: 3, status: '활성', createdAt: '2020-03-10'
  },
  {
    id: 4, code: 'C-004', name: 'GS건설(주)', bizNo: '104-81-00004', ceo: '허윤홍', bizType: '건설업', bizItem: '종합건설',
    address: '서울시 강남구 논현로 508', tel: '02-3429-1114', fax: '02-3429-1115', email: 'purchase@gsconst.co.kr',
    creditGrade: 'A', creditLimit: 4000000000, currentBalance: 0, manager: '최지에스', managerTel: '010-4567-8901',
    paymentTerms: '월말마감익월25일', discountRate: 4, status: '활성', createdAt: '2020-04-05'
  },
  {
    id: 5, code: 'C-005', name: '포스코건설(주)', bizNo: '602-81-00005', ceo: '한성희', bizType: '건설업', bizItem: '종합건설',
    address: '인천시 연수구 아카데미로 86', tel: '032-748-0114', fax: '032-748-0115', email: 'order@poscoenc.com',
    creditGrade: 'A', creditLimit: 4000000000, currentBalance: 0, manager: '정포스코', managerTel: '010-5678-9012',
    paymentTerms: '월말마감익월25일', discountRate: 5, status: '활성', createdAt: '2020-05-15'
  },
  {
    id: 6, code: 'C-006', name: '롯데건설(주)', bizNo: '110-81-00006', ceo: '하석주', bizType: '건설업', bizItem: '종합건설',
    address: '서울시 영등포구 국제금융로 2길 15', tel: '02-3479-5114', fax: '02-3479-5115', email: 'contract@lotteenc.co.kr',
    creditGrade: 'B', creditLimit: 3000000000, currentBalance: 80000000, manager: '강롯데', managerTel: '010-6789-0123',
    paymentTerms: '입금후출고', discountRate: 3, status: '활성', createdAt: '2020-06-20'
  },
  {
    id: 7, code: 'C-007', name: '호반건설(주)', bizNo: '134-81-00007', ceo: '김상열', bizType: '건설업', bizItem: '주택건설',
    address: '서울시 서초구 강남대로 465', tel: '02-532-3000', fax: '02-532-3001', email: 'purchase@hoban.co.kr',
    creditGrade: 'B', creditLimit: 2000000000, currentBalance: 45000000, manager: '임호반', managerTel: '010-7890-1234',
    paymentTerms: '입금후출고', discountRate: 2, status: '활성', createdAt: '2020-07-10'
  },
  {
    id: 8, code: 'C-008', name: '한화건설(주)', bizNo: '135-81-00008', ceo: '최광호', bizType: '건설업', bizItem: '종합건설',
    address: '서울시 중구 청계천로 86', tel: '02-729-2700', fax: '02-729-2701', email: 'order@hwconst.co.kr',
    creditGrade: 'A', creditLimit: 3500000000, currentBalance: 0, manager: '윤한화', managerTel: '010-8901-2345',
    paymentTerms: '월말마감익월25일', discountRate: 4, status: '활성', createdAt: '2020-08-05'
  },
  {
    id: 9, code: 'C-009', name: '태영건설(주)', bizNo: '106-81-00009', ceo: '박인규', bizType: '건설업', bizItem: '종합건설',
    address: '서울시 강남구 영동대로 511', tel: '02-2191-7114', fax: '02-2191-7115', email: 'contract@tyconst.co.kr',
    creditGrade: 'C', creditLimit: 1000000000, currentBalance: 200000000, manager: '서태영', managerTel: '010-9012-3456',
    paymentTerms: '경리승인', discountRate: 0, status: '활성', createdAt: '2020-09-15'
  },
  {
    id: 10, code: 'C-010', name: '두산건설(주)', bizNo: '101-81-00010', ceo: '박홍식', bizType: '건설업', bizItem: '종합건설',
    address: '서울시 영등포구 여의대로 24', tel: '02-3398-0114', fax: '02-3398-0115', email: 'purchase@doosanenc.com',
    creditGrade: 'B', creditLimit: 2500000000, currentBalance: 120000000, manager: '한두산', managerTel: '010-0123-4567',
    paymentTerms: '입금후출고', discountRate: 3, status: '활성', createdAt: '2020-10-20'
  },
];

// 2. 현장 마스터 (50개) - 각 거래처별 5개 현장
const integratedSiteMaster = [
  // 삼성물산 현장 (5개)
  { id: 1, code: 'S-001', name: '래미안 원베일리', customerId: 1, customerName: '삼성물산(주)', address: '서울시 서초구 반포동 1-1', manager: '김현장', tel: '010-1111-0001', status: '진행중', startDate: '2024-06-01', endDate: '2026-12-31', totalAmount: 850000000 },
  { id: 2, code: 'S-002', name: '래미안 포레카운티', customerId: 1, customerName: '삼성물산(주)', address: '경기도 수원시 영통구 매탄동', manager: '이현장', tel: '010-1111-0002', status: '진행중', startDate: '2024-08-15', endDate: '2027-02-28', totalAmount: 650000000 },
  { id: 3, code: 'S-003', name: '삼성 서초사옥', customerId: 1, customerName: '삼성물산(주)', address: '서울시 서초구 서초동 1320-10', manager: '박현장', tel: '010-1111-0003', status: '진행중', startDate: '2024-10-01', endDate: '2026-06-30', totalAmount: 420000000 },
  { id: 4, code: 'S-004', name: '래미안 리더스원', customerId: 1, customerName: '삼성물산(주)', address: '서울시 송파구 문정동', manager: '최현장', tel: '010-1111-0004', status: '계약', startDate: '2025-03-01', endDate: '2027-08-31', totalAmount: 780000000 },
  { id: 5, code: 'S-005', name: '삼성 부산사옥', customerId: 1, customerName: '삼성물산(주)', address: '부산시 해운대구 우동', manager: '정현장', tel: '010-1111-0005', status: '계약', startDate: '2025-04-01', endDate: '2026-09-30', totalAmount: 350000000 },
  // 현대건설 현장 (5개)
  { id: 6, code: 'S-006', name: '힐스테이트 광교중앙역', customerId: 2, customerName: '현대건설(주)', address: '경기도 수원시 영통구 이의동', manager: '강현장', tel: '010-2222-0001', status: '진행중', startDate: '2024-05-01', endDate: '2026-10-31', totalAmount: 920000000 },
  { id: 7, code: 'S-007', name: '디에이치 아너힐즈', customerId: 2, customerName: '현대건설(주)', address: '서울시 강동구 상일동', manager: '임현장', tel: '010-2222-0002', status: '진행중', startDate: '2024-07-15', endDate: '2027-01-31', totalAmount: 1100000000 },
  { id: 8, code: 'S-008', name: '현대 판교사옥', customerId: 2, customerName: '현대건설(주)', address: '경기도 성남시 분당구 판교동', manager: '조현장', tel: '010-2222-0003', status: '진행중', startDate: '2024-09-01', endDate: '2026-03-31', totalAmount: 480000000 },
  { id: 9, code: 'S-009', name: '힐스테이트 송도더스카이', customerId: 2, customerName: '현대건설(주)', address: '인천시 연수구 송도동', manager: '윤현장', tel: '010-2222-0004', status: '계약', startDate: '2025-02-01', endDate: '2027-06-30', totalAmount: 880000000 },
  { id: 10, code: 'S-010', name: '힐스테이트 대구역', customerId: 2, customerName: '현대건설(주)', address: '대구시 중구 동인동', manager: '장현장', tel: '010-2222-0005', status: '계약', startDate: '2025-05-01', endDate: '2027-09-30', totalAmount: 720000000 },
  // 대우건설 현장 (5개)
  { id: 11, code: 'S-011', name: '푸르지오 서울숲', customerId: 3, customerName: '대우건설(주)', address: '서울시 성동구 성수동', manager: '배현장', tel: '010-3333-0001', status: '진행중', startDate: '2024-04-01', endDate: '2026-08-31', totalAmount: 680000000 },
  { id: 12, code: 'S-012', name: '푸르지오 시티', customerId: 3, customerName: '대우건설(주)', address: '경기도 안양시 동안구', manager: '나현장', tel: '010-3333-0002', status: '진행중', startDate: '2024-06-15', endDate: '2026-11-30', totalAmount: 520000000 },
  { id: 13, code: 'S-013', name: '대우 마곡사옥', customerId: 3, customerName: '대우건설(주)', address: '서울시 강서구 마곡동', manager: '우현장', tel: '010-3333-0003', status: '진행중', startDate: '2024-08-01', endDate: '2026-01-31', totalAmount: 380000000 },
  { id: 14, code: 'S-014', name: '푸르지오 더샵', customerId: 3, customerName: '대우건설(주)', address: '경기도 화성시 동탄', manager: '공현장', tel: '010-3333-0004', status: '계약', startDate: '2025-01-01', endDate: '2027-04-30', totalAmount: 950000000 },
  { id: 15, code: 'S-015', name: '푸르지오 벨라듀', customerId: 3, customerName: '대우건설(주)', address: '부산시 남구 대연동', manager: '마현장', tel: '010-3333-0005', status: '계약', startDate: '2025-03-01', endDate: '2027-07-31', totalAmount: 620000000 },
  // GS건설 현장 (5개)
  { id: 16, code: 'S-016', name: '자이 분당센트럴', customerId: 4, customerName: 'GS건설(주)', address: '경기도 성남시 분당구 정자동', manager: '하현장', tel: '010-4444-0001', status: '진행중', startDate: '2024-03-01', endDate: '2026-07-31', totalAmount: 1050000000 },
  { id: 17, code: 'S-017', name: '자이 안산그랑시티', customerId: 4, customerName: 'GS건설(주)', address: '경기도 안산시 상록구', manager: '주현장', tel: '010-4444-0002', status: '진행중', startDate: '2024-05-15', endDate: '2026-09-30', totalAmount: 780000000 },
  { id: 18, code: 'S-018', name: 'GS 판교R&D센터', customerId: 4, customerName: 'GS건설(주)', address: '경기도 성남시 분당구 삼평동', manager: '차현장', tel: '010-4444-0003', status: '진행중', startDate: '2024-07-01', endDate: '2025-12-31', totalAmount: 420000000 },
  { id: 19, code: 'S-019', name: '자이 대치에코', customerId: 4, customerName: 'GS건설(주)', address: '서울시 강남구 대치동', manager: '고현장', tel: '010-4444-0004', status: '완료', startDate: '2023-06-01', endDate: '2025-01-31', totalAmount: 890000000 },
  { id: 20, code: 'S-020', name: '자이 광교엘리포레', customerId: 4, customerName: 'GS건설(주)', address: '경기도 수원시 영통구 광교', manager: '노현장', tel: '010-4444-0005', status: '계약', startDate: '2025-04-01', endDate: '2027-08-31', totalAmount: 1200000000 },
  // 포스코건설 현장 (5개)
  { id: 21, code: 'S-021', name: '더샵 송도센트럴시티', customerId: 5, customerName: '포스코건설(주)', address: '인천시 연수구 송도동', manager: '도현장', tel: '010-5555-0001', status: '진행중', startDate: '2024-02-01', endDate: '2026-06-30', totalAmount: 980000000 },
  { id: 22, code: 'S-022', name: '더샵 청라시티', customerId: 5, customerName: '포스코건설(주)', address: '인천시 서구 청라동', manager: '라현장', tel: '010-5555-0002', status: '진행중', startDate: '2024-04-15', endDate: '2026-08-31', totalAmount: 720000000 },
  { id: 23, code: 'S-023', name: '포스코 광양연구소', customerId: 5, customerName: '포스코건설(주)', address: '전남 광양시 금호동', manager: '마현장', tel: '010-5555-0003', status: '진행중', startDate: '2024-06-01', endDate: '2025-11-30', totalAmount: 350000000 },
  { id: 24, code: 'S-024', name: '더샵 광교테크노밸리', customerId: 5, customerName: '포스코건설(주)', address: '경기도 수원시 영통구', manager: '바현장', tel: '010-5555-0004', status: '완료', startDate: '2023-04-01', endDate: '2024-12-31', totalAmount: 650000000 },
  { id: 25, code: 'S-025', name: '더샵 위례신도시', customerId: 5, customerName: '포스코건설(주)', address: '경기도 성남시 위례동', manager: '사현장', tel: '010-5555-0005', status: '계약', startDate: '2025-06-01', endDate: '2027-10-31', totalAmount: 1100000000 },
  // 롯데건설 현장 (5개)
  { id: 26, code: 'S-026', name: '롯데캐슬 골드파크', customerId: 6, customerName: '롯데건설(주)', address: '서울시 강서구 가양동', manager: '아현장', tel: '010-6666-0001', status: '진행중', startDate: '2024-01-15', endDate: '2026-05-31', totalAmount: 850000000 },
  { id: 27, code: 'S-027', name: '롯데캐슬 시그니처', customerId: 6, customerName: '롯데건설(주)', address: '경기도 부천시 중동', manager: '자현장', tel: '010-6666-0002', status: '진행중', startDate: '2024-03-01', endDate: '2026-07-31', totalAmount: 680000000 },
  { id: 28, code: 'S-028', name: '롯데월드타워 증축', customerId: 6, customerName: '롯데건설(주)', address: '서울시 송파구 잠실동', manager: '차현장', tel: '010-6666-0003', status: '진행중', startDate: '2024-05-01', endDate: '2025-10-31', totalAmount: 450000000 },
  { id: 29, code: 'S-029', name: '롯데캐슬 더퍼스트', customerId: 6, customerName: '롯데건설(주)', address: '대전시 서구 둔산동', manager: '카현장', tel: '010-6666-0004', status: '완료', startDate: '2023-03-01', endDate: '2024-11-30', totalAmount: 520000000 },
  { id: 30, code: 'S-030', name: '롯데캐슬 프리미어', customerId: 6, customerName: '롯데건설(주)', address: '경기도 김포시 장기동', manager: '타현장', tel: '010-6666-0005', status: '계약', startDate: '2025-07-01', endDate: '2027-11-30', totalAmount: 920000000 },
  // 호반건설 현장 (5개)
  { id: 31, code: 'S-031', name: '호반써밋 개포', customerId: 7, customerName: '호반건설(주)', address: '서울시 강남구 개포동', manager: '파현장', tel: '010-7777-0001', status: '진행중', startDate: '2024-02-15', endDate: '2026-06-30', totalAmount: 580000000 },
  { id: 32, code: 'S-032', name: '호반베르디움 위례', customerId: 7, customerName: '호반건설(주)', address: '경기도 하남시 위례동', manager: '하현장', tel: '010-7777-0002', status: '진행중', startDate: '2024-04-01', endDate: '2026-08-31', totalAmount: 450000000 },
  { id: 33, code: 'S-033', name: '호반써밋 스카이폴리스', customerId: 7, customerName: '호반건설(주)', address: '경기도 의왕시 포일동', manager: '거현장', tel: '010-7777-0003', status: '진행중', startDate: '2024-06-15', endDate: '2026-10-31', totalAmount: 620000000 },
  { id: 34, code: 'S-034', name: '호반베르디움 산본', customerId: 7, customerName: '호반건설(주)', address: '경기도 군포시 산본동', manager: '너현장', tel: '010-7777-0004', status: '완료', startDate: '2023-05-01', endDate: '2024-10-31', totalAmount: 380000000 },
  { id: 35, code: 'S-035', name: '호반써밋 동탄', customerId: 7, customerName: '호반건설(주)', address: '경기도 화성시 동탄', manager: '더현장', tel: '010-7777-0005', status: '계약', startDate: '2025-08-01', endDate: '2027-12-31', totalAmount: 750000000 },
  // 한화건설 현장 (5개)
  { id: 36, code: 'S-036', name: '포레나 용산', customerId: 8, customerName: '한화건설(주)', address: '서울시 용산구 한남동', manager: '러현장', tel: '010-8888-0001', status: '진행중', startDate: '2024-03-15', endDate: '2026-07-31', totalAmount: 920000000 },
  { id: 37, code: 'S-037', name: '포레나 세종시티', customerId: 8, customerName: '한화건설(주)', address: '세종시 나성동', manager: '머현장', tel: '010-8888-0002', status: '진행중', startDate: '2024-05-01', endDate: '2026-09-30', totalAmount: 780000000 },
  { id: 38, code: 'S-038', name: '한화 대전본사', customerId: 8, customerName: '한화건설(주)', address: '대전시 유성구 덕명동', manager: '버현장', tel: '010-8888-0003', status: '진행중', startDate: '2024-07-01', endDate: '2025-12-31', totalAmount: 380000000 },
  { id: 39, code: 'S-039', name: '포레나 청주', customerId: 8, customerName: '한화건설(주)', address: '충북 청주시 서원구', manager: '서현장', tel: '010-8888-0004', status: '완료', startDate: '2023-07-01', endDate: '2025-01-31', totalAmount: 520000000 },
  { id: 40, code: 'S-040', name: '포레나 해운대', customerId: 8, customerName: '한화건설(주)', address: '부산시 해운대구 우동', manager: '어현장', tel: '010-8888-0005', status: '계약', startDate: '2025-09-01', endDate: '2028-01-31', totalAmount: 1050000000 },
  // 태영건설 현장 (5개)
  { id: 41, code: 'S-041', name: '데시앙 마포', customerId: 9, customerName: '태영건설(주)', address: '서울시 마포구 상암동', manager: '저현장', tel: '010-9999-0001', status: '진행중', startDate: '2024-04-01', endDate: '2026-08-31', totalAmount: 480000000 },
  { id: 42, code: 'S-042', name: '데시앙 부평', customerId: 9, customerName: '태영건설(주)', address: '인천시 부평구 삼산동', manager: '처현장', tel: '010-9999-0002', status: '진행중', startDate: '2024-06-15', endDate: '2026-10-31', totalAmount: 350000000 },
  { id: 43, code: 'S-043', name: '태영 물류센터', customerId: 9, customerName: '태영건설(주)', address: '경기도 이천시 마장면', manager: '커현장', tel: '010-9999-0003', status: '진행중', startDate: '2024-08-01', endDate: '2025-11-30', totalAmount: 280000000 },
  { id: 44, code: 'S-044', name: '데시앙 광명', customerId: 9, customerName: '태영건설(주)', address: '경기도 광명시 철산동', manager: '터현장', tel: '010-9999-0004', status: '완료', startDate: '2023-08-01', endDate: '2024-12-31', totalAmount: 420000000 },
  { id: 45, code: 'S-045', name: '데시앙 천안', customerId: 9, customerName: '태영건설(주)', address: '충남 천안시 서북구', manager: '퍼현장', tel: '010-9999-0005', status: '계약', startDate: '2025-10-01', endDate: '2028-02-28', totalAmount: 680000000 },
  // 두산건설 현장 (5개)
  { id: 46, code: 'S-046', name: '위브더제니스', customerId: 10, customerName: '두산건설(주)', address: '서울시 영등포구 여의도동', manager: '허현장', tel: '010-0000-0001', status: '진행중', startDate: '2024-01-01', endDate: '2026-05-31', totalAmount: 880000000 },
  { id: 47, code: 'S-047', name: '위브센티움', customerId: 10, customerName: '두산건설(주)', address: '경기도 고양시 일산동구', manager: '고현장', tel: '010-0000-0002', status: '진행중', startDate: '2024-03-15', endDate: '2026-07-31', totalAmount: 650000000 },
  { id: 48, code: 'S-048', name: '두산 인천연구소', customerId: 10, customerName: '두산건설(주)', address: '인천시 연수구 송도동', manager: '노현장', tel: '010-0000-0003', status: '진행중', startDate: '2024-05-01', endDate: '2025-09-30', totalAmount: 320000000 },
  { id: 49, code: 'S-049', name: '위브트레보', customerId: 10, customerName: '두산건설(주)', address: '경기도 용인시 수지구', manager: '모현장', tel: '010-0000-0004', status: '완료', startDate: '2023-04-01', endDate: '2024-09-30', totalAmount: 450000000 },
  { id: 50, code: 'S-050', name: '위브프리모', customerId: 10, customerName: '두산건설(주)', address: '대전시 중구 대흥동', manager: '보현장', tel: '010-0000-0005', status: '계약', startDate: '2025-11-01', endDate: '2028-03-31', totalAmount: 780000000 },
  // ======== 추가 현장 (51~100) - 각 거래처별 5개 추가 ========
  // 삼성물산 추가현장
  { id: 51, code: 'S-051', name: '래미안 역삼퍼스트', customerId: 1, customerName: '삼성물산(주)', address: '서울시 강남구 역삼동', manager: '권현장', tel: '010-1111-0006', status: '진행중', startDate: '2024-11-01', endDate: '2027-03-31', totalAmount: 920000000 },
  { id: 52, code: 'S-052', name: '래미안 목동센트럴', customerId: 1, customerName: '삼성물산(주)', address: '서울시 양천구 목동', manager: '금현장', tel: '010-1111-0007', status: '계약', startDate: '2025-02-01', endDate: '2027-06-30', totalAmount: 780000000 },
  { id: 53, code: 'S-053', name: '삼성 강북물류센터', customerId: 1, customerName: '삼성물산(주)', address: '서울시 강북구 미아동', manager: '기현장', tel: '010-1111-0008', status: '진행중', startDate: '2024-09-15', endDate: '2026-01-31', totalAmount: 450000000 },
  { id: 54, code: 'S-054', name: '래미안 일산엘포레', customerId: 1, customerName: '삼성물산(주)', address: '경기도 고양시 일산서구', manager: '남현장', tel: '010-1111-0009', status: '계약', startDate: '2025-05-01', endDate: '2027-09-30', totalAmount: 1100000000 },
  { id: 55, code: 'S-055', name: '래미안 광명센트럴', customerId: 1, customerName: '삼성물산(주)', address: '경기도 광명시 광명동', manager: '단현장', tel: '010-1111-0010', status: '진행중', startDate: '2024-07-01', endDate: '2026-11-30', totalAmount: 680000000 },
  // 현대건설 추가현장
  { id: 56, code: 'S-056', name: '힐스테이트 천안', customerId: 2, customerName: '현대건설(주)', address: '충남 천안시 서북구', manager: '도현장', tel: '010-2222-0006', status: '진행중', startDate: '2024-08-01', endDate: '2026-12-31', totalAmount: 820000000 },
  { id: 57, code: 'S-057', name: '디에이치 레이크시티', customerId: 2, customerName: '현대건설(주)', address: '경기도 김포시 구래동', manager: '라현장', tel: '010-2222-0007', status: '계약', startDate: '2025-03-01', endDate: '2027-07-31', totalAmount: 950000000 },
  { id: 58, code: 'S-058', name: '현대 수원연구소', customerId: 2, customerName: '현대건설(주)', address: '경기도 수원시 팔달구', manager: '마현장', tel: '010-2222-0008', status: '진행중', startDate: '2024-10-15', endDate: '2026-02-28', totalAmount: 380000000 },
  { id: 59, code: 'S-059', name: '힐스테이트 제주', customerId: 2, customerName: '현대건설(주)', address: '제주시 노형동', manager: '바현장', tel: '010-2222-0009', status: '계약', startDate: '2025-06-01', endDate: '2027-10-31', totalAmount: 720000000 },
  { id: 60, code: 'S-060', name: '힐스테이트 평택', customerId: 2, customerName: '현대건설(주)', address: '경기도 평택시 고덕동', manager: '사현장', tel: '010-2222-0010', status: '진행중', startDate: '2024-12-01', endDate: '2027-04-30', totalAmount: 1050000000 },
  // 대우건설 추가현장
  { id: 61, code: 'S-061', name: '푸르지오 인천파크', customerId: 3, customerName: '대우건설(주)', address: '인천시 서구 검단동', manager: '아현장', tel: '010-3333-0006', status: '진행중', startDate: '2024-06-01', endDate: '2026-10-31', totalAmount: 720000000 },
  { id: 62, code: 'S-062', name: '푸르지오 대전유성', customerId: 3, customerName: '대우건설(주)', address: '대전시 유성구 봉명동', manager: '자현장', tel: '010-3333-0007', status: '계약', startDate: '2025-04-01', endDate: '2027-08-31', totalAmount: 580000000 },
  { id: 63, code: 'S-063', name: '대우 부산물류', customerId: 3, customerName: '대우건설(주)', address: '부산시 강서구 녹산동', manager: '차현장', tel: '010-3333-0008', status: '진행중', startDate: '2024-09-01', endDate: '2026-01-31', totalAmount: 420000000 },
  { id: 64, code: 'S-064', name: '푸르지오 세종시티', customerId: 3, customerName: '대우건설(주)', address: '세종시 어진동', manager: '카현장', tel: '010-3333-0009', status: '계약', startDate: '2025-07-01', endDate: '2027-11-30', totalAmount: 890000000 },
  { id: 65, code: 'S-065', name: '푸르지오 수원역', customerId: 3, customerName: '대우건설(주)', address: '경기도 수원시 팔달구', manager: '타현장', tel: '010-3333-0010', status: '진행중', startDate: '2024-11-15', endDate: '2027-03-31', totalAmount: 750000000 },
  // GS건설 추가현장
  { id: 66, code: 'S-066', name: '자이 용산파크', customerId: 4, customerName: 'GS건설(주)', address: '서울시 용산구 용산동', manager: '파현장', tel: '010-4444-0006', status: '진행중', startDate: '2024-04-01', endDate: '2026-08-31', totalAmount: 1150000000 },
  { id: 67, code: 'S-067', name: '자이 청라호수', customerId: 4, customerName: 'GS건설(주)', address: '인천시 서구 청라동', manager: '하현장', tel: '010-4444-0007', status: '계약', startDate: '2025-08-01', endDate: '2027-12-31', totalAmount: 920000000 },
  { id: 68, code: 'S-068', name: 'GS 창원공장', customerId: 4, customerName: 'GS건설(주)', address: '경남 창원시 성산구', manager: '거현장', tel: '010-4444-0008', status: '진행중', startDate: '2024-08-15', endDate: '2025-12-31', totalAmount: 520000000 },
  { id: 69, code: 'S-069', name: '자이 울산파크', customerId: 4, customerName: 'GS건설(주)', address: '울산시 남구 삼산동', manager: '너현장', tel: '010-4444-0009', status: '계약', startDate: '2025-10-01', endDate: '2028-02-28', totalAmount: 780000000 },
  { id: 70, code: 'S-070', name: '자이 인천루원시티', customerId: 4, customerName: 'GS건설(주)', address: '인천시 서구 가좌동', manager: '더현장', tel: '010-4444-0010', status: '진행중', startDate: '2024-10-01', endDate: '2027-02-28', totalAmount: 980000000 },
  // 포스코건설 추가현장
  { id: 71, code: 'S-071', name: '더샵 광명역', customerId: 5, customerName: '포스코건설(주)', address: '경기도 광명시 일직동', manager: '러현장', tel: '010-5555-0006', status: '진행중', startDate: '2024-05-01', endDate: '2026-09-30', totalAmount: 880000000 },
  { id: 72, code: 'S-072', name: '더샵 부산센텀', customerId: 5, customerName: '포스코건설(주)', address: '부산시 해운대구 우동', manager: '머현장', tel: '010-5555-0007', status: '계약', startDate: '2025-09-01', endDate: '2028-01-31', totalAmount: 1020000000 },
  { id: 73, code: 'S-073', name: '포스코 울산연구소', customerId: 5, customerName: '포스코건설(주)', address: '울산시 남구 매암동', manager: '버현장', tel: '010-5555-0008', status: '진행중', startDate: '2024-07-01', endDate: '2025-11-30', totalAmount: 380000000 },
  { id: 74, code: 'S-074', name: '더샵 서울숲', customerId: 5, customerName: '포스코건설(주)', address: '서울시 성동구 성수동', manager: '서현장', tel: '010-5555-0009', status: '계약', startDate: '2025-11-01', endDate: '2028-03-31', totalAmount: 1250000000 },
  { id: 75, code: 'S-075', name: '더샵 안양역', customerId: 5, customerName: '포스코건설(주)', address: '경기도 안양시 만안구', manager: '어현장', tel: '010-5555-0010', status: '진행중', startDate: '2024-09-01', endDate: '2027-01-31', totalAmount: 720000000 },
  // 롯데건설 추가현장
  { id: 76, code: 'S-076', name: '롯데캐슬 평택역', customerId: 6, customerName: '롯데건설(주)', address: '경기도 평택시 평택동', manager: '저현장', tel: '010-6666-0006', status: '진행중', startDate: '2024-03-01', endDate: '2026-07-31', totalAmount: 680000000 },
  { id: 77, code: 'S-077', name: '롯데캐슬 광주', customerId: 6, customerName: '롯데건설(주)', address: '광주시 서구 치평동', manager: '처현장', tel: '010-6666-0007', status: '계약', startDate: '2025-05-01', endDate: '2027-09-30', totalAmount: 920000000 },
  { id: 78, code: 'S-078', name: '롯데 목포센터', customerId: 6, customerName: '롯데건설(주)', address: '전남 목포시 하당동', manager: '커현장', tel: '010-6666-0008', status: '진행중', startDate: '2024-06-15', endDate: '2025-10-31', totalAmount: 350000000 },
  { id: 79, code: 'S-079', name: '롯데캐슬 원주', customerId: 6, customerName: '롯데건설(주)', address: '강원도 원주시 무실동', manager: '터현장', tel: '010-6666-0009', status: '계약', startDate: '2025-08-01', endDate: '2027-12-31', totalAmount: 580000000 },
  { id: 80, code: 'S-080', name: '롯데캐슬 동탄', customerId: 6, customerName: '롯데건설(주)', address: '경기도 화성시 동탄', manager: '퍼현장', tel: '010-6666-0010', status: '진행중', startDate: '2024-11-01', endDate: '2027-03-31', totalAmount: 1050000000 },
  // 호반건설 추가현장
  { id: 81, code: 'S-081', name: '호반써밋 부천', customerId: 7, customerName: '호반건설(주)', address: '경기도 부천시 원미구', manager: '허현장', tel: '010-7777-0006', status: '진행중', startDate: '2024-05-15', endDate: '2026-09-30', totalAmount: 520000000 },
  { id: 82, code: 'S-082', name: '호반베르디움 수원', customerId: 7, customerName: '호반건설(주)', address: '경기도 수원시 영통구', manager: '고현장', tel: '010-7777-0007', status: '계약', startDate: '2025-06-01', endDate: '2027-10-31', totalAmount: 680000000 },
  { id: 83, code: 'S-083', name: '호반 안성물류', customerId: 7, customerName: '호반건설(주)', address: '경기도 안성시 공도읍', manager: '노현장', tel: '010-7777-0008', status: '진행중', startDate: '2024-08-01', endDate: '2025-12-31', totalAmount: 320000000 },
  { id: 84, code: 'S-084', name: '호반써밋 김포', customerId: 7, customerName: '호반건설(주)', address: '경기도 김포시 장기동', manager: '모현장', tel: '010-7777-0009', status: '계약', startDate: '2025-09-01', endDate: '2028-01-31', totalAmount: 820000000 },
  { id: 85, code: 'S-085', name: '호반베르디움 용인', customerId: 7, customerName: '호반건설(주)', address: '경기도 용인시 기흥구', manager: '보현장', tel: '010-7777-0010', status: '진행중', startDate: '2024-10-15', endDate: '2027-02-28', totalAmount: 650000000 },
  // 한화건설 추가현장
  { id: 86, code: 'S-086', name: '포레나 수원', customerId: 8, customerName: '한화건설(주)', address: '경기도 수원시 장안구', manager: '소현장', tel: '010-8888-0006', status: '진행중', startDate: '2024-04-01', endDate: '2026-08-31', totalAmount: 720000000 },
  { id: 87, code: 'S-087', name: '포레나 전주', customerId: 8, customerName: '한화건설(주)', address: '전북 전주시 덕진구', manager: '오현장', tel: '010-8888-0007', status: '계약', startDate: '2025-07-01', endDate: '2027-11-30', totalAmount: 580000000 },
  { id: 88, code: 'S-088', name: '한화 여수공장', customerId: 8, customerName: '한화건설(주)', address: '전남 여수시 중흥동', manager: '조현장', tel: '010-8888-0008', status: '진행중', startDate: '2024-09-01', endDate: '2026-01-31', totalAmount: 450000000 },
  { id: 89, code: 'S-089', name: '포레나 김해', customerId: 8, customerName: '한화건설(주)', address: '경남 김해시 내동', manager: '우현장', tel: '010-8888-0009', status: '계약', startDate: '2025-10-01', endDate: '2028-02-28', totalAmount: 680000000 },
  { id: 90, code: 'S-090', name: '포레나 인천검단', customerId: 8, customerName: '한화건설(주)', address: '인천시 서구 검단동', manager: '주현장', tel: '010-8888-0010', status: '진행중', startDate: '2024-12-01', endDate: '2027-04-30', totalAmount: 950000000 },
  // 태영건설 추가현장
  { id: 91, code: 'S-091', name: '데시앙 분당', customerId: 9, customerName: '태영건설(주)', address: '경기도 성남시 분당구', manager: '추현장', tel: '010-9999-0006', status: '진행중', startDate: '2024-06-01', endDate: '2026-10-31', totalAmount: 620000000 },
  { id: 92, code: 'S-092', name: '데시앙 안산', customerId: 9, customerName: '태영건설(주)', address: '경기도 안산시 단원구', manager: '국현장', tel: '010-9999-0007', status: '계약', startDate: '2025-08-01', endDate: '2027-12-31', totalAmount: 480000000 },
  { id: 93, code: 'S-093', name: '태영 시흥센터', customerId: 9, customerName: '태영건설(주)', address: '경기도 시흥시 정왕동', manager: '백현장', tel: '010-9999-0008', status: '진행중', startDate: '2024-10-01', endDate: '2026-02-28', totalAmount: 380000000 },
  { id: 94, code: 'S-094', name: '데시앙 대구', customerId: 9, customerName: '태영건설(주)', address: '대구시 달서구 상인동', manager: '남현장', tel: '010-9999-0009', status: '계약', startDate: '2025-11-01', endDate: '2028-03-31', totalAmount: 720000000 },
  { id: 95, code: 'S-095', name: '데시앙 파주', customerId: 9, customerName: '태영건설(주)', address: '경기도 파주시 금촌동', manager: '유현장', tel: '010-9999-0010', status: '진행중', startDate: '2024-07-15', endDate: '2026-11-30', totalAmount: 550000000 },
  // 두산건설 추가현장
  { id: 96, code: 'S-096', name: '위브더비스타', customerId: 10, customerName: '두산건설(주)', address: '서울시 마포구 합정동', manager: '손현장', tel: '010-0000-0006', status: '진행중', startDate: '2024-02-01', endDate: '2026-06-30', totalAmount: 780000000 },
  { id: 97, code: 'S-097', name: '위브프라임', customerId: 10, customerName: '두산건설(주)', address: '경기도 의정부시 녹양동', manager: '양현장', tel: '010-0000-0007', status: '계약', startDate: '2025-04-01', endDate: '2027-08-31', totalAmount: 620000000 },
  { id: 98, code: 'S-098', name: '두산 구미공장', customerId: 10, customerName: '두산건설(주)', address: '경북 구미시 공단동', manager: '홍현장', tel: '010-0000-0008', status: '진행중', startDate: '2024-08-01', endDate: '2025-12-31', totalAmount: 420000000 },
  { id: 99, code: 'S-099', name: '위브엘리트', customerId: 10, customerName: '두산건설(주)', address: '경기도 안양시 동안구', manager: '강현장', tel: '010-0000-0009', status: '계약', startDate: '2025-12-01', endDate: '2028-04-30', totalAmount: 850000000 },
  { id: 100, code: 'S-100', name: '위브더시티', customerId: 10, customerName: '두산건설(주)', address: '경기도 부천시 상동', manager: '신현장', tel: '010-0000-0010', status: '진행중', startDate: '2024-11-01', endDate: '2027-03-31', totalAmount: 920000000 },
];

// 3. 견적 마스터 (100개) - 사전 계산된 견적 데이터
const integratedQuoteMaster = (() => {
  const quotes = [];
  const sizeOptions = [
    { W0: 2000, H0: 2500 }, { W0: 2500, H0: 2800 }, { W0: 3000, H0: 3000 }, { W0: 3500, H0: 3200 }, { W0: 4000, H0: 3500 },
    { W0: 4500, H0: 3000 }, { W0: 5000, H0: 3500 }, { W0: 5500, H0: 4000 }, { W0: 6000, H0: 4000 }, { W0: 6500, H0: 4500 },
    { W0: 7000, H0: 4000 }, { W0: 7500, H0: 4500 }, { W0: 8000, H0: 5000 }, { W0: 2200, H0: 2600 }, { W0: 2800, H0: 2900 },
  ];
  const productTypes = ['스크린', '철재'];
  const voltages = ['220', '380'];
  const wireTypes = ['유선', '무선'];
  const ctTypes = ['매립', '노출'];
  const gtTypes = ['벽면형', '코너형'];

  // ★ 통합 유틸리티 연동 견적 계산 함수 (mesIntegrationUtils.calculateBOM 활용)
  const calculateQuoteWithBOM = (W0, H0, qty, productType, options = {}) => {
    // 통합 BOM 계산 유틸리티 사용
    const bomResult = calculateBOM({
      openWidth: W0,
      openHeight: H0,
      productType: productType === '스크린' ? '스크린' : '철재',
      shaftInch: options.shaftInch || '5',
      installType: options.installType || '벽면형',
      motorPower: options.motorPower || '380',
      wireType: options.wireType || '유선',
      controllerType: options.controllerType || '매립',
      qty,
    });

    // BOM 결과를 견적 형식으로 변환
    const totalAmount = bomResult.summary.totalAmount;
    const unitPrice = Math.round(totalAmount / qty);

    return {
      area: bomResult.variables.M.toFixed(2),
      weight: bomResult.variables.K.toFixed(1),
      motorCapacity: `${bomResult.variables.motorCapacity}KG`,
      shaftInch: `${bomResult.variables.shaftInch}인치`,
      unitPrice,
      totalAmount,
      variables: bomResult.variables, // BOM 계산 변수들 포함
      items: bomResult.items.map(item => ({
        itemCode: item.itemCode,
        itemName: item.itemName,
        spec: item.spec,
        qty: item.qty,
        unit: item.unit,
        unitPrice: item.unitPrice || 0,
        amount: item.qty * (item.unitPrice || 0),
        category: item.category,
      })),
    };
  };

  // 레거시 호환용 간단 계산 함수 (기존 로직 유지)
  const calculateQuote = (W0, H0, qty, productType) => {
    const area = (W0 * H0) / 1000000; // 면적 (㎡)
    const weight = area * 25; // 대략적인 중량
    const basePrice = productType === '스크린' ? 850000 : 750000; // 기본 단가/㎡
    const unitPrice = Math.round(area * basePrice);
    const totalAmount = unitPrice * qty;

    // 모터 용량 결정
    const motorCapacity = weight > 150 ? '500KG' : weight > 100 ? '400KG' : weight > 60 ? '300KG' : '200KG';
    const shaftInch = weight > 100 ? '5인치' : weight > 60 ? '4인치' : '3인치';

    return {
      area: area.toFixed(2),
      weight: weight.toFixed(1),
      motorCapacity,
      shaftInch,
      unitPrice,
      totalAmount,
      items: [
        { itemCode: 'SCR-SCREEN', itemName: '스크린', qty, unit: 'EA', unitPrice: Math.round(area * 350000), amount: Math.round(area * 350000 * qty) },
        { itemCode: 'STL-GUIDE', itemName: '가이드레일', qty: qty * 2, unit: 'EA', unitPrice: Math.round(H0 * 15), amount: Math.round(H0 * 15 * qty * 2) },
        { itemCode: 'STL-CASE', itemName: '케이스', qty, unit: 'EA', unitPrice: Math.round(W0 * 20), amount: Math.round(W0 * 20 * qty) },
        { itemCode: 'MTR-MOTOR', itemName: '튜블러모터', qty, unit: 'EA', unitPrice: 180000, amount: 180000 * qty },
        { itemCode: 'CTL-CTRL', itemName: '제어기', qty, unit: 'EA', unitPrice: 85000, amount: 85000 * qty },
        { itemCode: 'STL-SHAFT', itemName: '샤프트', qty, unit: 'EA', unitPrice: Math.round(W0 * 12), amount: Math.round(W0 * 12 * qty) },
        { itemCode: 'STL-BRACKET', itemName: '브라켓', qty: qty * 2, unit: 'EA', unitPrice: 25000, amount: 25000 * qty * 2 },
        { itemCode: 'INSP-FEE', itemName: '검사비', qty, unit: 'SET', unitPrice: 50000, amount: 50000 * qty },
      ]
    };
  };

  for (let i = 0; i < 100; i++) {
    const siteId = i + 1;
    const site = integratedSiteMaster.find(s => s.id === siteId);
    const customer = integratedCustomerMaster.find(c => c.id === site.customerId);
    const sizeOpt = sizeOptions[i % sizeOptions.length];
    const qty = (i % 5) + 1; // 1~5개
    const productType = productTypes[i % 2];

    // 견적 계산
    const calcResult = calculateQuote(sizeOpt.W0, sizeOpt.H0, qty, productType);
    const discountRate = customer.discountRate || 0;
    const discountAmount = Math.round(calcResult.totalAmount * discountRate / 100);
    const finalAmount = calcResult.totalAmount - discountAmount;

    // 상태 결정 (다양한 상태 분포)
    const statusList = ['견적중', '견적중', '제출완료', '제출완료', '수주전환', '수주전환', '수주전환', '취소', '만료'];
    const status = statusList[i % statusList.length];

    const quoteDate = new Date(2025, 0, 1 + i); // 2025년 1월부터
    // 견적번호 생성 (KD-PR-YYMMDD-## 형식) - 채번관리 규칙 적용
    const qYY = String(quoteDate.getFullYear()).slice(-2);
    const qMM = String(quoteDate.getMonth() + 1).padStart(2, '0');
    const qDD = String(quoteDate.getDate()).padStart(2, '0');
    const qSeq = String((i % 99) + 1).padStart(2, '0');

    quotes.push({
      id: i + 1,
      quoteNo: `KD-PR-${qYY}${qMM}${qDD}-${qSeq}`,
      quoteDate: quoteDate.toISOString().split('T')[0],
      validUntil: new Date(quoteDate.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      status,
      customerId: customer.id,
      customerCode: customer.code,
      customerName: customer.name,
      creditGrade: customer.creditGrade,
      siteId: site.id,
      siteCode: site.code,
      siteName: site.name,
      siteAddress: site.address,
      siteManager: site.manager,
      siteTel: site.tel,
      // 제품 정보
      productType,
      width: sizeOpt.W0,
      height: sizeOpt.H0,
      productionSizeW: sizeOpt.W0 + 140,
      productionSizeH: sizeOpt.H0 + 350,
      area: parseFloat(calcResult.area),
      weight: parseFloat(calcResult.weight),
      motorCapacity: calcResult.motorCapacity,
      shaftInch: calcResult.shaftInch,
      guideType: gtTypes[i % 2],
      voltage: voltages[i % 2],
      wireType: wireTypes[i % 2],
      controllerType: ctTypes[i % 2],
      qty,
      // 금액 정보
      supplyAmount: calcResult.totalAmount,
      discountRate,
      discountAmount,
      finalAmount,
      vatAmount: Math.round(finalAmount * 0.1),
      totalWithVat: Math.round(finalAmount * 1.1),
      // 품목 상세
      items: calcResult.items.map((item, idx) => ({
        ...item,
        lineNo: idx + 1,
        quoteId: i + 1,
      })),
      // 메타 정보
      createdBy: '판매팀',
      createdAt: quoteDate.toISOString(),
      updatedAt: quoteDate.toISOString(),
      note: `${site.name} 방화셔터 견적건`,
    });
  }

  // ========== 절곡 공정 E2E 테스트용 견적 2건 추가 ==========
  // 테스트 1: 강남 타워 절곡 테스트 (수주전환 상태)
  const testQuote1Date = new Date(2025, 11, 15); // 2025-12-15
  quotes.push({
    id: 101,
    quoteNo: 'KD-PR-251215-T1',
    quoteDate: testQuote1Date.toISOString().split('T')[0],
    validUntil: new Date(testQuote1Date.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    status: '수주전환',
    customerId: 1,
    customerCode: 'CUS-001',
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteId: 1,
    siteCode: 'PJ-251215-01',
    siteName: '[E2E테스트1] 강남 타워 절곡현장',
    siteAddress: '서울시 강남구 역삼동 123-45',
    siteManager: '김현장',
    siteTel: '02-1234-5678',
    productType: '절곡',
    width: 3500,
    height: 4000,
    productionSizeW: 3640,
    productionSizeH: 4350,
    area: 14.0,
    weight: 350.0,
    motorCapacity: '500KG',
    shaftInch: '5인치',
    guideType: '벽면형',
    voltage: '380',
    wireType: '유선',
    controllerType: '매립',
    qty: 2,
    supplyAmount: 8500000,
    discountRate: 5,
    discountAmount: 425000,
    finalAmount: 8075000,
    vatAmount: 807500,
    totalWithVat: 8882500,
    items: [
      { lineNo: 1, itemCode: 'FLD-GUIDE', itemName: '가이드레일(절곡)', qty: 4, unit: 'EA', unitPrice: 180000, amount: 720000, quoteId: 101 },
      { lineNo: 2, itemCode: 'FLD-CASE', itemName: '케이스(절곡)', qty: 2, unit: 'EA', unitPrice: 250000, amount: 500000, quoteId: 101 },
      { lineNo: 3, itemCode: 'FLD-SLAT', itemName: '슬랫조립체(절곡)', qty: 2, unit: 'SET', unitPrice: 1500000, amount: 3000000, quoteId: 101 },
      { lineNo: 4, itemCode: 'FLD-BOTTOM', itemName: '바텀바(절곡)', qty: 2, unit: 'EA', unitPrice: 120000, amount: 240000, quoteId: 101 },
      { lineNo: 5, itemCode: 'MTR-MOTOR', itemName: '튜블러모터', qty: 2, unit: 'EA', unitPrice: 280000, amount: 560000, quoteId: 101 },
      { lineNo: 6, itemCode: 'CTL-CTRL', itemName: '제어기', qty: 2, unit: 'EA', unitPrice: 120000, amount: 240000, quoteId: 101 },
      { lineNo: 7, itemCode: 'FLD-BRACKET', itemName: '브라켓(절곡)', qty: 4, unit: 'EA', unitPrice: 45000, amount: 180000, quoteId: 101 },
      { lineNo: 8, itemCode: 'INSP-FEE', itemName: '검사비', qty: 2, unit: 'SET', unitPrice: 80000, amount: 160000, quoteId: 101 },
    ],
    // 절곡 전용 전개도 데이터
    developedParts: [
      { itemCode: 'SD30', itemName: '엘바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3500, qty: 4, weight: 1.05, dimensions: '75', note: '테스트1' },
      { itemCode: 'SD31', itemName: '하장바', material: 'E.G.I 1.6T', totalWidth: 520, length: 3500, qty: 2, weight: 1.35, dimensions: '67→126→165→178→193', note: '' },
      { itemCode: 'SD32', itemName: '바텀커버', material: 'E.G.I 1.0T', totalWidth: 350, length: 3500, qty: 2, weight: 0.42, dimensions: '50→15→215→15→50', note: '' },
      { itemCode: 'SD33', itemName: '가이드레일', material: 'E.G.I 2.0T', totalWidth: 187.5, length: 4000, qty: 4, weight: 1.18, dimensions: '40→80→42.5→25', note: '' },
      { itemCode: 'SD34', itemName: '행거브라켓', material: 'E.G.I 2.3T', totalWidth: 300, length: 350, qty: 4, weight: 0.65, dimensions: '100→50→100→50', note: '' },
      { itemCode: 'SD35', itemName: '케이스상판', material: 'E.G.I 1.0T', totalWidth: 450, length: 3500, qty: 2, weight: 0.58, dimensions: '30→390→30', note: '' },
      { itemCode: 'SD36', itemName: '케이스측판', material: 'E.G.I 1.0T', totalWidth: 450, length: 350, qty: 4, weight: 0.12, dimensions: '30→390→30', note: '' },
      { itemCode: 'SD37', itemName: '케이스전면', material: 'E.G.I 0.8T', totalWidth: 380, length: 3500, qty: 2, weight: 0.41, dimensions: '20→340→20', note: '' },
      { itemCode: 'SD38', itemName: '중간가이드', material: 'E.G.I 1.6T', totalWidth: 200, length: 500, qty: 2, weight: 0.13, dimensions: '50→100→50', note: '' },
    ],
    createdBy: '테스트팀',
    createdAt: testQuote1Date.toISOString(),
    updatedAt: testQuote1Date.toISOString(),
    note: '[E2E테스트1] 강남 타워 절곡 테스트 - 견적→수주→생산지시→작업지시 연동 테스트',
  });

  // 테스트 2: 판교 물류센터 절곡 테스트 (수주전환 상태)
  const testQuote2Date = new Date(2025, 11, 16); // 2025-12-16
  quotes.push({
    id: 102,
    quoteNo: 'KD-PR-251216-T2',
    quoteDate: testQuote2Date.toISOString().split('T')[0],
    validUntil: new Date(testQuote2Date.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    status: '수주전환',
    customerId: 2,
    customerCode: 'CUS-002',
    customerName: '현대건설(주)',
    creditGrade: 'A',
    siteId: 2,
    siteCode: 'PJ-251216-01',
    siteName: '[E2E테스트2] 판교 물류센터 절곡현장',
    siteAddress: '경기도 성남시 분당구 판교동 789-12',
    siteManager: '이현장',
    siteTel: '031-987-6543',
    productType: '절곡',
    width: 4000,
    height: 4500,
    productionSizeW: 4140,
    productionSizeH: 4850,
    area: 18.0,
    weight: 450.0,
    motorCapacity: '500KG',
    shaftInch: '5인치',
    guideType: '코너형',
    voltage: '380',
    wireType: '무선',
    controllerType: '노출',
    qty: 3,
    supplyAmount: 12500000,
    discountRate: 3,
    discountAmount: 375000,
    finalAmount: 12125000,
    vatAmount: 1212500,
    totalWithVat: 13337500,
    items: [
      { lineNo: 1, itemCode: 'FLD-GUIDE', itemName: '가이드레일(절곡)', qty: 6, unit: 'EA', unitPrice: 200000, amount: 1200000, quoteId: 102 },
      { lineNo: 2, itemCode: 'FLD-CASE', itemName: '케이스(절곡)', qty: 3, unit: 'EA', unitPrice: 280000, amount: 840000, quoteId: 102 },
      { lineNo: 3, itemCode: 'FLD-SLAT', itemName: '슬랫조립체(절곡)', qty: 3, unit: 'SET', unitPrice: 1800000, amount: 5400000, quoteId: 102 },
      { lineNo: 4, itemCode: 'FLD-BOTTOM', itemName: '바텀바(절곡)', qty: 3, unit: 'EA', unitPrice: 140000, amount: 420000, quoteId: 102 },
      { lineNo: 5, itemCode: 'MTR-MOTOR', itemName: '튜블러모터', qty: 3, unit: 'EA', unitPrice: 320000, amount: 960000, quoteId: 102 },
      { lineNo: 6, itemCode: 'CTL-CTRL', itemName: '제어기', qty: 3, unit: 'EA', unitPrice: 140000, amount: 420000, quoteId: 102 },
      { lineNo: 7, itemCode: 'FLD-BRACKET', itemName: '브라켓(절곡)', qty: 6, unit: 'EA', unitPrice: 50000, amount: 300000, quoteId: 102 },
      { lineNo: 8, itemCode: 'INSP-FEE', itemName: '검사비', qty: 3, unit: 'SET', unitPrice: 90000, amount: 270000, quoteId: 102 },
    ],
    // 절곡 전용 전개도 데이터
    developedParts: [
      { itemCode: 'SD40', itemName: '엘바', material: 'E.G.I 2.0T', totalWidth: 550, length: 4000, qty: 6, weight: 1.38, dimensions: '85', note: '테스트2' },
      { itemCode: 'SD41', itemName: '하장바', material: 'E.G.I 2.0T', totalWidth: 580, length: 4000, qty: 3, weight: 1.82, dimensions: '72→135→175→188→210', note: '' },
      { itemCode: 'SD42', itemName: '바텀커버', material: 'E.G.I 1.2T', totalWidth: 400, length: 4000, qty: 3, weight: 0.58, dimensions: '55→20→250→20→55', note: '' },
      { itemCode: 'SD43', itemName: '가이드레일', material: 'E.G.I 2.3T', totalWidth: 210, length: 4500, qty: 6, weight: 1.72, dimensions: '45→90→47.5→27.5', note: '' },
      { itemCode: 'SD44', itemName: '행거브라켓', material: 'E.G.I 2.3T', totalWidth: 350, length: 400, qty: 6, weight: 0.92, dimensions: '120→55→120→55', note: '' },
      { itemCode: 'SD45', itemName: '케이스상판', material: 'E.G.I 1.2T', totalWidth: 500, length: 4000, qty: 3, weight: 0.74, dimensions: '35→430→35', note: '' },
      { itemCode: 'SD46', itemName: '케이스측판', material: 'E.G.I 1.2T', totalWidth: 500, length: 400, qty: 6, weight: 0.18, dimensions: '35→430→35', note: '' },
      { itemCode: 'SD47', itemName: '케이스전면', material: 'E.G.I 1.0T', totalWidth: 420, length: 4000, qty: 3, weight: 0.55, dimensions: '25→370→25', note: '' },
      { itemCode: 'SD48', itemName: '중간가이드', material: 'E.G.I 2.0T', totalWidth: 230, length: 550, qty: 3, weight: 0.19, dimensions: '55→120→55', note: '' },
      { itemCode: 'SD49', itemName: '보강재', material: 'E.G.I 1.6T', totalWidth: 180, length: 600, qty: 3, weight: 0.14, dimensions: '40→100→40', note: '' },
    ],
    createdBy: '테스트팀',
    createdAt: testQuote2Date.toISOString(),
    updatedAt: testQuote2Date.toISOString(),
    note: '[E2E테스트2] 판교 물류센터 절곡 테스트 - 견적→수주→생산지시→작업지시 연동 테스트',
  });
  // ========== 절곡 공정 E2E 테스트용 견적 끝 ==========

  return quotes;
})();

// 4. 수주 마스터 - 견적에서 수주전환된 건 (35건)
const integratedOrderMaster = (() => {
  const orders = [];
  const convertedQuotes = integratedQuoteMaster.filter(q => q.status === '수주전환');

  convertedQuotes.forEach((quote, idx) => {
    const orderDate = new Date(quote.quoteDate);
    orderDate.setDate(orderDate.getDate() + 5); // 견적일 + 5일 = 수주일
    const dueDate = new Date(orderDate);
    dueDate.setDate(dueDate.getDate() + 45); // 수주일 + 45일 = 납기일

    // 상태 결정 (E2E 테스트 데이터는 생산중으로 고정)
    // 수주 상태는 생산지시완료까지만 표시 (출하는 출하관리에서 처리)
    const statusList = ['수주확정', '수주확정', '생산지시', '생산중', '생산완료', '생산지시완료'];
    const isTestData = quote.id === 101 || quote.id === 102;
    const status = isTestData ? '생산중' : statusList[idx % statusList.length];

    // 수주번호 생성 (채번관리 규칙 적용)
    // 스크린: KD-TS, 슬랫: KD-SL, 절곡: KD-BD
    const oYY = String(orderDate.getFullYear()).slice(-2);
    const oMM = String(orderDate.getMonth() + 1).padStart(2, '0');
    const oDD = String(orderDate.getDate()).padStart(2, '0');
    const oSeq = String((idx % 99) + 1).padStart(2, '0');
    const orderPrefix = quote.productType === '스크린' ? 'KD-TS' : 'KD-BD'; // 스크린/철재(절곡)

    // 절곡 공정 관련 제품 여부 확인
    const isFoldProduct = ['절곡', '방화셔터', '방연셔터', '방화문', '철재'].includes(quote.productType) ||
      orderPrefix === 'KD-BD';

    // 견적에 developedParts가 있으면 그대로 사용, 없으면 샘플 데이터 생성
    const developedParts = quote.developedParts ? quote.developedParts : (isFoldProduct ? [
      { itemCode: 'SD30', itemName: '엘바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 4, weight: 0.9, dimensions: '75', note: '' },
      { itemCode: 'SD31', itemName: '하장바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 1.158, dimensions: '67→126→165→178→193', note: '' },
      { itemCode: 'SD32', itemName: '짜부가스켓', material: 'E.G.I 0.8T', totalWidth: 500, length: 3000, qty: 4, weight: 0.576, dimensions: '48', note: '80*4,50*8' },
      { itemCode: 'SD33', itemName: '가이드레일', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 2.304, dimensions: '40→80→42.5→25', note: '' },
      { itemCode: 'SD34', itemName: '바텀바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.44, dimensions: '30→95→30', note: '' },
      { itemCode: 'SD35', itemName: '바텀커버', material: 'E.G.I 1.2T', totalWidth: 500, length: 3000, qty: 1, weight: 0.864, dimensions: '65→50→16.5→25', note: '' },
      { itemCode: 'SD36', itemName: '전면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.92, dimensions: '25→210→140→30→50→28', note: '' },
      { itemCode: 'SD37', itemName: '후면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.728, dimensions: '25→165→90→155', note: '' },
      { itemCode: 'SD38', itemName: '측면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 0.96, dimensions: '35→50→35', note: '' },
      { itemCode: 'SD39', itemName: '상부덮개', material: 'E.G.I 1.2T', totalWidth: 500, length: 3000, qty: 1, weight: 0.648, dimensions: '25→140→330→25', note: '' },
    ] : null);

    orders.push({
      id: idx + 1,
      orderNo: `${orderPrefix}-${oYY}${oMM}${oDD}-${oSeq}`,
      orderDate: orderDate.toISOString().split('T')[0],
      status,
      // 견적 연결
      quoteId: quote.id,
      quoteNo: quote.quoteNo,
      // 거래처/현장
      customerId: quote.customerId,
      customerCode: quote.customerCode,
      customerName: quote.customerName,
      creditGrade: quote.creditGrade,
      siteId: quote.siteId,
      siteCode: quote.siteCode,
      siteName: quote.siteName,
      siteAddress: quote.siteAddress,
      siteManager: quote.siteManager,
      siteTel: quote.siteTel,
      // 제품 정보
      productType: quote.productType,
      openSizeW: quote.openSizeW,
      openSizeH: quote.openSizeH,
      productionSizeW: quote.productionSizeW,
      productionSizeH: quote.productionSizeH,
      area: quote.area,
      weight: quote.weight,
      motorCapacity: quote.motorCapacity,
      shaftInch: quote.shaftInch,
      guideType: quote.guideType,
      voltage: quote.voltage,
      wireType: quote.wireType,
      controllerType: quote.controllerType,
      qty: quote.qty,
      // 금액
      orderAmount: quote.finalAmount,
      vatAmount: quote.vatAmount,
      totalAmount: quote.totalWithVat,
      // 납기
      dueDate: dueDate.toISOString().split('T')[0],
      deliveryAddress: quote.siteAddress,
      // 품목
      items: quote.items,
      // 절곡 공정 전개도 데이터 (있는 경우만)
      ...(developedParts && { developedParts }),
      // 메타
      createdBy: '판매팀',
      createdAt: orderDate.toISOString(),
      approvedBy: '판매팀장',
      approvedAt: orderDate.toISOString(),
      note: quote.note,
    });
  });
  return orders;
})();

// 5. 생산지시 마스터 - 수주에서 생산지시 생성 (중간 단계)
// BOM 품목 → 공정 매핑 테이블 (processMasterConfig.sampleProcesses와 동일한 코드 형식 사용)
// SCR-001: 스크린 생산, SLT-001: 슬랫 생산, FLD-001: 절곡 생산, STK-001: 재고 생산(포밍)
const itemProcessMapping = {
  'SCR-SCREEN': { processCode: 'SCR-001', processName: '스크린 생산', workflowCode: 'SCREEN', processSeq: 1 },
  'SLT-SLAT': { processCode: 'SLT-001', processName: '슬랫 생산', workflowCode: 'SLAT', processSeq: 2 },
  'STL-GUIDE': { processCode: 'FLD-001', processName: '절곡 생산', workflowCode: 'FOLD', processSeq: 3 },
  'STL-CASE': { processCode: 'FLD-001', processName: '절곡 생산', workflowCode: 'FOLD', processSeq: 3 },
  'STL-BRACKET': { processCode: 'FLD-001', processName: '절곡 생산', workflowCode: 'FOLD', processSeq: 3 },
  'STL-SHAFT': { processCode: 'STK-001', processName: '재고 생산', workflowCode: 'STOCK', processSeq: 4 },
  'MTR-MOTOR': { processCode: null, processName: '구매품', workflowCode: null, processSeq: 99, isPurchased: true },
  'CTL-CTRL': { processCode: null, processName: '구매품', workflowCode: null, processSeq: 99, isPurchased: true },
  'INSP-FEE': { processCode: 'QC-001', processName: '중간검사', workflowCode: null, processSeq: 5, isService: true },
};

const integratedProductionOrderMaster = (() => {
  const productionOrders = [];
  // 생산중 이상 상태의 수주에서 생산지시 생성
  const eligibleOrders = integratedOrderMaster.filter(o =>
    ['생산중', '생산완료', '출하중', '출하완료', '완료'].includes(o.status)
  );

  eligibleOrders.forEach((order, idx) => {
    const poDate = new Date(order.orderDate);
    poDate.setDate(poDate.getDate() + 2); // 수주일 + 2일 = 생산지시일

    // 상태 결정
    let status = '생산완료';
    if (order.status === '생산중') status = '생산중';
    if (order.status === '수주확정') status = '생산대기';

    // BOM 품목별 공정 분류 (구매품/서비스 제외, workflowCode 포함)
    const bomItems = order.items || [];
    const processGroups = {};

    bomItems.forEach(item => {
      const mapping = itemProcessMapping[item.itemCode];
      // 구매품(isPurchased), 서비스(isService), 검사(중간검사) 제외
      if (mapping && mapping.processCode && !mapping.isPurchased && !mapping.isService) {
        const key = mapping.processCode;
        if (!processGroups[key]) {
          processGroups[key] = {
            processCode: mapping.processCode,
            processName: mapping.processName,
            workflowCode: mapping.workflowCode, // 공정 워크플로우 코드 추가
            processSeq: mapping.processSeq,
            items: []
          };
        }
        processGroups[key].items.push(item);
      }
    });

    // 절곡 공정 여부 확인 (processGroups에 FOLD가 있거나 productType이 절곡 관련인 경우)
    const hasFoldProcess = Object.values(processGroups).some(pg =>
      pg.processName === 'FOLD' || pg.processName === '절곡'
    ) || ['절곡', '방화셔터', '방연셔터', '방화문'].includes(order.productType);

    // 수주에 developedParts가 있으면 그대로 사용, 없으면 샘플 데이터 생성
    const developedParts = order.developedParts ? order.developedParts : (hasFoldProcess ? [
      { itemCode: 'SD30', itemName: '엘바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 4, weight: 0.9, dimensions: '75', note: '' },
      { itemCode: 'SD31', itemName: '하장바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 1.158, dimensions: '67→126→165→178→193', note: '' },
      { itemCode: 'SD32', itemName: '짜부가스켓', material: 'E.G.I 0.8T', totalWidth: 500, length: 3000, qty: 4, weight: 0.576, dimensions: '48', note: '80*4,50*8' },
      { itemCode: 'SD33', itemName: '가이드레일', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 2.304, dimensions: '40→80→42.5→25', note: '' },
      { itemCode: 'SD34', itemName: '바텀바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.44, dimensions: '30→95→30', note: '' },
      { itemCode: 'SD35', itemName: '바텀커버', material: 'E.G.I 1.2T', totalWidth: 500, length: 3000, qty: 1, weight: 0.864, dimensions: '65→50→16.5→25', note: '' },
      { itemCode: 'SD36', itemName: '전면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.92, dimensions: '25→210→140→30→50→28', note: '' },
      { itemCode: 'SD37', itemName: '후면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.728, dimensions: '25→165→90→155', note: '' },
      { itemCode: 'SD38', itemName: '측면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 0.96, dimensions: '35→50→35', note: '' },
      { itemCode: 'SD39', itemName: '상부덮개', material: 'E.G.I 1.2T', totalWidth: 500, length: 3000, qty: 1, weight: 0.648, dimensions: '25→140→330→25', note: '' },
    ] : null);

    productionOrders.push({
      id: idx + 1,
      productionOrderNo: `PO-${order.orderNo.replace('SO-', '')}`,
      productionOrderDate: poDate.toISOString().split('T')[0],
      status,
      // 수주 연결
      orderId: order.id,
      orderNo: order.orderNo,
      quoteNo: order.quoteNo,
      // 거래처/현장
      customerId: order.customerId,
      customerName: order.customerName,
      siteId: order.siteId,
      siteName: order.siteName,
      // 제품 정보
      productType: order.productType,
      qty: order.qty,
      // 납기
      dueDate: order.dueDate,
      // 공정 그룹 (BOM 기반)
      processGroups: Object.values(processGroups).sort((a, b) => a.processSeq - b.processSeq),
      // 진행 현황
      totalProcesses: Object.keys(processGroups).length,
      completedProcesses: status === '생산완료' ? Object.keys(processGroups).length :
        status === '생산중' ? Math.floor(Object.keys(processGroups).length / 2) : 0,
      // 작업지시서 생성 여부
      workOrdersGenerated: true, // 기존 데이터는 이미 생성됨
      // 절곡 공정 전개도 데이터 (있는 경우만)
      ...(developedParts && { developedParts }),
      // 메타
      createdBy: '생산관리',
      createdAt: poDate.toISOString(),
      approvedBy: status !== '생산대기' ? '생산팀장' : null,
      approvedAt: status !== '생산대기' ? poDate.toISOString() : null,
      note: `${order.siteName} 생산지시`,
    });
  });
  return productionOrders;
})();

// 6. 작업지시 마스터 - 생산지시에서 공정별 자동 생성
// ★ 통합 유틸리티(mesIntegrationUtils) 연동: processSteps, processAssignees, initializeStepStatus 활용
const integratedWorkOrderMaster = (() => {
  const workOrders = [];
  const productionOrders = integratedOrderMaster.filter(o =>
    ['생산중', '생산완료', '출하중', '출하완료', '완료'].includes(o.status)
  );

  // ★ 통합 유틸리티의 공정 정의 사용 (processSteps 연동)
  const availableProcesses = Object.keys(processSteps); // ['스크린', '슬랫', '절곡', '재고생산', '전기']
  const processes = ['스크린', '절곡', '슬랫', '조립']; // 실제 사용할 공정

  productionOrders.forEach((order, orderIdx) => {
    processes.forEach((process, procIdx) => {
      const woDate = new Date(order.orderDate);
      woDate.setDate(woDate.getDate() + 3 + procIdx * 2);

      // 상태 결정
      let status = '완료';
      if (order.status === '생산중' && procIdx >= 2) status = '진행중';
      if (order.status === '생산중' && procIdx >= 3) status = '대기';

      // ★ 채번관리 연동: 공정별 문서유형 결정
      // WO-SCR(스크린), WO-SLT(슬랫), WO-FLD(절곡), WO(일반)
      const woDocType = process === '스크린' ? 'WO-SCR'
        : process === '슬랫' ? 'WO-SLT'
          : process === '절곡' ? 'WO-FLD'
            : 'WO';

      // 작업지시(생산LOT) 번호 생성 (KD-PL-YYMMDD-## 형식) - 채번관리 규칙 적용
      const wYY = String(woDate.getFullYear()).slice(-2);
      const wMM = String(woDate.getMonth() + 1).padStart(2, '0');
      const wDD = String(woDate.getDate()).padStart(2, '0');
      const wSeq = String((orderIdx * 4 + procIdx + 1) % 99 || 1).padStart(2, '0');

      // 절곡 공정인 경우 수주에서 developedParts 연동
      const isFoldProcess = process === '절곡';
      const developedParts = isFoldProcess && order.developedParts ? order.developedParts : null;

      // ★ 공정관리 연동: 작업단계 상태 초기화 (initializeStepStatus 활용)
      const steps = processSteps[process] || processSteps['스크린'] || [];
      const stepStatus = {};
      steps.forEach((step, idx) => {
        if (status === '완료') {
          stepStatus[step] = { status: '완료', startTime: woDate.toISOString(), endTime: woDate.toISOString() };
        } else if (status === '진행중' && idx < Math.ceil(steps.length / 2)) {
          stepStatus[step] = { status: '완료', startTime: woDate.toISOString(), endTime: woDate.toISOString() };
        } else if (status === '진행중' && idx === Math.ceil(steps.length / 2)) {
          stepStatus[step] = { status: '진행중', startTime: woDate.toISOString(), endTime: null };
        } else {
          stepStatus[step] = { status: '대기', startTime: null, endTime: null };
        }
      });

      // ★ 공정관리 연동: 담당자 배정 (processAssignees 활용)
      const assigneeInfo = processAssignees[process] || processAssignees['스크린'] || { team: '생산팀', members: ['작업자'] };

      workOrders.push({
        id: orderIdx * 4 + procIdx + 1,
        workOrderNo: `${woDocType}-${wYY}${wMM}${wDD}-${wSeq}`,
        workOrderDate: woDate.toISOString().split('T')[0],
        status,
        processType: process, // 공정 유형 추가
        // 수주 연결
        orderId: order.id,
        orderNo: order.orderNo,
        // 거래처/현장 정보 추가
        customerName: order.customerName,
        siteName: order.siteName,
        // 공정 정보
        processCode: `P-00${procIdx + 1}`,
        processName: process,
        processSeq: procIdx + 1,
        // 제품 정보
        productType: order.productType,
        productionSizeW: order.productionSizeW,
        productionSizeH: order.productionSizeH,
        qty: order.qty,
        totalQty: order.qty,
        completedQty: status === '완료' ? order.qty : (status === '진행중' ? Math.floor(order.qty / 2) : 0),
        defectQty: 0,
        // LOT 정보
        lotNo: `${order.orderNo}-${String(procIdx + 1).padStart(2, '0')}`,
        // 작업 계획
        plannedStartDate: woDate.toISOString().split('T')[0],
        plannedEndDate: new Date(woDate.getTime() + 2 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        plannedQty: order.qty,
        // 작업 실적
        actualStartDate: status !== '대기' ? woDate.toISOString().split('T')[0] : null,
        actualEndDate: status === '완료' ? new Date(woDate.getTime() + 2 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] : null,
        actualQty: status === '완료' ? order.qty : (status === '진행중' ? Math.floor(order.qty / 2) : 0),
        // ★ 공정관리 연동: 작업단계 상태
        stepStatus,
        currentStep: status === '완료' ? steps[steps.length - 1] : (status === '진행중' ? steps[Math.ceil(steps.length / 2)] : steps[0]),
        // ★ 공정관리 연동: 담당자
        assignee: assigneeInfo.team,
        assignees: assigneeInfo.members,
        worker: assigneeInfo.members[0] || `${process}작업자`,
        workCenter: `${process}라인`,
        // 절곡 공정 전개도 데이터 (있는 경우만)
        ...(developedParts && { developedParts }),
        // 메타
        createdBy: '생산관리',
        createdAt: woDate.toISOString(),
        note: `${order.siteName} ${process} 공정`,
      });
    });
  });
  return workOrders;
})();

// 6. 품질검사 데이터 - 작업지시 완료건에 대해
const integratedQualityMaster = (() => {
  const inspections = [];
  const completedWOs = integratedWorkOrderMaster.filter(wo => wo.status === '완료');

  completedWOs.forEach((wo, idx) => {
    const inspDate = new Date(wo.actualEndDate);
    inspDate.setDate(inspDate.getDate() + 1);

    // 결과 (대부분 합격, 일부 불합격)
    const result = idx % 10 === 0 ? '불합격' : '합격';

    // 검사LOT 번호 생성 (채번관리 규칙 적용)
    // 중간검사: KD-WE, 제품검사: KD-SA
    const iYY = String(inspDate.getFullYear()).slice(-2);
    const iMM = String(inspDate.getMonth() + 1).padStart(2, '0');
    const iDD = String(inspDate.getDate()).padStart(2, '0');
    const iSeq = String((idx % 99) + 1).padStart(2, '0');
    const inspPrefix = wo.processSeq === 4 ? 'KD-SA' : 'KD-WE';

    inspections.push({
      id: idx + 1,
      inspectionNo: `${inspPrefix}-${iYY}${iMM}${iDD}-${iSeq}`,
      inspectionDate: inspDate.toISOString().split('T')[0],
      inspectionType: wo.processSeq === 4 ? '제품검사' : '중간검사',
      status: result === '합격' ? '완료' : '재작업',
      result,
      // 작업지시 연결
      workOrderId: wo.id,
      workOrderNo: wo.workOrderNo,
      orderId: wo.orderId,
      orderNo: wo.orderNo,
      // 공정 정보
      processName: wo.processName,
      // 검사 정보
      inspectedQty: wo.actualQty,
      passedQty: result === '합격' ? wo.actualQty : 0,
      failedQty: result === '불합격' ? wo.actualQty : 0,
      // 검사 항목
      checkItems: [
        { item: '외관검사', spec: '흠집/찍힘 없음', result: result === '합격' ? 'OK' : 'NG', note: '' },
        { item: '치수검사', spec: '±5mm', result: 'OK', note: '' },
        { item: '작동검사', spec: '정상 작동', result: 'OK', note: '' },
      ],
      // 메타
      inspector: '품질검사원',
      createdAt: inspDate.toISOString(),
      note: result === '불합격' ? '외관 불량으로 재작업 필요' : '',
    });
  });
  return inspections;
})();

// 7. 출하 데이터 - 생산완료 이상 상태
// ★ 채번관리 연동: SL(출하지시서) 번호 규칙 적용
const integratedShipmentMaster = (() => {
  const shipments = [];
  const shippableOrders = integratedOrderMaster.filter(o =>
    ['출하중', '출하완료', '완료'].includes(o.status)
  );

  shippableOrders.forEach((order, idx) => {
    const shipDate = new Date(order.dueDate);
    shipDate.setDate(shipDate.getDate() - 3);

    const status = order.status === '완료' ? '배송완료' : (order.status === '출하완료' ? '배송중' : '출하대기');

    // ★ 채번관리 연동: 출하번호 생성 (SL-YYMMDD-## 형식)
    const sYY = String(shipDate.getFullYear()).slice(-2);
    const sMM = String(shipDate.getMonth() + 1).padStart(2, '0');
    const sDD = String(shipDate.getDate()).padStart(2, '0');
    const sSeq = String((idx % 99) + 1).padStart(2, '0');

    // 연결된 작업지시 조회
    const relatedWorkOrders = integratedWorkOrderMaster.filter(wo => wo.orderId === order.id);
    const relatedWorkOrderNo = relatedWorkOrders.length > 0 ? relatedWorkOrders[0].workOrderNo : null;

    // 연결된 검사 조회
    const relatedInspections = integratedQualityMaster.filter(insp =>
      relatedWorkOrders.some(wo => wo.id === insp.workOrderId)
    );
    const relatedInspectionNo = relatedInspections.length > 0 ? relatedInspections[0].inspectionNo : null;

    shipments.push({
      id: idx + 1,
      shipmentNo: `SL-${sYY}${sMM}${sDD}-${sSeq}`,
      shipmentDate: shipDate.toISOString().split('T')[0],
      status,
      // 수주 연결
      orderId: order.id,
      orderNo: order.orderNo,
      // ★ 작업지시/검사 연결 (워크플로우 추적용)
      workOrderId: relatedWorkOrders[0]?.id || null,
      workOrderNo: relatedWorkOrderNo,
      inspectionId: relatedInspections[0]?.id || null,
      inspectionNo: relatedInspectionNo,
      // 거래처/현장
      customerId: order.customerId,
      customerName: order.customerName,
      siteId: order.siteId,
      siteName: order.siteName,
      deliveryAddress: order.deliveryAddress,
      siteManager: order.siteManager,
      siteTel: order.siteTel,
      // 제품 정보
      productName: order.productType ? `${order.productType} 셔터` : '방화셔터',
      productSpec: `${order.width || order.productionSizeW}×${order.height || order.productionSizeH}`,
      lotNo: relatedWorkOrders[0]?.lotNo || `${order.orderNo}-01`,
      // 출하 정보
      shipmentQty: order.qty,
      shippedQty: order.qty,
      // 배송 정보
      deliveryType: '자사배송',
      carrier: '자사배송',
      driverName: `배송기사${idx + 1}`,
      driverTel: `010-5000-${String(idx + 1).padStart(4, '0')}`,
      vehicleNo: `12가${1234 + idx}`,
      // 배송 시간
      departureTime: status !== '출하대기' ? `${shipDate.toISOString().split('T')[0]} 08:00` : null,
      arrivalTime: status === '배송완료' ? `${shipDate.toISOString().split('T')[0]} 14:00` : null,
      // 메타
      createdBy: '물류팀',
      createdAt: shipDate.toISOString(),
      confirmedBy: status === '배송완료' ? order.siteManager : null,
      confirmedAt: status === '배송완료' ? `${shipDate.toISOString().split('T')[0]} 14:30` : null,
      note: '',
    });
  });
  return shipments;
})();

// 8. 매출/세금계산서 데이터 - 출하완료건
const integratedSalesMaster = (() => {
  const sales = [];
  const completedShipments = integratedShipmentMaster.filter(s => s.status === '배송완료');

  completedShipments.forEach((shipment, idx) => {
    const order = integratedOrderMaster.find(o => o.id === shipment.orderId);
    const customer = integratedCustomerMaster.find(c => c.id === order.customerId);
    const salesDate = new Date(shipment.shipmentDate);
    salesDate.setDate(salesDate.getDate() + 1);

    sales.push({
      id: idx + 1,
      salesNo: `SL-${order.orderNo.replace('SO-', '')}`,
      salesDate: salesDate.toISOString().split('T')[0],
      salesType: '제품매출',
      status: idx % 3 === 0 ? '수금완료' : '미수금',
      // 수주/출하 연결
      orderId: order.id,
      orderNo: order.orderNo,
      shipmentId: shipment.id,
      shipmentNo: shipment.shipmentNo,
      // 거래처
      customerId: customer.id,
      customerCode: customer.code,
      customerName: customer.name,
      bizNo: customer.bizNo,
      // 금액
      supplyAmount: order.orderAmount,
      vatAmount: order.vatAmount,
      totalAmount: order.totalAmount,
      // 세금계산서
      invoiceNo: `INV-${salesDate.getFullYear()}${String(salesDate.getMonth() + 1).padStart(2, '0')}${String(idx + 1).padStart(4, '0')}`,
      invoiceDate: salesDate.toISOString().split('T')[0],
      invoiceStatus: '발행완료',
      // 수금 정보
      paidAmount: idx % 3 === 0 ? order.totalAmount : 0,
      unpaidAmount: idx % 3 === 0 ? 0 : order.totalAmount,
      dueDate: new Date(salesDate.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      // 메타
      createdBy: '경리팀',
      createdAt: salesDate.toISOString(),
      note: '',
    });
  });
  return sales;
})();

// 9. 수금 데이터 - 수금완료건
const integratedCollectionMaster = (() => {
  const collections = [];
  const paidSales = integratedSalesMaster.filter(s => s.status === '수금완료');

  paidSales.forEach((sale, idx) => {
    const collectDate = new Date(sale.salesDate);
    collectDate.setDate(collectDate.getDate() + 25);

    collections.push({
      id: idx + 1,
      collectionNo: `CL-${sale.salesNo.replace('SL-', '')}`,
      collectionDate: collectDate.toISOString().split('T')[0],
      collectionType: idx % 2 === 0 ? '계좌이체' : '어음',
      status: '완료',
      // 매출 연결
      salesId: sale.id,
      salesNo: sale.salesNo,
      invoiceNo: sale.invoiceNo,
      // 거래처
      customerId: sale.customerId,
      customerName: sale.customerName,
      // 금액
      amount: sale.totalAmount,
      // 입금 정보
      bankName: idx % 2 === 0 ? '우리은행' : '어음',
      accountNo: idx % 2 === 0 ? '1005-XXX-XXXXXX' : null,
      billNo: idx % 2 === 0 ? null : `BILL-${collectDate.getFullYear()}${String(idx + 1).padStart(4, '0')}`,
      billDueDate: idx % 2 === 0 ? null : new Date(collectDate.getTime() + 60 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      // 메타
      createdBy: '경리팀',
      createdAt: collectDate.toISOString(),
      note: '',
    });
  });
  return collections;
})();

// 통합 데이터 요약 정보
const integratedDataSummary = {
  customers: integratedCustomerMaster.length,
  sites: integratedSiteMaster.length,
  quotes: integratedQuoteMaster.length,
  orders: integratedOrderMaster.length,
  workOrders: integratedWorkOrderMaster.length,
  qualityInspections: integratedQualityMaster.length,
  shipments: integratedShipmentMaster.length,
  sales: integratedSalesMaster.length,
  collections: integratedCollectionMaster.length,
  totalQuoteAmount: integratedQuoteMaster.reduce((sum, q) => sum + q.finalAmount, 0),
  totalOrderAmount: integratedOrderMaster.reduce((sum, o) => sum + o.totalAmount, 0),
  totalSalesAmount: integratedSalesMaster.reduce((sum, s) => sum + s.totalAmount, 0),
  totalCollectedAmount: integratedCollectionMaster.reduce((sum, c) => sum + c.amount, 0),
};

// ═══════════════════════════════════════════════════════════════════════════════
// ★ 통합 워크플로우 데이터 생성 (mesIntegrationUtils 완전 연동)
// 견적 → 수주 → 작업지시 → 검사 → 출하 전체 흐름 자동 생성
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * 통합 워크플로우 테스트 데이터 생성
 * - 채번관리 규칙 적용 (documentTemplateConfig)
 * - 견적수식 → BOM 자동계산 (calculateBOM)
 * - 공정관리 연동 (processSteps, processAssignees)
 *
 * @param {number} count - 생성할 워크플로우 수
 * @returns {object} 생성된 통합 테스트 데이터
 */
const generateIntegratedWorkflowData = (count = 10) => {
  const workflows = [];

  // 테스트용 고객/현장 정보
  const testCustomers = [
    { customerName: '삼성물산(주)', siteName: '[통합테스트] 래미안 강남 프레스티지', siteCode: 'S-INT-001' },
    { customerName: '현대건설(주)', siteName: '[통합테스트] 힐스테이트 판교', siteCode: 'S-INT-002' },
    { customerName: '대우건설(주)', siteName: '[통합테스트] 푸르지오 송도', siteCode: 'S-INT-003' },
    { customerName: 'GS건설(주)', siteName: '[통합테스트] 자이 위례', siteCode: 'S-INT-004' },
    { customerName: '포스코건설(주)', siteName: '[통합테스트] 더샵 마린시티', siteCode: 'S-INT-005' },
    { customerName: '롯데건설(주)', siteName: '[통합테스트] 롯데캐슬 동탄', siteCode: 'S-INT-006' },
    { customerName: '호반건설(주)', siteName: '[통합테스트] 써밋 광교', siteCode: 'S-INT-007' },
    { customerName: '한화건설(주)', siteName: '[통합테스트] 포레나 수지', siteCode: 'S-INT-008' },
    { customerName: '태영건설(주)', siteName: '[통합테스트] 데시앙 동탄', siteCode: 'S-INT-009' },
    { customerName: '두산건설(주)', siteName: '[통합테스트] 위브 청라', siteCode: 'S-INT-010' },
  ];

  // 테스트용 제품 규격
  const testSpecs = [
    { openWidth: 3000, openHeight: 3000, productType: '스크린', qty: 2 },
    { openWidth: 3500, openHeight: 3500, productType: '스크린', qty: 3 },
    { openWidth: 4000, openHeight: 4000, productType: '스크린', qty: 1 },
    { openWidth: 4500, openHeight: 3000, productType: '철재', qty: 2 },
    { openWidth: 5000, openHeight: 3500, productType: '철재', qty: 4 },
    { openWidth: 2500, openHeight: 2800, productType: '스크린', qty: 5 },
    { openWidth: 3200, openHeight: 3200, productType: '스크린', qty: 2 },
    { openWidth: 3800, openHeight: 4200, productType: '철재', qty: 3 },
    { openWidth: 6000, openHeight: 4000, productType: '스크린', qty: 1 },
    { openWidth: 5500, openHeight: 3800, productType: '철재', qty: 2 },
  ];

  for (let i = 0; i < count; i++) {
    const customer = testCustomers[i % testCustomers.length];
    const spec = testSpecs[i % testSpecs.length];

    // ★ simulateFullWorkflow 호출 - 전체 워크플로우 자동 생성
    const workflow = simulateFullWorkflow(
      {
        openWidth: spec.openWidth,
        openHeight: spec.openHeight,
        productType: spec.productType,
        shaftInch: spec.openWidth > 4000 ? '6' : '5',
        installType: '벽면형',
        motorPower: '380',
        wireType: i % 2 === 0 ? '유선' : '무선',
        controllerType: i % 2 === 0 ? '매립' : '노출',
        qty: spec.qty,
      },
      {
        customerName: customer.customerName,
        siteName: customer.siteName,
        siteCode: customer.siteCode,
      }
    );

    workflows.push({
      id: i + 1,
      ...workflow,
      // 메타정보 추가
      createdAt: new Date().toISOString(),
      testScenario: `통합테스트 #${i + 1}: ${customer.customerName} - ${spec.productType} ${spec.openWidth}×${spec.openHeight}`,
    });
  }

  // 요약 정보 생성
  const summary = {
    totalWorkflows: workflows.length,
    totalQuotes: workflows.length,
    totalOrders: workflows.length,
    totalWorkOrders: workflows.reduce((sum, w) => sum + (w.workOrders?.length || 0), 0),
    totalInspections: workflows.filter(w => w.inspection).length,
    totalShipments: workflows.filter(w => w.shipment).length,
    totalBomItems: workflows.reduce((sum, w) => sum + (w.bom?.items?.length || 0), 0),
    totalAmount: workflows.reduce((sum, w) => sum + (w.bom?.summary?.totalAmount || 0), 0),
    processDistribution: {
      '스크린': workflows.filter(w => w.workOrders?.some(wo => wo.processType === '스크린')).length,
      '슬랫': workflows.filter(w => w.workOrders?.some(wo => wo.processType === '슬랫')).length,
      '절곡': workflows.filter(w => w.workOrders?.some(wo => wo.processType === '절곡')).length,
    },
  };

  console.log('=== 통합 워크플로우 테스트 데이터 생성 완료 ===');
  console.log('생성된 워크플로우:', summary.totalWorkflows, '건');
  console.log('총 작업지시:', summary.totalWorkOrders, '건');
  console.log('총 BOM 품목:', summary.totalBomItems, '건');
  console.log('총 금액:', new Intl.NumberFormat('ko-KR').format(summary.totalAmount), '원');

  return {
    workflows,
    summary,
  };
};

// 테스트 데이터 생성 (개발용)
// const integratedWorkflowTestData = generateIntegratedWorkflowData(10);

console.log('=== 통합 샘플 데이터 로드 완료 ===');
console.log('거래처:', integratedDataSummary.customers, '개');
console.log('현장:', integratedDataSummary.sites, '개');
console.log('견적:', integratedDataSummary.quotes, '건');
console.log('수주:', integratedDataSummary.orders, '건');
console.log('작업지시:', integratedDataSummary.workOrders, '건');
console.log('품질검사:', integratedDataSummary.qualityInspections, '건');
console.log('출하:', integratedDataSummary.shipments, '건');
console.log('매출:', integratedDataSummary.sales, '건');
console.log('수금:', integratedDataSummary.collections, '건');

// ═══════════════════════════════════════════════════════════════════════════════
// 통합 테스트 대시보드 - 전체 프로세스 데이터 흐름 확인
// ═══════════════════════════════════════════════════════════════════════════════
const IntegratedTestDashboard = () => {
  const [activeTab, setActiveTab] = useState('process-integration');
  const [selectedCustomer, setSelectedCustomer] = useState(null);
  const [selectedQuote, setSelectedQuote] = useState(null);

  // 금액 포맷
  const formatCurrency = (amount) => {
    return new Intl.NumberFormat('ko-KR').format(amount) + '원';
  };

  // 상태별 색상
  const getStatusColor = (status) => {
    const colors = {
      '견적중': 'bg-blue-100 text-blue-800',
      '제출완료': 'bg-purple-100 text-purple-800',
      '수주전환': 'bg-green-100 text-green-800',
      '수주확정': 'bg-green-200 text-green-900',
      '생산중': 'bg-yellow-100 text-yellow-800',
      '생산완료': 'bg-orange-100 text-orange-800',
      '출하중': 'bg-indigo-100 text-indigo-800',
      '출하완료': 'bg-teal-100 text-teal-800',
      '완료': 'bg-gray-200 text-gray-800',
      '합격': 'bg-green-100 text-green-800',
      '불합격': 'bg-red-100 text-red-800',
      '배송완료': 'bg-green-100 text-green-800',
      '배송중': 'bg-blue-100 text-blue-800',
      '수금완료': 'bg-green-100 text-green-800',
      '미수금': 'bg-red-100 text-red-800',
    };
    return colors[status] || 'bg-gray-100 text-gray-800';
  };

  // 탭 정의
  const tabs = [
    { id: 'process-integration', label: '프로세스별 통합 테스트', icon: Layers },
    { id: 'complete-integration', label: '완전 통합 테스트 (10건)', icon: Database },
    { id: 'full-integration', label: '전체 통합 테스트 (5건)', icon: Zap },
    { id: 'workflow', label: '워크플로우 테스트', icon: PlayCircle },
    { id: 'e2e-test', label: 'E2E 50건 테스트', icon: Activity },
    { id: 'summary', label: '요약', icon: BarChart3 },
    { id: 'customers', label: '거래처', icon: Building },
    { id: 'quotes', label: '견적', icon: FileText },
    { id: 'orders', label: '수주', icon: Package },
    { id: 'production', label: '생산', icon: Factory },
    { id: 'quality', label: '품질', icon: ShieldCheck },
    { id: 'shipment', label: '출하', icon: Truck },
    { id: 'accounting', label: '회계', icon: DollarSign },
    { id: 'flow', label: '전체흐름', icon: GitBranch },
  ];

  // ═══════════════════════════════════════════════════════════════════════════
  // 전체 통합 테스트 탭 (5건 실데이터) - 기준정보 연동 검증
  // ═══════════════════════════════════════════════════════════════════════════
  const FullIntegrationTestTab = () => {
    const [testResults, setTestResults] = useState(null);
    const [isRunning, setIsRunning] = useState(false);
    const [selectedTest, setSelectedTest] = useState(null);

    // 테스트 실행
    const handleRunTests = () => {
      setIsRunning(true);
      setSelectedTest(null);

      // 약간의 딜레이 후 테스트 실행 (UI 반응을 위해)
      setTimeout(() => {
        try {
          const results = runAllIntegrationTests();
          setTestResults(results);
        } catch (error) {
          console.error('테스트 실행 오류:', error);
          setTestResults({ error: error.message });
        }
        setIsRunning(false);
      }, 500);
    };

    // 마스터 데이터 요약
    const masterData = getAllMasterData();

    return (
      <div className="space-y-6">
        {/* 헤더 */}
        <div className="bg-gradient-to-r from-red-500 to-orange-500 text-white rounded-xl p-6">
          <h2 className="text-2xl font-bold mb-2">🔥 MES 전체 시스템 통합 테스트</h2>
          <p className="opacity-90">
            기준정보(공정/채번/코드/수식/양식) → 거래처 → 현장 → 품목 → 견적 → 수주 → 생산 → 검사 → 출하 전체 연동 검증
          </p>
        </div>

        {/* 마스터 데이터 현황 */}
        <div className="bg-white rounded-xl p-6 border">
          <h3 className="text-lg font-bold mb-4 flex items-center gap-2">
            <Database className="w-5 h-5 text-blue-500" />
            실데이터 마스터 현황
          </h3>
          <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
            <div className="bg-blue-50 rounded-lg p-4 text-center">
              <p className="text-2xl font-bold text-blue-600">{masterData.customers.length}</p>
              <p className="text-sm text-gray-600">거래처</p>
            </div>
            <div className="bg-green-50 rounded-lg p-4 text-center">
              <p className="text-2xl font-bold text-green-600">{masterData.sites.length}</p>
              <p className="text-sm text-gray-600">현장</p>
            </div>
            <div className="bg-purple-50 rounded-lg p-4 text-center">
              <p className="text-2xl font-bold text-purple-600">{masterData.products.length}</p>
              <p className="text-sm text-gray-600">제품</p>
            </div>
            <div className="bg-orange-50 rounded-lg p-4 text-center">
              <p className="text-2xl font-bold text-orange-600">
                {masterData.parts.purchased.length + masterData.parts.assembly.length + masterData.parts.bending.length}
              </p>
              <p className="text-sm text-gray-600">부품</p>
            </div>
            <div className="bg-yellow-50 rounded-lg p-4 text-center">
              <p className="text-2xl font-bold text-yellow-600">{masterData.rawMaterials.length}</p>
              <p className="text-sm text-gray-600">원자재</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-4 text-center">
              <p className="text-2xl font-bold text-gray-600">{masterData.consumables.length}</p>
              <p className="text-sm text-gray-600">소모품</p>
            </div>
          </div>
        </div>

        {/* 테스트 실행 버튼 */}
        <div className="flex justify-center">
          <button
            onClick={handleRunTests}
            disabled={isRunning}
            className={`px-8 py-4 rounded-xl text-white font-bold text-lg flex items-center gap-3 ${isRunning
                ? 'bg-gray-400 cursor-not-allowed'
                : 'bg-gradient-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600'
              }`}
          >
            {isRunning ? (
              <>
                <RefreshCw className="w-6 h-6 animate-spin" />
                테스트 실행 중...
              </>
            ) : (
              <>
                <Play className="w-6 h-6" />
                5건 전체 통합 테스트 실행
              </>
            )}
          </button>
        </div>

        {/* 테스트 결과 */}
        {testResults && !testResults.error && (
          <div className="space-y-4">
            {/* 결과 요약 */}
            <div className="bg-white rounded-xl p-6 border">
              <h3 className="text-lg font-bold mb-4 flex items-center gap-2">
                <CheckCircle className="w-5 h-5 text-green-500" />
                테스트 결과 요약
              </h3>
              <div className="grid grid-cols-3 gap-4 mb-6">
                <div className="bg-gray-50 rounded-lg p-4 text-center">
                  <p className="text-3xl font-bold">{testResults.summary.totalTests}</p>
                  <p className="text-sm text-gray-600">총 테스트</p>
                </div>
                <div className="bg-green-50 rounded-lg p-4 text-center">
                  <p className="text-3xl font-bold text-green-600">{testResults.summary.successCount}</p>
                  <p className="text-sm text-gray-600">성공</p>
                </div>
                <div className="bg-red-50 rounded-lg p-4 text-center">
                  <p className="text-3xl font-bold text-red-600">{testResults.summary.failCount}</p>
                  <p className="text-sm text-gray-600">실패</p>
                </div>
              </div>

              {/* 개별 테스트 결과 목록 */}
              <div className="space-y-2">
                {testResults.results.map((result, idx) => (
                  <div
                    key={idx}
                    onClick={() => setSelectedTest(selectedTest === idx ? null : idx)}
                    className={`p-4 rounded-lg border cursor-pointer transition-all ${result.success
                        ? 'bg-green-50 border-green-200 hover:bg-green-100'
                        : 'bg-red-50 border-red-200 hover:bg-red-100'
                      } ${selectedTest === idx ? 'ring-2 ring-blue-500' : ''}`}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <span className={`text-lg ${result.success ? 'text-green-500' : 'text-red-500'}`}>
                          {result.success ? '✅' : '❌'}
                        </span>
                        <span className="font-medium">{result.testName}</span>
                      </div>
                      <ChevronDown className={`w-5 h-5 transition-transform ${selectedTest === idx ? 'rotate-180' : ''}`} />
                    </div>

                    {/* 상세 정보 (펼쳐졌을 때) */}
                    {selectedTest === idx && result.summary && (
                      <div className="mt-4 pt-4 border-t border-gray-200">
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                          <div>
                            <p className="text-gray-500">견적번호</p>
                            <p className="font-mono font-medium">{result.summary.quoteNo}</p>
                          </div>
                          <div>
                            <p className="text-gray-500">수주번호</p>
                            <p className="font-mono font-medium">{result.summary.orderNo}</p>
                          </div>
                          <div>
                            <p className="text-gray-500">작업지시</p>
                            <p className="font-mono font-medium">{result.summary.workOrderCount}건</p>
                          </div>
                          <div>
                            <p className="text-gray-500">검사</p>
                            <p className="font-mono font-medium">{result.summary.inspectionCount}건</p>
                          </div>
                          <div>
                            <p className="text-gray-500">출하번호</p>
                            <p className="font-mono font-medium">{result.summary.shipmentNo}</p>
                          </div>
                          <div>
                            <p className="text-gray-500">매출번호</p>
                            <p className="font-mono font-medium">{result.summary.salesNo}</p>
                          </div>
                          <div>
                            <p className="text-gray-500">총 금액</p>
                            <p className="font-medium text-blue-600">
                              {result.summary.totalAmount?.toLocaleString()}원
                            </p>
                          </div>
                          <div>
                            <p className="text-gray-500">잔금</p>
                            <p className="font-medium text-orange-600">
                              {result.summary.remainingAmount?.toLocaleString()}원
                            </p>
                          </div>
                        </div>
                        <div className="mt-4">
                          <p className="text-gray-500 text-sm mb-2">작업지시번호</p>
                          <div className="flex flex-wrap gap-2">
                            {result.summary.workOrderNos?.map((woNo, i) => (
                              <span key={i} className="px-2 py-1 bg-yellow-100 text-yellow-800 rounded text-xs font-mono">
                                {woNo}
                              </span>
                            ))}
                          </div>
                        </div>
                        <div className="mt-4 p-3 bg-gray-100 rounded">
                          <p className="text-xs text-gray-500">프로세스 흐름</p>
                          <p className="text-sm font-medium">{result.summary.processFlow}</p>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>

            {/* 연동 검증 체크리스트 */}
            <div className="bg-white rounded-xl p-6 border">
              <h3 className="text-lg font-bold mb-4 flex items-center gap-2">
                <ClipboardList className="w-5 h-5 text-purple-500" />
                기준정보 연동 검증 체크리스트
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {[
                  { name: '채번관리', desc: 'QT/SO/WO/IQC/PQC/FQC/SL 문서번호 자동생성', status: 'pass' },
                  { name: '공통코드', desc: '품목코드/거래처코드/현장코드 규칙 적용', status: 'pass' },
                  { name: '공정관리', desc: '스크린/슬랫/절곡 공정별 작업단계 연동', status: 'pass' },
                  { name: '견적수식', desc: 'BOM 자동계산 (제작사이즈/면적/중량)', status: 'pass' },
                  { name: '문서양식', desc: '견적서/수주서/작업지시서/검사성적서', status: 'pass' },
                  { name: '단가관리', desc: '품목별 단가 조회 및 적용', status: 'pass' },
                  { name: '재고연동', desc: '자재 소요량 산출 및 출고 처리', status: 'pass' },
                  { name: '품질연동', desc: '중간검사/최종검사 결과 연동', status: 'pass' },
                  { name: '회계연동', desc: '입금/매출/수금 데이터 연동', status: 'pass' },
                  { name: '추적성', desc: '견적→출하 전 과정 문서번호 연결', status: 'pass' },
                ].map((item, idx) => (
                  <div key={idx} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                    <span className="text-green-500 text-xl">✅</span>
                    <div>
                      <p className="font-medium">{item.name}</p>
                      <p className="text-sm text-gray-500">{item.desc}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* 에러 표시 */}
        {testResults?.error && (
          <div className="bg-red-50 border border-red-200 rounded-xl p-6">
            <h3 className="text-lg font-bold text-red-600 mb-2">테스트 실행 오류</h3>
            <p className="text-red-700">{testResults.error}</p>
          </div>
        )}
      </div>
    );
  };

  // ═══════════════════════════════════════════════════════════════════════════
  // 워크플로우 테스트 탭 - 견적 입력부터 회계까지 전 과정 실시간 테스트
  // ═══════════════════════════════════════════════════════════════════════════
  const WorkflowTestTab = () => {
    // 워크플로우 상태
    const [currentStep, setCurrentStep] = useState(0);
    const [isProcessing, setIsProcessing] = useState(false);
    const [workflowData, setWorkflowData] = useState({
      // 입력 정보
      inputs: {
        customerId: integratedCustomerMaster[0]?.id,
        siteId: integratedSiteMaster[0]?.id,
        PC: '스크린',
        W0: 2500,
        H0: 3000,
        QTY: 2,
        GT: '벽면형',
        V: '220',
        WIRE: '유선',
        CT: '매립',
        floor: '1층',
        symbol: 'A',
      },
      // 계산 결과
      calculatedResult: null,
      // 생성된 데이터
      quote: null,
      order: null,
      workOrders: [],
      qualityInspections: [],
      shipment: null,
      sales: null,
      collection: null,
    });

    // 단계 정의
    const steps = [
      { id: 0, label: '견적 입력', icon: Calculator, color: 'blue' },
      { id: 1, label: '자동 산출', icon: Zap, color: 'purple' },
      { id: 2, label: '견적 확정', icon: FileText, color: 'green' },
      { id: 3, label: '수주 전환', icon: Package, color: 'orange' },
      { id: 4, label: '생산 지시', icon: Factory, color: 'yellow' },
      { id: 5, label: '품질 검사', icon: ShieldCheck, color: 'indigo' },
      { id: 6, label: '출하', icon: Truck, color: 'teal' },
      { id: 7, label: '회계 처리', icon: DollarSign, color: 'pink' },
      { id: 8, label: '완료', icon: CheckCircle, color: 'emerald' },
    ];

    // 선택된 거래처의 현장 목록
    const customerSites = integratedSiteMaster.filter(s => s.customerId === workflowData.inputs.customerId);
    const selectedCustomer = integratedCustomerMaster.find(c => c.id === workflowData.inputs.customerId);
    const selectedSite = integratedSiteMaster.find(s => s.id === workflowData.inputs.siteId);

    // 입력값 변경
    const handleInputChange = (key, value) => {
      setWorkflowData(prev => ({
        ...prev,
        inputs: { ...prev.inputs, [key]: value }
      }));
      // 거래처 변경시 현장 초기화
      if (key === 'customerId') {
        const sites = integratedSiteMaster.filter(s => s.customerId === parseInt(value));
        if (sites.length > 0) {
          setWorkflowData(prev => ({
            ...prev,
            inputs: { ...prev.inputs, customerId: parseInt(value), siteId: sites[0].id }
          }));
        }
      }
    };

    // 견적 자동 산출
    const calculateQuote = () => {
      const { PC, W0, H0, QTY, GT, V, WIRE, CT } = workflowData.inputs;

      // 제작사이즈 계산
      const W1 = PC === '스크린' ? W0 + 140 : W0 + 110;
      const H1 = H0 + 350;

      // 면적 및 중량 계산
      const M = (W1 * H1) / 1000000;
      const K = PC === '스크린' ? (M * 2) + (W0 * 14.17 / 1000) : M * 25;

      // 모터 용량 결정
      let motorCapacity = '200KG';
      if (K > 150) motorCapacity = '500KG';
      else if (K > 100) motorCapacity = '400KG';
      else if (K > 60) motorCapacity = '300KG';

      // 샤프트 인치 결정
      let shaftInch = '3인치';
      if (W1 > 5000) shaftInch = '5인치';
      else if (W1 > 3500) shaftInch = '4인치';

      // 품목별 산출
      const items = [
        { id: 1, itemCode: 'SCR-001', itemName: '스크린', spec: `${W1}x${H1}`, qty: QTY, unit: 'EA', unitPrice: Math.round(M * 350000), amount: Math.round(M * 350000 * QTY), process: '스크린', category: '스크린' },
        { id: 2, itemCode: 'GR-001', itemName: '가이드레일', spec: `${H0 + 250}mm`, qty: QTY * 2, unit: 'EA', unitPrice: Math.round((H0 + 250) * 85), amount: Math.round((H0 + 250) * 85 * QTY * 2), process: '절곡', category: '철재' },
        { id: 3, itemCode: 'CS-001', itemName: '케이스', spec: `${W1}mm`, qty: QTY, unit: 'SET', unitPrice: Math.round(W1 * 120), amount: Math.round(W1 * 120 * QTY), process: '절곡', category: '철재' },
        { id: 4, itemCode: `MTR-${motorCapacity}`, itemName: `튜블러모터 ${motorCapacity}`, spec: motorCapacity, qty: QTY, unit: 'EA', unitPrice: motorCapacity === '500KG' ? 450000 : motorCapacity === '400KG' ? 380000 : motorCapacity === '300KG' ? 320000 : 280000, amount: 0, process: '조립', category: '모터' },
        { id: 5, itemCode: `SFT-${shaftInch}`, itemName: `샤프트 ${shaftInch}`, spec: `${shaftInch} x ${W1}mm`, qty: QTY, unit: 'EA', unitPrice: shaftInch === '5인치' ? 180000 : shaftInch === '4인치' ? 150000 : 120000, amount: 0, process: '샤프트', category: '샤프트' },
        { id: 6, itemCode: 'BRK-001', itemName: '브라켓', spec: motorCapacity, qty: QTY * 2, unit: 'EA', unitPrice: 25000, amount: 25000 * QTY * 2, process: '조립', category: '부자재' },
        { id: 7, itemCode: 'CTR-001', itemName: `연동제어기 ${CT}`, spec: CT === '매립' ? '매립형' : '노출형', qty: QTY, unit: 'EA', unitPrice: CT === '매립' ? 85000 : 65000, amount: 0, process: '전장', category: '제어' },
        { id: 8, itemCode: 'BTM-001', itemName: '하단마감재', spec: `${W0}mm`, qty: QTY, unit: 'SET', unitPrice: Math.round(W0 * 45), amount: Math.round(W0 * 45 * QTY), process: '절곡', category: '철재' },
      ];

      // 금액 계산 (아직 계산되지 않은 항목)
      items.forEach(item => {
        if (item.amount === 0) {
          item.amount = item.unitPrice * item.qty;
        }
      });

      const totalAmount = items.reduce((sum, item) => sum + item.amount, 0);

      return {
        summary: {
          productType: PC,
          openSize: `${W0} x ${H0}`,
          productionSize: `${W1} x ${H1}`,
          area: M.toFixed(2),
          weight: K.toFixed(1),
          motorCapacity,
          shaftInch,
          qty: QTY,
        },
        items,
        totalAmount,
        vatAmount: Math.round(totalAmount * 0.1),
        grandTotal: Math.round(totalAmount * 1.1),
      };
    };

    // 다음 단계 실행
    const executeNextStep = async () => {
      setIsProcessing(true);

      // 각 단계별 처리
      await new Promise(resolve => setTimeout(resolve, 800)); // 애니메이션 효과

      switch (currentStep) {
        case 0: // 견적 입력 → 자동 산출
          const result = calculateQuote();
          setWorkflowData(prev => ({ ...prev, calculatedResult: result }));
          break;

        case 1: // 자동 산출 → 견적 확정
          const quoteNo = `QT-${Date.now().toString().slice(-8)}`;
          const newQuote = {
            id: Date.now(),
            quoteNo,
            quoteDate: new Date().toISOString().slice(0, 10),
            customerId: workflowData.inputs.customerId,
            customerName: selectedCustomer?.name,
            siteId: workflowData.inputs.siteId,
            siteName: selectedSite?.name,
            productType: workflowData.calculatedResult.summary.productType,
            width: workflowData.inputs.W0,
            height: workflowData.inputs.H0,
            qty: workflowData.inputs.QTY,
            items: workflowData.calculatedResult.items,
            totalAmount: workflowData.calculatedResult.totalAmount,
            vatAmount: workflowData.calculatedResult.vatAmount,
            finalAmount: workflowData.calculatedResult.grandTotal,
            status: '최종확정',
            discountRate: selectedCustomer?.discountRate || 0,
          };
          setWorkflowData(prev => ({ ...prev, quote: newQuote }));
          break;

        case 2: // 견적 확정 → 수주 전환
          const orderNo = `SO-${Date.now().toString().slice(-8)}`;
          const newOrder = {
            id: Date.now(),
            orderNo,
            orderDate: new Date().toISOString().slice(0, 10),
            quoteId: workflowData.quote.id,
            quoteNo: workflowData.quote.quoteNo,
            customerId: workflowData.quote.customerId,
            customerName: workflowData.quote.customerName,
            siteId: workflowData.quote.siteId,
            siteName: workflowData.quote.siteName,
            items: workflowData.quote.items,
            totalAmount: workflowData.quote.finalAmount,
            dueDate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
            status: '수주확정',
          };
          setWorkflowData(prev => ({
            ...prev,
            order: newOrder,
            quote: { ...prev.quote, status: '수주전환', convertedOrderNo: orderNo }
          }));
          break;

        case 3: // 수주 전환 → 생산 지시
          const processes = ['스크린', '절곡', '샤프트', '조립', '전장'];
          const newWorkOrders = processes.map((process, idx) => ({
            id: Date.now() + idx,
            workOrderNo: `WO-${Date.now().toString().slice(-6)}-${idx + 1}`,
            orderId: workflowData.order.id,
            orderNo: workflowData.order.orderNo,
            processName: process,
            qty: workflowData.inputs.QTY,
            producedQty: 0,
            defectQty: 0,
            status: '대기',
            startDate: null,
            endDate: null,
          }));
          setWorkflowData(prev => ({
            ...prev,
            workOrders: newWorkOrders,
            order: { ...prev.order, status: '생산중' }
          }));
          break;

        case 4: // 생산 지시 → 품질 검사 (생산 완료 처리 포함)
          // 생산 완료 처리
          const completedWorkOrders = workflowData.workOrders.map(wo => ({
            ...wo,
            producedQty: wo.qty,
            status: '완료',
            startDate: new Date().toISOString().slice(0, 10),
            endDate: new Date().toISOString().slice(0, 10),
          }));

          // 품질 검사 생성
          const inspections = completedWorkOrders.map((wo, idx) => ({
            id: Date.now() + idx,
            inspectionNo: `QI-${Date.now().toString().slice(-6)}-${idx + 1}`,
            workOrderId: wo.id,
            workOrderNo: wo.workOrderNo,
            inspectionType: wo.processName === '조립' ? '제품검사' : '중간검사',
            inspectionItems: ['외관검사', '치수검사', '작동검사'],
            inspectionDate: new Date().toISOString().slice(0, 10),
            result: '합격',
            inspector: '검사원A',
          }));

          setWorkflowData(prev => ({
            ...prev,
            workOrders: completedWorkOrders,
            qualityInspections: inspections,
            order: { ...prev.order, status: '생산완료' }
          }));
          break;

        case 5: // 품질 검사 → 출하
          const shipmentNo = `SH-${Date.now().toString().slice(-8)}`;
          const newShipment = {
            id: Date.now(),
            shipmentNo,
            orderId: workflowData.order.id,
            orderNo: workflowData.order.orderNo,
            customerId: workflowData.order.customerId,
            customerName: workflowData.order.customerName,
            siteId: workflowData.order.siteId,
            siteName: workflowData.order.siteName,
            shipmentDate: new Date().toISOString().slice(0, 10),
            carrier: '자체배송',
            status: '배송완료',
            deliveryDate: new Date().toISOString().slice(0, 10),
          };
          setWorkflowData(prev => ({
            ...prev,
            shipment: newShipment,
            order: { ...prev.order, status: '출하완료' }
          }));
          break;

        case 6: // 출하 → 회계 처리
          const salesNo = `SL-${Date.now().toString().slice(-8)}`;
          const supplyAmount = workflowData.order.totalAmount / 1.1;
          const newSales = {
            id: Date.now(),
            salesNo,
            orderId: workflowData.order.id,
            orderNo: workflowData.order.orderNo,
            customerId: workflowData.order.customerId,
            customerName: workflowData.order.customerName,
            supplyAmount: Math.round(supplyAmount),
            vatAmount: Math.round(supplyAmount * 0.1),
            totalAmount: workflowData.order.totalAmount,
            salesDate: new Date().toISOString().slice(0, 10),
            paymentStatus: '미수금',
          };

          // 수금 처리 (A등급 거래처는 자동 수금 처리)
          let newCollection = null;
          if (selectedCustomer?.creditGrade === 'A') {
            const collectionNo = `CL-${Date.now().toString().slice(-8)}`;
            newCollection = {
              id: Date.now() + 1,
              collectionNo,
              salesId: newSales.id,
              salesNo: newSales.salesNo,
              customerId: workflowData.order.customerId,
              customerName: workflowData.order.customerName,
              amount: newSales.totalAmount,
              collectionDate: new Date().toISOString().slice(0, 10),
              paymentMethod: '계좌이체',
            };
            newSales.paymentStatus = '수금완료';
          }

          setWorkflowData(prev => ({
            ...prev,
            sales: newSales,
            collection: newCollection,
            order: { ...prev.order, status: '완료' }
          }));
          break;

        default:
          break;
      }

      setCurrentStep(prev => Math.min(prev + 1, 8));
      setIsProcessing(false);
    };

    // 초기화
    const resetWorkflow = () => {
      setCurrentStep(0);
      setWorkflowData({
        inputs: {
          customerId: integratedCustomerMaster[0]?.id,
          siteId: integratedSiteMaster[0]?.id,
          PC: '스크린',
          W0: 2500,
          H0: 3000,
          QTY: 2,
          GT: '벽면형',
          V: '220',
          WIRE: '유선',
          CT: '매립',
          floor: '1층',
          symbol: 'A',
        },
        calculatedResult: null,
        quote: null,
        order: null,
        workOrders: [],
        qualityInspections: [],
        shipment: null,
        sales: null,
        collection: null,
      });
    };

    // 자동 실행 (전체 프로세스)
    const [isAutoRunning, setIsAutoRunning] = useState(false);
    const [selectedScenario, setSelectedScenario] = useState('normal');
    const [testResults, setTestResults] = useState([]);

    // 테스트 시나리오 정의
    const testScenarios = [
      // ═══════════════════════════════════════════════════════════════════════════
      // MVP 핵심 시나리오 (수주→작업지시→자재투입→작업실적→검사→출하)
      // ═══════════════════════════════════════════════════════════════════════════
      { id: 'mvp-core', label: 'MVP 핵심흐름', desc: '수주→작업지시→자재투입→실적→검사→출하', icon: '🎯' },
      { id: 'mvp-material-input', label: 'MVP 자재투입', desc: '작업지시 자재투입 테스트', icon: '🔧' },
      { id: 'mvp-work-result', label: 'MVP 작업실적', desc: '공정별 작업실적 입력 테스트', icon: '📝' },
      { id: 'mvp-worker-screen', label: 'MVP 작업자화면', desc: '작업자 현장 입력 화면 테스트', icon: '👷' },
      { id: 'mvp-production-board', label: 'MVP 생산현황판', desc: '실시간 생산현황 모니터링', icon: '📺' },
      { id: 'mvp-stock-status', label: 'MVP 재고현황', desc: '재고현황 조회 테스트', icon: '📦' },
      { id: 'mvp-inbound', label: 'MVP 입고관리', desc: '자재입고 처리 테스트', icon: '📥' },
      { id: 'mvp-full-flow', label: 'MVP 전체흐름', desc: 'MVP 전 과정 통합 테스트', icon: '🔄' },
      // ═══════════════════════════════════════════════════════════════════════════
      // 기존 시나리오
      // ═══════════════════════════════════════════════════════════════════════════
      { id: 'normal', label: '정상 프로세스', desc: '모든 단계 정상 완료', icon: '✅' },
      { id: 'quote-cancel', label: '견적 취소', desc: '견적 단계에서 취소', icon: '❌' },
      { id: 'quote-expire', label: '견적 만료', desc: '유효기간 초과로 만료', icon: '⏰' },
      { id: 'quality-fail', label: '품질 불합격', desc: '품질검사 불합격 → 재작업', icon: '🔴' },
      { id: 'quality-conditional', label: '조건부 합격', desc: '품질검사 조건부 합격', icon: '🟡' },
      { id: 'partial-shipment', label: '부분 출하', desc: '일부 수량만 출하', icon: '📦' },
      { id: 'payment-delay', label: '수금 지연', desc: '미수금 발생 (B/C등급)', icon: '💰' },
      { id: 'rush-order', label: '긴급 주문', desc: '납기 단축 긴급 처리', icon: '🚨' },
      { id: 'size-change', label: '사이즈 변경', desc: '생산 중 사이즈 변경', icon: '📐' },
      { id: 'new-item', label: '신규 품목', desc: '품목등록 → 견적 테스트', icon: '📋' },
      { id: 'multi-inspection', label: '검사유형전환', desc: '입고/중간/제품검사 통합', icon: '🔍' },
      { id: 'numbering-test', label: '채번 테스트', desc: '자동채번 규칙 검증', icon: '🔢' },
      { id: 'code-reference', label: '코드참조', desc: '공통코드 활용 테스트', icon: '📑' },
      { id: 'accounting-sales', label: '매출관리', desc: '매출 등록/수정/조회 테스트', icon: '📊' },
      { id: 'accounting-purchase', label: '매입관리', desc: '매입 등록/수정/조회 테스트', icon: '🛒' },
      { id: 'accounting-cashbook', label: '금전출납부', desc: '입출금 내역 관리 테스트', icon: '💵' },
      { id: 'accounting-collection', label: '수금관리', desc: '미수금/수금 처리 테스트', icon: '💳' },
      { id: 'accounting-cost', label: '원가관리', desc: '원가계산/분석 테스트', icon: '🧮' },
      // 문서 출력 테스트 시나리오
      { id: 'doc-quote', label: '견적서 출력', desc: '견적서 생성/출력 테스트', icon: '📄' },
      { id: 'doc-order-confirm', label: '수주확인서', desc: '수주확인서 생성/출력', icon: '📋' },
      { id: 'doc-work-order', label: '작업지시서', desc: '작업지시서 생성/출력', icon: '📝' },
      { id: 'doc-inspection', label: '검사성적서', desc: '검사성적서 생성/출력', icon: '🔬' },
      { id: 'doc-shipment', label: '출하지시서', desc: '출하지시서 생성/출력', icon: '🚚' },
      { id: 'doc-invoice', label: '거래명세서', desc: '거래명세서 생성/출력', icon: '🧾' },
      { id: 'doc-tax', label: '세금계산서', desc: '세금계산서 발행 테스트', icon: '💹' },
      { id: 'doc-full-flow', label: '문서 전체흐름', desc: '전 과정 문서출력 통합', icon: '📚' },
      // ═══════════════════════════════════════════════════════════════════════════
      // E2E 통합 테스트 시나리오 (견적산출 → 수주 → 생산지시 → 공정분리 → 출하)
      // ═══════════════════════════════════════════════════════════════════════════
      { id: 'e2e-quote-calc', label: 'E2E 견적산출', desc: '새 수식 기준 자동견적 산출', icon: '🧮', isE2E: true },
      { id: 'e2e-order-convert', label: 'E2E 수주전환', desc: '견적→수주 전환 테스트', icon: '📦', isE2E: true },
      { id: 'e2e-order-confirm', label: 'E2E 수주확정', desc: '입금/승인 후 수주 확정', icon: '✅', isE2E: true },
      { id: 'e2e-production-order', label: 'E2E 생산지시', desc: '수주→생산지시 발행', icon: '🏭', isE2E: true },
      { id: 'e2e-process-split', label: 'E2E 공정분리', desc: '스크린/슬랫/절곡 공정 분리', icon: '🔀', isE2E: true },
      { id: 'e2e-work-order', label: 'E2E 작업지시', desc: '공정별 작업지시서 생성', icon: '📋', isE2E: true },
      { id: 'e2e-work-result', label: 'E2E 작업실적', desc: '공정별 작업 완료 처리', icon: '✔️', isE2E: true },
      { id: 'e2e-inspection', label: 'E2E 품질검사', desc: '완제품 품질검사 통과', icon: '🔍', isE2E: true },
      { id: 'e2e-shipment', label: 'E2E 출하완료', desc: '출하 처리 및 문서발행', icon: '🚚', isE2E: true },
      { id: 'e2e-full-flow', label: 'E2E 전체흐름', desc: '견적→출하 전과정 통합', icon: '🎯', isE2E: true },
      { id: 'full-cycle', label: '전체 사이클', desc: '모든 경우의 수 테스트', icon: '🔄' },
    ];

    // 전체 테스트 결과 상세
    const [allTestResults, setAllTestResults] = useState({});
    const [testSummary, setTestSummary] = useState(null);

    // 시나리오별 자동 실행
    const runAutoWorkflow = async () => {
      setIsAutoRunning(true);
      resetWorkflow();
      setTestResults([]);
      setAllTestResults({});
      setTestSummary(null);
      await new Promise(resolve => setTimeout(resolve, 300));

      const results = [];
      const scenario = selectedScenario;

      // 시나리오별 처리
      if (scenario === 'full-cycle') {
        // 전체 사이클: 모든 시나리오 순차 실행
        const startTime = Date.now();
        const detailedResults = {};
        let passCount = 0;
        let failCount = 0;

        for (const sc of testScenarios.filter(s => s.id !== 'full-cycle')) {
          const scenarioStartTime = Date.now();
          results.push({
            scenario: sc.label,
            scenarioId: sc.id,
            status: '실행중',
            icon: sc.icon,
            startTime: new Date().toLocaleTimeString(),
          });
          setTestResults([...results]);

          try {
            await runSingleScenario(sc.id);
            const duration = ((Date.now() - scenarioStartTime) / 1000).toFixed(1);
            results[results.length - 1].status = '✅ 통과';
            results[results.length - 1].duration = `${duration}s`;
            results[results.length - 1].passed = true;
            detailedResults[sc.id] = { passed: true, duration, label: sc.label };
            passCount++;
          } catch (error) {
            const duration = ((Date.now() - scenarioStartTime) / 1000).toFixed(1);
            results[results.length - 1].status = '❌ 실패';
            results[results.length - 1].duration = `${duration}s`;
            results[results.length - 1].passed = false;
            results[results.length - 1].error = error.message;
            detailedResults[sc.id] = { passed: false, duration, label: sc.label, error: error.message };
            failCount++;
          }

          setTestResults([...results]);
          await new Promise(resolve => setTimeout(resolve, 300));
          resetWorkflow();
        }

        const totalDuration = ((Date.now() - startTime) / 1000).toFixed(1);
        setAllTestResults(detailedResults);
        setTestSummary({
          totalScenarios: testScenarios.length - 1,
          passed: passCount,
          failed: failCount,
          passRate: ((passCount / (testScenarios.length - 1)) * 100).toFixed(1),
          totalDuration: `${totalDuration}s`,
          completedAt: new Date().toLocaleString(),
        });
        setIsAutoRunning(false);
        return;
      }

      await runSingleScenario(scenario);
      setIsAutoRunning(false);
    };

    // 단일 시나리오 실행
    const runSingleScenario = async (scenario) => {
      // 번호 시퀀스 카운터 (실제 운영에서는 DB에서 관리)
      const seqCounters = {
        quote: Math.floor(Math.random() * 50) + 1,
        order: Math.floor(Math.random() * 50) + 1,
        production: Math.floor(Math.random() * 20) + 1,
        inspection: Math.floor(Math.random() * 20) + 1,
      };
      const today = new Date();

      // Step 0: 견적 입력 → 자동 산출
      await new Promise(resolve => setTimeout(resolve, 400));
      const calcResult = calculateQuote();
      setWorkflowData(prev => ({ ...prev, calculatedResult: calcResult }));
      setCurrentStep(1);

      // 견적 취소 시나리오
      if (scenario === 'quote-cancel') {
        await new Promise(resolve => setTimeout(resolve, 400));
        const quoteNo = generateQuoteNo(today, seqCounters.quote);
        setWorkflowData(prev => ({
          ...prev,
          quote: {
            id: Date.now(),
            quoteNo,
            quoteDate: today.toISOString().slice(0, 10),
            customerName: selectedCustomer?.name,
            siteName: selectedSite?.name,
            status: '취소',
            cancelReason: '고객 요청으로 취소',
            cancelDate: today.toISOString().slice(0, 10),
          }
        }));
        setCurrentStep(8);
        return;
      }

      // 견적 만료 시나리오
      if (scenario === 'quote-expire') {
        await new Promise(resolve => setTimeout(resolve, 400));
        const expireDate = new Date();
        expireDate.setDate(expireDate.getDate() - 31);
        const quoteNo = generateQuoteNo(expireDate, seqCounters.quote);
        setWorkflowData(prev => ({
          ...prev,
          quote: {
            id: Date.now(),
            quoteNo,
            quoteDate: expireDate.toISOString().slice(0, 10),
            validUntil: new Date(expireDate.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
            customerName: selectedCustomer?.name,
            siteName: selectedSite?.name,
            status: '만료',
            expireReason: '유효기간 30일 초과',
          }
        }));
        setCurrentStep(8);
        return;
      }

      // Step 1: 자동 산출 → 견적 확정
      await new Promise(resolve => setTimeout(resolve, 400));
      setWorkflowData(prev => {
        const quoteNo = generateQuoteNo(today, seqCounters.quote);
        return {
          ...prev,
          quote: {
            id: Date.now(),
            quoteNo,
            quoteDate: today.toISOString().slice(0, 10),
            validUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
            customerId: prev.inputs.customerId,
            customerName: selectedCustomer?.name,
            creditGrade: selectedCustomer?.creditGrade,
            siteId: prev.inputs.siteId,
            siteName: selectedSite?.name,
            productType: prev.calculatedResult?.summary?.productType || '스크린',
            width: prev.inputs.W0,
            height: prev.inputs.H0,
            qty: prev.inputs.QTY,
            items: prev.calculatedResult?.items || [],
            totalAmount: prev.calculatedResult?.totalAmount || 0,
            vatAmount: prev.calculatedResult?.vatAmount || 0,
            finalAmount: prev.calculatedResult?.grandTotal || 0,
            status: '최종확정',
            discountRate: selectedCustomer?.discountRate || 0,
          }
        };
      });
      setCurrentStep(2);

      // Step 2: 견적 확정 → 수주 전환
      await new Promise(resolve => setTimeout(resolve, 400));
      const isRushOrder = scenario === 'rush-order';
      setWorkflowData(prev => {
        // 수주번호: KD-모델코드-YYMMDD-## (예: KD-TS-251209-02)
        const productType = prev.quote?.productType || '스크린';
        const orderNo = generateOrderNo(productType, today, seqCounters.order);
        const productionLot = generateProductionLot(today, seqCounters.production);
        const dueDate = new Date();
        dueDate.setDate(dueDate.getDate() + (isRushOrder ? 7 : 14)); // 긴급주문은 7일
        return {
          ...prev,
          order: {
            id: Date.now(),
            orderNo,
            productionLot,
            orderDate: today.toISOString().slice(0, 10),
            quoteId: prev.quote?.id,
            quoteNo: prev.quote?.quoteNo,
            customerId: prev.quote?.customerId,
            customerName: prev.quote?.customerName,
            creditGrade: prev.quote?.creditGrade,
            siteId: prev.quote?.siteId,
            siteName: prev.quote?.siteName,
            productType: prev.quote?.productType,
            items: prev.quote?.items || [],
            totalAmount: prev.quote?.finalAmount || 0,
            dueDate: dueDate.toISOString().slice(0, 10),
            status: '수주확정',
            isRush: isRushOrder,
            rushReason: isRushOrder ? '고객 긴급 요청' : null,
            priority: isRushOrder ? '긴급' : '일반',
          },
          quote: { ...prev.quote, status: '수주전환', convertedOrderNo: orderNo }
        };
      });
      setCurrentStep(3);

      // Step 3: 수주 전환 → 생산 지시
      await new Promise(resolve => setTimeout(resolve, 400));
      setWorkflowData(prev => {
        const processes = ['스크린', '절곡', '샤프트', '조립', '전장'];
        const newWorkOrders = processes.map((process, idx) => {
          // 중간검사 LOT: KD-WE-YYMMDD-##-(공정단계)
          const processInspLot = generateProcessInspectionLot(today, seqCounters.inspection, idx + 1);
          return {
            id: Date.now() + idx,
            workOrderNo: `${prev.order?.orderNo}-W${String(idx + 1).padStart(2, '0')}`,
            processInspectionLot: processInspLot,
            orderId: prev.order?.id,
            orderNo: prev.order?.orderNo,
            processName: process,
            processStep: idx + 1,
            qty: prev.inputs.QTY,
            producedQty: 0,
            defectQty: 0,
            status: '대기',
            priority: prev.order?.priority || '일반',
            startDate: null,
            endDate: null,
          };
        });
        return {
          ...prev,
          workOrders: newWorkOrders,
          order: { ...prev.order, status: '생산중' }
        };
      });
      setCurrentStep(4);

      // 사이즈 변경 시나리오
      if (scenario === 'size-change') {
        await new Promise(resolve => setTimeout(resolve, 400));
        setWorkflowData(prev => ({
          ...prev,
          sizeChangeLog: {
            originalSize: `${prev.inputs.W0}x${prev.inputs.H0}`,
            newSize: `${prev.inputs.W0 + 100}x${prev.inputs.H0 + 50}`,
            changeDate: new Date().toISOString().slice(0, 10),
            reason: '현장 실측 후 변경',
            approver: '생산관리자',
          },
          inputs: {
            ...prev.inputs,
            W0: prev.inputs.W0 + 100,
            H0: prev.inputs.H0 + 50,
          }
        }));
      }

      // Step 4: 생산 지시 → 품질 검사
      await new Promise(resolve => setTimeout(resolve, 400));
      const qualityResult = scenario === 'quality-fail' ? '불합격' :
        scenario === 'quality-conditional' ? '조건부합격' : '합격';

      setWorkflowData(prev => {
        const completedWO = prev.workOrders.map((wo, idx) => ({
          ...wo,
          producedQty: wo.qty,
          defectQty: scenario === 'quality-fail' && idx === 3 ? 1 : 0, // 조립 공정에서 불량
          status: '완료',
          startDate: today.toISOString().slice(0, 10),
          endDate: today.toISOString().slice(0, 10),
        }));

        // 검사 LOT 번호 생성
        const inspections = completedWO.map((wo, idx) => {
          const isFinalInspection = wo.processName === '조립';
          // 중간검사: KD-WE-YYMMDD-##-(공정단계), 제품검사: KD-SA-YYMMDD-##
          const inspLot = isFinalInspection
            ? generateProductInspectionLot(today, seqCounters.inspection + idx)
            : wo.processInspectionLot || generateProcessInspectionLot(today, seqCounters.inspection, wo.processStep);

          return {
            id: Date.now() + idx,
            inspectionLot: inspLot,
            inspectionNo: inspLot,
            workOrderId: wo.id,
            workOrderNo: wo.workOrderNo,
            inspectionType: isFinalInspection ? '제품검사' : '중간검사',
            inspectionItems: ['외관검사', '치수검사', '작동검사'],
            inspectionDate: today.toISOString().slice(0, 10),
            result: isFinalInspection ? qualityResult : '합격',
            defectType: qualityResult === '불합격' && isFinalInspection ? '외관불량' : null,
            defectDescription: qualityResult === '불합격' && isFinalInspection ? '스크래치 발견' : null,
            conditionalNote: qualityResult === '조건부합격' && isFinalInspection ? '경미한 외관 손상, 터치업 후 출하 가능' : null,
            inspector: '검사원A',
          };
        });

        // 제품검사 시 완제품/부품 LOT 발급
        const productLot = generateProductLot(prev.order?.orderNo, 1);

        return {
          ...prev,
          workOrders: completedWO,
          qualityInspections: inspections,
          finishedProductLot: productLot,
          installationLot: productLot, // 설치 LOT = 완제품 LOT
          order: { ...prev.order, status: qualityResult === '불합격' ? '재작업필요' : '생산완료' }
        };
      });
      setCurrentStep(5);

      // 품질 불합격 → 재작업 처리
      if (scenario === 'quality-fail') {
        await new Promise(resolve => setTimeout(resolve, 400));
        setWorkflowData(prev => ({
          ...prev,
          reworkOrder: {
            id: Date.now(),
            reworkNo: `RW-${Date.now().toString().slice(-8)}`,
            originalWorkOrderNo: prev.workOrders[3]?.workOrderNo,
            reason: '품질검사 불합격',
            defectType: '외관불량',
            reworkProcess: '조립 재작업',
            status: '재작업완료',
            completedDate: new Date().toISOString().slice(0, 10),
          },
          qualityInspections: prev.qualityInspections.map((qi, idx) =>
            idx === 3 ? { ...qi, result: '합격', reinspectionDate: new Date().toISOString().slice(0, 10), reinspectionNote: '재작업 후 재검사 합격' } : qi
          ),
          order: { ...prev.order, status: '생산완료' }
        }));
      }

      // Step 5: 품질 검사 → 출하
      await new Promise(resolve => setTimeout(resolve, 400));
      const isPartialShipment = scenario === 'partial-shipment';
      const shippedQty = isPartialShipment ? Math.ceil(workflowData.inputs.QTY / 2) : workflowData.inputs.QTY;

      setWorkflowData(prev => ({
        ...prev,
        shipment: {
          id: Date.now(),
          shipmentNo: `SH-${Date.now().toString().slice(-8)}`,
          orderId: prev.order?.id,
          orderNo: prev.order?.orderNo,
          customerId: prev.order?.customerId,
          customerName: prev.order?.customerName,
          siteId: prev.order?.siteId,
          siteName: prev.order?.siteName,
          shipmentDate: new Date().toISOString().slice(0, 10),
          carrier: '자체배송',
          status: isPartialShipment ? '부분출하' : '배송완료',
          shippedQty,
          totalQty: prev.inputs.QTY,
          remainingQty: prev.inputs.QTY - shippedQty,
          deliveryDate: new Date().toISOString().slice(0, 10),
          partialReason: isPartialShipment ? '재고 부족으로 부분 출하' : null,
        },
        order: { ...prev.order, status: isPartialShipment ? '부분출하' : '출하완료' }
      }));
      setCurrentStep(6);

      // 부분 출하 → 잔여 출하
      if (isPartialShipment) {
        await new Promise(resolve => setTimeout(resolve, 400));
        setWorkflowData(prev => ({
          ...prev,
          shipment2: {
            id: Date.now() + 1,
            shipmentNo: `SH-${Date.now().toString().slice(-8)}-2`,
            orderId: prev.order?.id,
            orderNo: prev.order?.orderNo,
            shipmentDate: new Date().toISOString().slice(0, 10),
            shippedQty: prev.shipment.remainingQty,
            status: '배송완료',
            note: '잔여 수량 출하',
          },
          shipment: { ...prev.shipment, status: '전량출하완료' },
          order: { ...prev.order, status: '출하완료' }
        }));
      }

      // Step 6: 출하 → 회계 처리
      await new Promise(resolve => setTimeout(resolve, 400));
      const creditGrade = selectedCustomer?.creditGrade || 'B';
      const isPaymentDelay = scenario === 'payment-delay' || creditGrade !== 'A';

      setWorkflowData(prev => {
        const supplyAmount = (prev.order?.totalAmount || 0) / 1.1;
        const salesNo = `SL-${Date.now().toString().slice(-8)}`;

        return {
          ...prev,
          sales: {
            id: Date.now(),
            salesNo,
            orderId: prev.order?.id,
            orderNo: prev.order?.orderNo,
            customerId: prev.order?.customerId,
            customerName: prev.order?.customerName,
            creditGrade,
            supplyAmount: Math.round(supplyAmount),
            vatAmount: Math.round(supplyAmount * 0.1),
            totalAmount: prev.order?.totalAmount || 0,
            salesDate: new Date().toISOString().slice(0, 10),
            paymentStatus: isPaymentDelay ? '미수금' : '수금완료',
            paymentDueDate: new Date(Date.now() + (creditGrade === 'A' ? 30 : creditGrade === 'B' ? 45 : 60) * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
          },
          collection: !isPaymentDelay ? {
            id: Date.now() + 1,
            collectionNo: `CL-${Date.now().toString().slice(-8)}`,
            salesId: Date.now(),
            salesNo,
            customerId: prev.order?.customerId,
            customerName: prev.order?.customerName,
            amount: prev.order?.totalAmount || 0,
            collectionDate: new Date().toISOString().slice(0, 10),
            paymentMethod: '계좌이체',
          } : null,
          order: { ...prev.order, status: isPaymentDelay ? '수금대기' : '완료' }
        };
      });
      setCurrentStep(7);

      // 수금 지연 → 수금 처리
      if (isPaymentDelay) {
        await new Promise(resolve => setTimeout(resolve, 400));
        setWorkflowData(prev => ({
          ...prev,
          collection: {
            id: Date.now() + 1,
            collectionNo: `CL-${Date.now().toString().slice(-8)}`,
            salesId: prev.sales?.id,
            salesNo: prev.sales?.salesNo,
            customerId: prev.order?.customerId,
            customerName: prev.order?.customerName,
            amount: prev.order?.totalAmount || 0,
            collectionDate: new Date().toISOString().slice(0, 10),
            paymentMethod: creditGrade === 'C' ? '어음' : '계좌이체',
            delayDays: creditGrade === 'A' ? 0 : creditGrade === 'B' ? 15 : 30,
            note: creditGrade !== 'A' ? `${creditGrade}등급 거래처 - 지연 수금` : null,
          },
          sales: { ...prev.sales, paymentStatus: '수금완료' },
          order: { ...prev.order, status: '완료' }
        }));
      }

      // 신규 품목 등록 시나리오 - 품목관리(생산관리 메뉴)에서 신규 품목 등록 후 견적 진행
      if (scenario === 'new-item') {
        setWorkflowData(prev => ({
          ...prev,
          newItem: {
            id: Date.now(),
            itemCode: `ITM-${Date.now().toString().slice(-6)}`,
            itemName: '신규 스크린 제품',
            category: '제품',
            itemType: 'FG',
            unit: 'EA',
            basePrice: 850000,
            registeredDate: new Date().toISOString().slice(0, 10),
            registeredBy: '생산팀',
            menuPath: '생산관리 > 품목관리',
            status: '등록완료',
          }
        }));
      }

      // 검사유형 전환 시나리오 - 입고검사/중간검사/제품검사 통합 테스트
      if (scenario === 'multi-inspection') {
        setWorkflowData(prev => ({
          ...prev,
          inspectionFlow: {
            iqc: { // 입고검사 (IQC)
              inspectionNo: `IQC-${Date.now().toString().slice(-6)}`,
              inspectionType: '입고검사',
              typeCode: 'IQC',
              targetItem: '원자재',
              inspectionItems: ['외관검사', '성적서확인', '수량검수'],
              result: '합격',
              date: new Date().toISOString().slice(0, 10),
            },
            pqc: { // 중간검사 (PQC)
              inspectionNo: `PQC-${Date.now().toString().slice(-6)}`,
              inspectionType: '중간검사',
              typeCode: 'PQC',
              targetProcess: '절곡공정',
              inspectionItems: ['치수검사', '가공상태', '규격확인'],
              result: '합격',
              date: new Date().toISOString().slice(0, 10),
            },
            fqc: { // 제품검사 (FQC)
              inspectionNo: `FQC-${Date.now().toString().slice(-6)}`,
              inspectionType: '제품검사',
              typeCode: 'FQC',
              targetItem: '완제품',
              inspectionItems: ['외관검사', '작동검사', '포장상태', '부속품확인'],
              result: '합격',
              date: new Date().toISOString().slice(0, 10),
            },
            menuPath: '품질관리 > 검사관리',
            note: '품질기준관리에서 정의된 3단계 검사유형(IQC/PQC/FQC) 통합 테스트',
          }
        }));
      }

      // 채번 테스트 시나리오 - 자동채번 규칙 검증
      if (scenario === 'numbering-test') {
        const today = new Date();
        const yymmdd = `${String(today.getFullYear()).slice(-2)}${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`;
        setWorkflowData(prev => ({
          ...prev,
          numberingResults: {
            menuPath: '기준정보 > 채번관리',
            rules: [
              {
                ruleName: '견적번호',
                pattern: 'QT-{YYYYMMDD}-{SEQ:3}',
                example: `QT-${today.toISOString().slice(0, 10).replace(/-/g, '')}-001`,
                description: '견적 문서번호 자동생성',
              },
              {
                ruleName: '수주번호',
                pattern: 'KD-{모델}-{YYMMDD}-{SEQ:2}',
                example: `KD-TS-${yymmdd}-01`,
                description: '수주번호 (모델코드 포함)',
              },
              {
                ruleName: '생산LOT',
                pattern: 'KD-WE-{YYMMDD}-{SEQ:2}',
                example: `KD-WE-${yymmdd}-01`,
                description: '생산 LOT번호',
              },
              {
                ruleName: '중간검사LOT',
                pattern: 'KD-WE-{YYMMDD}-{SEQ:2}-{공정단계}',
                example: `KD-WE-${yymmdd}-01-1`,
                description: '공정별 중간검사 LOT',
              },
              {
                ruleName: '제품검사LOT',
                pattern: 'KD-SA-{YYMMDD}-{SEQ:2}',
                example: `KD-SA-${yymmdd}-01`,
                description: '완제품 검사 LOT',
              },
              {
                ruleName: '완제품LOT',
                pattern: '{수주번호}-F{SEQ:2}',
                example: `KD-TS-${yymmdd}-01-F01`,
                description: '완제품/부품 LOT',
              },
            ],
            testStatus: '모든 채번규칙 검증 완료',
          }
        }));
      }

      // 공통코드 참조 시나리오 - 공통코드 활용 테스트
      if (scenario === 'code-reference') {
        setWorkflowData(prev => ({
          ...prev,
          codeReferences: {
            menuPath: '기준정보 > 공통코드관리',
            codeGroups: [
              {
                groupCode: 'ITEM_TYPE',
                groupName: '품목유형',
                codes: [
                  { code: 'FG', name: '제품', desc: '완제품' },
                  { code: 'PT', name: '부품', desc: '부품/파트' },
                  { code: 'WIP', name: '반제품', desc: '반제품/공정품' },
                  { code: 'RM', name: '원자재', desc: '원자재' },
                ],
                usedIn: ['품목관리', '재고관리', 'BOM관리'],
              },
              {
                groupCode: 'CUST_TYPE',
                groupName: '거래처유형',
                codes: [
                  { code: 'CUST', name: '고객사', desc: '제품 구매 고객' },
                  { code: 'SUPP', name: '공급업체', desc: '자재 공급업체' },
                  { code: 'BOTH', name: '고객/공급', desc: '고객 및 공급업체' },
                  { code: 'PARTNER', name: '협력사', desc: '외주/협력 업체' },
                ],
                usedIn: ['거래처관리', '발주관리', '매출관리'],
              },
              {
                groupCode: 'INSP_TYPE',
                groupName: '검사유형',
                codes: [
                  { code: 'IQC', name: '입고검사', desc: '자재 입고 시 검사' },
                  { code: 'PQC', name: '중간검사', desc: '생산 중 품질검사' },
                  { code: 'FQC', name: '제품검사', desc: '출하 후 고객요청 검사' },
                ],
                usedIn: ['검사관리', '품질관리', '품질기준관리'],
              },
              {
                groupCode: 'PROCESS_TYPE',
                groupName: '공정유형',
                codes: [
                  { code: 'MAIN', name: '주공정', desc: '메인 생산공정' },
                  { code: 'SUB', name: '보조공정', desc: '보조 작업공정' },
                  { code: 'QC', name: '검사공정', desc: '품질검사 공정' },
                  { code: 'PACK', name: '포장공정', desc: '포장/출하 공정' },
                ],
                usedIn: ['공정관리', '작업지시', '생산실적'],
              },
              {
                groupCode: 'SITE_TYPE',
                groupName: '현장유형',
                codes: [
                  { code: 'NEW', name: '신규현장', desc: '신규 설치 현장' },
                  { code: 'MAINT', name: '유지보수', desc: '유지보수 현장' },
                  { code: 'REPLACE', name: '교체현장', desc: '기존 설비 교체' },
                  { code: 'AS', name: 'AS현장', desc: 'AS 대응 현장' },
                ],
                usedIn: ['현장관리', '견적관리', '출하관리'],
              },
            ],
            testStatus: '모든 공통코드 참조 검증 완료',
          }
        }));
      }

      // 회계관리 - 매출관리 시나리오
      if (scenario === 'accounting-sales') {
        setWorkflowData(prev => ({
          ...prev,
          accountingSales: {
            menuPath: '회계관리 > 매출관리',
            testCases: [
              { id: 1, action: '매출전표 등록', data: { orderNo: 'ORD-202501-001', amount: 52000000, customer: '삼성물산(주)' }, result: '등록완료' },
              { id: 2, action: '매출 수정', data: { salesNo: 'KD-SH-250101-01', field: '금액', before: 52000000, after: 53000000 }, result: '수정완료' },
              { id: 3, action: '매출 조회', data: { period: '2025-01', filter: '거래처별' }, result: '3건 조회' },
              { id: 4, action: '세금계산서 발행', data: { salesNo: 'KD-SH-250101-01', type: '전자세금계산서' }, result: '발행완료' },
            ],
            summary: { total: 4, success: 4, fail: 0 },
            testStatus: '매출관리 전체 테스트 통과',
          }
        }));
      }

      // 회계관리 - 매입관리 시나리오
      if (scenario === 'accounting-purchase') {
        setWorkflowData(prev => ({
          ...prev,
          accountingPurchase: {
            menuPath: '회계관리 > 매입관리',
            testCases: [
              { id: 1, action: '매입전표 등록', data: { poNo: 'KD-SO-250101-01', amount: 12000000, supplier: '대한알루미늄' }, result: '등록완료' },
              { id: 2, action: '매입 수정', data: { purchaseNo: 'PR-202501-001', field: '단가', before: 50000, after: 48000 }, result: '수정완료' },
              { id: 3, action: '매입 조회', data: { period: '2025-01', filter: '공급업체별' }, result: '5건 조회' },
              { id: 4, action: '지급 예정 확인', data: { dueDate: '2025-02-10' }, result: '3건 지급예정' },
            ],
            summary: { total: 4, success: 4, fail: 0 },
            testStatus: '매입관리 전체 테스트 통과',
          }
        }));
      }

      // 회계관리 - 금전출납부 시나리오
      if (scenario === 'accounting-cashbook') {
        setWorkflowData(prev => ({
          ...prev,
          accountingCashbook: {
            menuPath: '회계관리 > 금전출납부',
            testCases: [
              { id: 1, action: '입금 등록', data: { type: '매출입금', amount: 50000000, account: '기업은행', customer: '삼성물산' }, result: '등록완료' },
              { id: 2, action: '출금 등록', data: { type: '경비지출', amount: 2500000, account: '기업은행', purpose: '원자재비' }, result: '등록완료' },
              { id: 3, action: '잔액 조회', data: { account: '기업은행', date: '2025-01-31' }, result: '잔액: 150,000,000원' },
              { id: 4, action: '월별 현금흐름', data: { period: '2025-01' }, result: '입금 200M / 출금 150M' },
            ],
            summary: { total: 4, success: 4, fail: 0 },
            testStatus: '금전출납부 전체 테스트 통과',
          }
        }));
      }

      // 회계관리 - 수금관리 시나리오
      if (scenario === 'accounting-collection') {
        setWorkflowData(prev => ({
          ...prev,
          accountingCollection: {
            menuPath: '회계관리 > 수금관리',
            testCases: [
              { id: 1, action: '미수금 조회', data: { customer: '전체', status: '미수' }, result: '5건 / 85,000,000원' },
              { id: 2, action: '수금 등록', data: { customer: '삼성물산(주)', amount: 52000000, method: '계좌이체' }, result: '수금완료' },
              { id: 3, action: '연체 알림', data: { overdueDays: 30 }, result: '연체 2건 알림발송' },
              { id: 4, action: '수금 현황표', data: { period: '2025-01', groupBy: '거래처' }, result: '리포트 생성완료' },
            ],
            summary: { total: 4, success: 4, fail: 0 },
            testStatus: '수금관리 전체 테스트 통과',
          }
        }));
      }

      // 회계관리 - 원가관리 시나리오
      if (scenario === 'accounting-cost') {
        setWorkflowData(prev => ({
          ...prev,
          accountingCost: {
            menuPath: '회계관리 > 원가관리',
            testCases: [
              { id: 1, action: '제품별 원가계산', data: { product: 'KS60 스크린', period: '2025-01' }, result: '원가: 385,000원/EA' },
              { id: 2, action: '원가 구성분석', data: { product: 'KS60 스크린' }, result: '재료비 60%, 노무비 25%, 경비 15%' },
              { id: 3, action: '원가 추이분석', data: { period: '2024-01 ~ 2025-01' }, result: '원가 5.2% 상승' },
              { id: 4, action: '손익분석표', data: { period: '2025-01', type: '제품별' }, result: '리포트 생성완료' },
            ],
            summary: { total: 4, success: 4, fail: 0 },
            testStatus: '원가관리 전체 테스트 통과',
          }
        }));
      }

      // ═══════════════════════════════════════════════════════════════════════════
      // 문서 출력 테스트 시나리오
      // ═══════════════════════════════════════════════════════════════════════════

      // 견적서 출력 테스트
      if (scenario === 'doc-quote') {
        setWorkflowData(prev => ({
          ...prev,
          documentTest: {
            docType: '견적서',
            docTypeCode: 'QT',
            menuPath: '판매관리 > 견적관리',
            testCases: [
              { id: 1, action: '견적서 생성', status: '완료', timestamp: new Date().toLocaleTimeString() },
              { id: 2, action: '결재 상신', status: '완료', timestamp: new Date().toLocaleTimeString() },
              { id: 3, action: '검토자 승인', status: '완료', approver: '판매팀장', timestamp: new Date().toLocaleTimeString() },
              { id: 4, action: '최종 승인', status: '완료', approver: '판매본부장', timestamp: new Date().toLocaleTimeString() },
              { id: 5, action: 'PDF 출력', status: '완료', format: 'A4', timestamp: new Date().toLocaleTimeString() },
              { id: 6, action: '이메일 발송', status: '완료', recipient: 'customer@example.com', timestamp: new Date().toLocaleTimeString() },
            ],
            document: {
              docNo: `QT-${today.toISOString().slice(0, 10).replace(/-/g, '')}-001`,
              title: '방화셔터 견적서',
              customer: selectedCustomer?.name || '삼성물산(주)',
              amount: prev.calculatedResult?.grandTotal || 52800000,
              createdAt: today.toISOString().slice(0, 10),
              createdBy: '김판매',
              status: '결재완료',
            },
            approvalLine: [
              { step: 1, role: '작성', name: '김판매', dept: '판매팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
              { step: 2, role: '검토', name: '이팀장', dept: '판매팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
              { step: 3, role: '승인', name: '박본부장', dept: '판매본부', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
            ],
            printOptions: {
              paperSize: 'A4',
              orientation: 'portrait',
              copies: 2,
              includeLogo: true,
              includeStamp: true,
            },
            summary: { total: 6, success: 6, fail: 0 },
          }
        }));
      }

      // 수주확인서 출력 테스트
      if (scenario === 'doc-order-confirm') {
        setWorkflowData(prev => ({
          ...prev,
          documentTest: {
            docType: '수주확인서',
            docTypeCode: 'OC',
            menuPath: '판매관리 > 수주관리',
            testCases: [
              { id: 1, action: '수주확인서 생성', status: '완료', timestamp: new Date().toLocaleTimeString() },
              { id: 2, action: '견적 연동 확인', status: '완료', linkedDoc: 'KD-PR-250109-01', timestamp: new Date().toLocaleTimeString() },
              { id: 3, action: '결재 상신', status: '완료', timestamp: new Date().toLocaleTimeString() },
              { id: 4, action: '생산팀 확인', status: '완료', approver: '생산팀장', timestamp: new Date().toLocaleTimeString() },
              { id: 5, action: '최종 승인', status: '완료', approver: '공장장', timestamp: new Date().toLocaleTimeString() },
              { id: 6, action: 'PDF 출력', status: '완료', format: 'A4', timestamp: new Date().toLocaleTimeString() },
            ],
            document: {
              docNo: `OC-${today.toISOString().slice(0, 10).replace(/-/g, '')}-001`,
              title: '수주확인서',
              customer: selectedCustomer?.name || '삼성물산(주)',
              orderNo: prev.order?.orderNo || 'KD-TS-251209-01',
              amount: prev.order?.totalAmount || 52800000,
              dueDate: prev.order?.dueDate || new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
              createdAt: today.toISOString().slice(0, 10),
              status: '결재완료',
            },
            approvalLine: [
              { step: 1, role: '작성', name: '김판매', dept: '판매팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
              { step: 2, role: '검토', name: '최생산팀장', dept: '생산팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
              { step: 3, role: '승인', name: '정공장장', dept: '생산본부', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
            ],
            summary: { total: 6, success: 6, fail: 0 },
          }
        }));
      }

      // 작업지시서 출력 테스트
      if (scenario === 'doc-work-order') {
        setWorkflowData(prev => ({
          ...prev,
          documentTest: {
            docType: '작업지시서',
            docTypeCode: 'WO',
            menuPath: '생산관리 > 작업지시관리',
            testCases: [
              { id: 1, action: '작업지시서 생성', status: '완료', count: 5, timestamp: new Date().toLocaleTimeString() },
              { id: 2, action: '수주 연동 확인', status: '완료', linkedDoc: 'KD-TS-251209-01', timestamp: new Date().toLocaleTimeString() },
              { id: 3, action: 'BOM 전개 확인', status: '완료', itemCount: 8, timestamp: new Date().toLocaleTimeString() },
              { id: 4, action: '결재 상신', status: '완료', timestamp: new Date().toLocaleTimeString() },
              { id: 5, action: '생산팀장 승인', status: '완료', approver: '생산팀장', timestamp: new Date().toLocaleTimeString() },
              { id: 6, action: '현장 배포', status: '완료', target: '생산현장', timestamp: new Date().toLocaleTimeString() },
            ],
            document: {
              docNo: `WO-${today.toISOString().slice(0, 10).replace(/-/g, '')}-001`,
              title: '작업지시서',
              orderNo: prev.order?.orderNo || 'KD-TS-251209-01',
              processes: ['스크린', '절곡', '샤프트', '조립', '전장'],
              qty: prev.inputs?.QTY || 2,
              startDate: today.toISOString().slice(0, 10),
              dueDate: prev.order?.dueDate || new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
              status: '결재완료',
            },
            approvalLine: [
              { step: 1, role: '작성', name: '박생산', dept: '생산관리팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
              { step: 2, role: '승인', name: '최생산팀장', dept: '생산팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
            ],
            summary: { total: 6, success: 6, fail: 0 },
          }
        }));
      }

      // 검사성적서 출력 테스트
      if (scenario === 'doc-inspection') {
        setWorkflowData(prev => ({
          ...prev,
          documentTest: {
            docType: '검사성적서',
            docTypeCode: 'IR',
            menuPath: '품질관리 > 검사관리',
            testCases: [
              { id: 1, action: '수입검사성적서(IQC) 생성', status: '완료', result: '합격', timestamp: new Date().toLocaleTimeString() },
              { id: 2, action: '중간검사성적서(PQC) 생성', status: '완료', result: '합격', count: 5, timestamp: new Date().toLocaleTimeString() },
              { id: 3, action: '제품검사성적서(FQC) 생성', status: '완료', result: '합격', timestamp: new Date().toLocaleTimeString() },
              { id: 4, action: 'QC팀장 검토', status: '완료', approver: 'QC팀장', timestamp: new Date().toLocaleTimeString() },
              { id: 5, action: '품질책임자 승인', status: '완료', approver: '품질책임자', timestamp: new Date().toLocaleTimeString() },
              { id: 6, action: 'PDF 출력 (고객제출용)', status: '완료', format: 'A4', timestamp: new Date().toLocaleTimeString() },
            ],
            document: {
              docNo: `IR-${today.toISOString().slice(0, 10).replace(/-/g, '')}-001`,
              title: '검사성적서',
              productionLot: prev.order?.productionLot || 'KD-WE-251209-01',
              inspectionTypes: ['IQC', 'PQC', 'FQC'],
              inspectionItems: [
                { name: '외관검사', spec: '스크래치, 변형 없음', result: '합격', value: 'OK' },
                { name: '치수검사', spec: '±3mm 이내', result: '합격', value: '2502x3148mm' },
                { name: '작동검사', spec: '정상작동', result: '합격', value: '5회 정상' },
                { name: '내화시험', spec: 'KS F 2268-1 합격', result: '합격', value: '60분 차염' },
              ],
              overallResult: '합격',
              createdAt: today.toISOString().slice(0, 10),
              status: '결재완료',
            },
            approvalLine: [
              { step: 1, role: '검사', name: '홍검사', dept: 'QC팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
              { step: 2, role: '검토', name: '강QC팀장', dept: 'QC팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
              { step: 3, role: '승인', name: '윤품질책임자', dept: '품질본부', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
            ],
            summary: { total: 7, success: 7, fail: 0 },
          }
        }));
      }

      // 출하지시서 출력 테스트
      if (scenario === 'doc-shipment') {
        setWorkflowData(prev => ({
          ...prev,
          documentTest: {
            docType: '출하지시서',
            docTypeCode: 'SD',
            menuPath: '물류관리 > 출하관리',
            testCases: [
              { id: 1, action: '출하지시서 생성', status: '완료', timestamp: new Date().toLocaleTimeString() },
              { id: 2, action: '수주/생산 완료 확인', status: '완료', linkedDoc: 'KD-TS-251209-01', timestamp: new Date().toLocaleTimeString() },
              { id: 3, action: '검사성적서 첨부', status: '완료', attachment: 'IR-20251209-001', timestamp: new Date().toLocaleTimeString() },
              { id: 4, action: '물류팀장 승인', status: '완료', approver: '물류팀장', timestamp: new Date().toLocaleTimeString() },
              { id: 5, action: '거래명세서 자동생성', status: '완료', linkedDoc: 'IV-20251209-001', timestamp: new Date().toLocaleTimeString() },
              { id: 6, action: '출하 PDF 출력', status: '완료', format: 'A4', timestamp: new Date().toLocaleTimeString() },
            ],
            document: {
              docNo: `SD-${today.toISOString().slice(0, 10).replace(/-/g, '')}-001`,
              title: '출하지시서',
              orderNo: prev.order?.orderNo || 'KD-TS-251209-01',
              customer: selectedCustomer?.name || '삼성물산(주)',
              site: selectedSite?.name || '강남 현장',
              shipmentDate: today.toISOString().slice(0, 10),
              carrier: '자체배송',
              driverName: '배송기사A',
              vehicleNo: '서울12가3456',
              items: [
                { name: '방화스크린 KS60', spec: '2500x3000mm', qty: 2, unit: 'SET' },
              ],
              status: '결재완료',
            },
            approvalLine: [
              { step: 1, role: '작성', name: '조물류', dept: '물류팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
              { step: 2, role: '승인', name: '한물류팀장', dept: '물류팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
            ],
            summary: { total: 6, success: 6, fail: 0 },
          }
        }));
      }

      // 거래명세서 출력 테스트
      if (scenario === 'doc-invoice') {
        setWorkflowData(prev => ({
          ...prev,
          documentTest: {
            docType: '거래명세서',
            docTypeCode: 'IV',
            menuPath: '판매관리 > 출하관리',
            testCases: [
              { id: 1, action: '거래명세서 생성', status: '완료', timestamp: new Date().toLocaleTimeString() },
              { id: 2, action: '출하 연동 확인', status: '완료', linkedDoc: 'SD-20251209-001', timestamp: new Date().toLocaleTimeString() },
              { id: 3, action: '금액 검증', status: '완료', amount: '52,800,000원', timestamp: new Date().toLocaleTimeString() },
              { id: 4, action: '경리팀 확인', status: '완료', approver: '경리담당', timestamp: new Date().toLocaleTimeString() },
              { id: 5, action: '인감 날인', status: '완료', stampType: '법인인감', timestamp: new Date().toLocaleTimeString() },
              { id: 6, action: 'PDF 출력', status: '완료', copies: 3, timestamp: new Date().toLocaleTimeString() },
            ],
            document: {
              docNo: `IV-${today.toISOString().slice(0, 10).replace(/-/g, '')}-001`,
              title: '거래명세서',
              customer: selectedCustomer?.name || '삼성물산(주)',
              businessNo: '123-45-67890',
              representative: '대표이사',
              address: '서울시 강남구 테헤란로 123',
              supplyAmount: Math.round((prev.order?.totalAmount || 52800000) / 1.1),
              vatAmount: Math.round((prev.order?.totalAmount || 52800000) / 1.1 * 0.1),
              totalAmount: prev.order?.totalAmount || 52800000,
              items: [
                { name: '방화스크린 KS60', spec: '2500x3000mm', qty: 2, unitPrice: 24000000, amount: 48000000 },
              ],
              issueDate: today.toISOString().slice(0, 10),
              status: '발급완료',
            },
            approvalLine: [
              { step: 1, role: '작성', name: '이경리', dept: '경리팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
              { step: 2, role: '확인', name: '박경리팀장', dept: '경리팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
            ],
            summary: { total: 6, success: 6, fail: 0 },
          }
        }));
      }

      // 세금계산서 발행 테스트
      if (scenario === 'doc-tax') {
        setWorkflowData(prev => ({
          ...prev,
          documentTest: {
            docType: '세금계산서',
            docTypeCode: 'TX',
            menuPath: '회계관리 > 매출관리',
            testCases: [
              { id: 1, action: '세금계산서 초안 생성', status: '완료', timestamp: new Date().toLocaleTimeString() },
              { id: 2, action: '매출 데이터 연동', status: '완료', linkedDoc: 'KD-SH-251209-01', timestamp: new Date().toLocaleTimeString() },
              { id: 3, action: '사업자정보 검증', status: '완료', businessNo: '123-45-67890', timestamp: new Date().toLocaleTimeString() },
              { id: 4, action: '경리팀장 승인', status: '완료', approver: '경리팀장', timestamp: new Date().toLocaleTimeString() },
              { id: 5, action: '전자서명', status: '완료', signType: '공인인증', timestamp: new Date().toLocaleTimeString() },
              { id: 6, action: '국세청 전송', status: '완료', ntsSendResult: '전송성공', timestamp: new Date().toLocaleTimeString() },
              { id: 7, action: '승인번호 수신', status: '완료', approvalNo: '20251209-12345678-00001234', timestamp: new Date().toLocaleTimeString() },
            ],
            document: {
              docNo: `TX-${today.toISOString().slice(0, 10).replace(/-/g, '')}-001`,
              title: '전자세금계산서',
              taxType: '세금계산서',
              issueType: '전자발급',
              supplier: {
                businessNo: '111-22-33333',
                companyName: '(주)방화산업',
                representative: '대표이사',
                address: '서울시 금천구 가산디지털로 123',
              },
              buyer: {
                businessNo: '123-45-67890',
                companyName: selectedCustomer?.name || '삼성물산(주)',
                representative: '대표이사',
              },
              supplyAmount: Math.round((prev.order?.totalAmount || 52800000) / 1.1),
              vatAmount: Math.round((prev.order?.totalAmount || 52800000) / 1.1 * 0.1),
              totalAmount: prev.order?.totalAmount || 52800000,
              issueDate: today.toISOString().slice(0, 10),
              ntsApprovalNo: '20251209-12345678-00001234',
              status: '국세청 전송완료',
            },
            approvalLine: [
              { step: 1, role: '작성', name: '이경리', dept: '경리팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
              { step: 2, role: '승인', name: '박경리팀장', dept: '경리팀', status: '완료', date: today.toISOString().slice(0, 10), signature: '✓' },
              { step: 3, role: '전자서명', name: '대표이사', dept: '경영진', status: '완료', date: today.toISOString().slice(0, 10), signature: '공인인증' },
            ],
            summary: { total: 7, success: 7, fail: 0 },
          }
        }));
      }

      // ═══════════════════════════════════════════════════════════════════════════
      // 결재 프로세스 테스트 시나리오
      // ═══════════════════════════════════════════════════════════════════════════

      // 정상 결재 프로세스 테스트
      if (scenario === 'approval-normal') {
        setWorkflowData(prev => ({
          ...prev,
          approvalTest: {
            testType: '정상 결재',
            menuPath: '전체 결재 프로세스',
            description: '작성 → 검토 → 승인 정상 흐름 테스트',
            testCases: [
              { id: 1, action: '문서 작성', status: '완료', actor: '김작성', role: '작성자', timestamp: new Date().toLocaleTimeString() },
              { id: 2, action: '결재 상신', status: '완료', actor: '김작성', nextApprover: '이검토', timestamp: new Date().toLocaleTimeString() },
              { id: 3, action: '검토자 확인', status: '완료', actor: '이검토', role: '검토자', action: '승인', timestamp: new Date().toLocaleTimeString() },
              { id: 4, action: '승인권자 확인', status: '완료', actor: '박승인', role: '승인권자', action: '최종승인', timestamp: new Date().toLocaleTimeString() },
              { id: 5, action: '결재 완료 알림', status: '완료', recipient: '김작성', notifyType: '이메일+푸시', timestamp: new Date().toLocaleTimeString() },
              { id: 6, action: '문서 상태 변경', status: '완료', beforeStatus: '결재중', afterStatus: '결재완료', timestamp: new Date().toLocaleTimeString() },
            ],
            approvalFlow: {
              docType: '견적서',
              docNo: 'KD-PR-251209-01',
              startTime: new Date(Date.now() - 3600000).toLocaleTimeString(),
              endTime: new Date().toLocaleTimeString(),
              totalDuration: '1시간 0분',
              steps: [
                { order: 1, role: '작성', name: '김작성', dept: '판매팀', status: '완료', timestamp: new Date(Date.now() - 3600000).toLocaleTimeString(), comment: '' },
                { order: 2, role: '검토', name: '이검토', dept: '판매팀', status: '완료', timestamp: new Date(Date.now() - 1800000).toLocaleTimeString(), comment: '내용 확인했습니다.' },
                { order: 3, role: '승인', name: '박승인', dept: '판매본부', status: '완료', timestamp: new Date().toLocaleTimeString(), comment: '승인합니다.' },
              ],
            },
            notifications: [
              { type: '상신알림', recipient: '이검토', sentAt: new Date(Date.now() - 3600000).toLocaleTimeString(), status: '발송완료' },
              { type: '검토완료알림', recipient: '박승인', sentAt: new Date(Date.now() - 1800000).toLocaleTimeString(), status: '발송완료' },
              { type: '결재완료알림', recipient: '김작성', sentAt: new Date().toLocaleTimeString(), status: '발송완료' },
            ],
            summary: { total: 6, success: 6, fail: 0 },
          }
        }));
      }

      // 결재 반려 테스트
      if (scenario === 'approval-reject') {
        setWorkflowData(prev => ({
          ...prev,
          approvalTest: {
            testType: '결재 반려',
            menuPath: '결재 프로세스',
            description: '검토자 반려 → 수정 → 재상신 테스트',
            testCases: [
              { id: 1, action: '문서 작성', status: '완료', actor: '김작성', timestamp: new Date().toLocaleTimeString() },
              { id: 2, action: '결재 상신', status: '완료', actor: '김작성', timestamp: new Date().toLocaleTimeString() },
              { id: 3, action: '검토자 반려', status: '완료', actor: '이검토', reason: '견적금액 재검토 필요', timestamp: new Date().toLocaleTimeString() },
              { id: 4, action: '반려 알림 수신', status: '완료', recipient: '김작성', timestamp: new Date().toLocaleTimeString() },
              { id: 5, action: '문서 수정', status: '완료', actor: '김작성', changes: ['금액 5% 조정'], timestamp: new Date().toLocaleTimeString() },
              { id: 6, action: '재상신', status: '완료', actor: '김작성', version: 'V2', timestamp: new Date().toLocaleTimeString() },
              { id: 7, action: '검토자 승인', status: '완료', actor: '이검토', comment: '수정 내용 확인', timestamp: new Date().toLocaleTimeString() },
              { id: 8, action: '최종 승인', status: '완료', actor: '박승인', timestamp: new Date().toLocaleTimeString() },
            ],
            approvalFlow: {
              docType: '견적서',
              docNo: 'KD-PR-251209-02',
              version: 'V2',
              rejectionHistory: [
                {
                  version: 'V1',
                  rejectedBy: '이검토',
                  rejectReason: '견적금액 재검토 필요',
                  rejectDate: today.toISOString().slice(0, 10),
                  modifiedFields: ['totalAmount', 'discountRate'],
                }
              ],
              steps: [
                { order: 1, role: '작성', name: '김작성', status: '완료', version: 'V1→V2' },
                { order: 2, role: '검토', name: '이검토', status: '완료', action: '반려→승인' },
                { order: 3, role: '승인', name: '박승인', status: '완료' },
              ],
            },
            summary: { total: 8, success: 8, fail: 0 },
          }
        }));
      }

      // 결재 대결 테스트
      if (scenario === 'approval-delegate') {
        setWorkflowData(prev => ({
          ...prev,
          approvalTest: {
            testType: '결재 대결',
            menuPath: '결재 프로세스',
            description: '부재 시 대결처리 테스트',
            testCases: [
              { id: 1, action: '문서 작성', status: '완료', actor: '김작성', timestamp: new Date().toLocaleTimeString() },
              { id: 2, action: '결재 상신', status: '완료', actor: '김작성', timestamp: new Date().toLocaleTimeString() },
              { id: 3, action: '검토자 부재 확인', status: '완료', absentee: '이검토', reason: '출장', period: '12/9~12/11', timestamp: new Date().toLocaleTimeString() },
              { id: 4, action: '대결자 자동 지정', status: '완료', delegate: '최대결', originalApprover: '이검토', timestamp: new Date().toLocaleTimeString() },
              { id: 5, action: '대결 처리', status: '완료', actor: '최대결', comment: '이검토 대결', timestamp: new Date().toLocaleTimeString() },
              { id: 6, action: '최종 승인', status: '완료', actor: '박승인', timestamp: new Date().toLocaleTimeString() },
              { id: 7, action: '대결 이력 기록', status: '완료', logged: true, timestamp: new Date().toLocaleTimeString() },
            ],
            approvalFlow: {
              docType: '작업지시서',
              docNo: 'KD-WO-251209-01',
              delegateInfo: {
                originalApprover: '이검토',
                delegate: '최대결',
                delegateReason: '출장',
                delegatePeriod: '2025-12-09 ~ 2025-12-11',
                delegateRegisteredAt: '2025-12-08',
              },
              steps: [
                { order: 1, role: '작성', name: '김작성', status: '완료' },
                { order: 2, role: '검토', name: '최대결', status: '완료', note: '이검토 대결', originalApprover: '이검토' },
                { order: 3, role: '승인', name: '박승인', status: '완료' },
              ],
            },
            summary: { total: 7, success: 7, fail: 0 },
          }
        }));
      }

      // 긴급 결재 테스트
      if (scenario === 'approval-urgent') {
        setWorkflowData(prev => ({
          ...prev,
          approvalTest: {
            testType: '긴급 결재',
            menuPath: '결재 프로세스',
            description: '긴급 결재선 단축 처리 테스트',
            testCases: [
              { id: 1, action: '긴급 문서 생성', status: '완료', urgentLevel: '긴급', timestamp: new Date().toLocaleTimeString() },
              { id: 2, action: '긴급 결재 요청', status: '완료', actor: '김작성', reason: '납기 긴급', timestamp: new Date().toLocaleTimeString() },
              { id: 3, action: '결재선 자동 단축', status: '완료', originalSteps: 3, reducedSteps: 2, timestamp: new Date().toLocaleTimeString() },
              { id: 4, action: '긴급 알림 발송', status: '완료', notifyType: 'SMS+카카오톡+푸시', timestamp: new Date().toLocaleTimeString() },
              { id: 5, action: '승인권자 즉시 확인', status: '완료', actor: '박승인', responseTime: '5분', timestamp: new Date().toLocaleTimeString() },
              { id: 6, action: '긴급 결재 완료', status: '완료', totalTime: '15분', timestamp: new Date().toLocaleTimeString() },
            ],
            approvalFlow: {
              docType: '출하지시서',
              docNo: 'SD-20251209-001',
              urgentInfo: {
                isUrgent: true,
                urgentLevel: '긴급',
                urgentReason: '고객 긴급 요청 - 오늘 출하 필요',
                originalApprovalLine: ['작성→검토→승인'],
                reducedApprovalLine: ['작성→승인'],
                skippedSteps: ['검토'],
                notificationChannels: ['SMS', '카카오톡', '푸시알림', '이메일'],
              },
              steps: [
                { order: 1, role: '작성', name: '김작성', status: '완료', timestamp: new Date(Date.now() - 900000).toLocaleTimeString() },
                { order: 2, role: '승인', name: '박승인', status: '완료', timestamp: new Date().toLocaleTimeString(), note: '긴급결재' },
              ],
              totalProcessTime: '15분',
              normalProcessTime: '평균 2시간',
              timeSaved: '1시간 45분',
            },
            summary: { total: 6, success: 6, fail: 0 },
          }
        }));
      }

      // 문서 전체흐름 테스트 (모든 문서 + 결재 통합)
      if (scenario === 'doc-full-flow') {
        setWorkflowData(prev => ({
          ...prev,
          fullDocumentFlow: {
            testType: '문서 전체흐름 테스트',
            description: '견적 → 수주 → 생산 → 검사 → 출하 → 회계 전 과정의 문서출력 및 결재 통합 테스트',
            testPhases: [
              {
                phase: '판매단계',
                documents: [
                  { docType: '견적서', docNo: 'KD-PR-251209-01', status: '결재완료', approvalTime: '30분' },
                  { docType: '수주확인서', docNo: 'OC-20251209-001', status: '결재완료', approvalTime: '45분' },
                ],
                approvalCount: 2,
                totalApprovals: 6,
              },
              {
                phase: '생산단계',
                documents: [
                  { docType: '작업지시서', docNo: 'KD-WO-251209-01', status: '결재완료', approvalTime: '20분', count: 5 },
                  { docType: '생산일보', docNo: 'PR-20251209-001', status: '작성완료', count: 5 },
                ],
                approvalCount: 1,
                totalApprovals: 2,
              },
              {
                phase: '품질단계',
                documents: [
                  { docType: '수입검사성적서', docNo: 'IQC-20251209-001', status: '결재완료', approvalTime: '15분' },
                  { docType: '중간검사성적서', docNo: 'PQC-20251209-001', status: '결재완료', approvalTime: '15분', count: 5 },
                  { docType: '제품검사성적서', docNo: 'FQC-20251209-001', status: '결재완료', approvalTime: '20분' },
                ],
                approvalCount: 3,
                totalApprovals: 9,
              },
              {
                phase: '물류단계',
                documents: [
                  { docType: '출하지시서', docNo: 'SD-20251209-001', status: '결재완료', approvalTime: '15분' },
                  { docType: '거래명세서', docNo: 'IV-20251209-001', status: '발급완료', approvalTime: '10분' },
                ],
                approvalCount: 2,
                totalApprovals: 4,
              },
              {
                phase: '회계단계',
                documents: [
                  { docType: '매출전표', docNo: 'KD-SH-251209-01', status: '등록완료' },
                  { docType: '세금계산서', docNo: 'TX-20251209-001', status: '국세청전송완료', approvalTime: '30분' },
                ],
                approvalCount: 1,
                totalApprovals: 3,
              },
            ],
            testSummary: {
              totalDocuments: 14,
              totalApprovals: 27,
              totalApprovalTime: '3시간 30분',
              avgApprovalTime: '15분/건',
              documentTypes: ['견적서', '수주확인서', '작업지시서', '생산일보', '검사성적서(4종)', '출하지시서', '거래명세서', '매출전표', '세금계산서'],
              approvalRoles: ['작성자', '검토자', '승인권자', '품질책임자', '경리팀장', '대표이사'],
            },
            testCases: [
              { id: 1, phase: '판매', action: '견적서 결재', status: '완료' },
              { id: 2, phase: '판매', action: '수주확인서 결재', status: '완료' },
              { id: 3, phase: '생산', action: '작업지시서 결재', status: '완료' },
              { id: 4, phase: '품질', action: '검사성적서 결재 (4건)', status: '완료' },
              { id: 5, phase: '물류', action: '출하지시서 결재', status: '완료' },
              { id: 6, phase: '물류', action: '거래명세서 발급', status: '완료' },
              { id: 7, phase: '회계', action: '세금계산서 발행', status: '완료' },
              { id: 8, phase: '통합', action: '전체 문서 PDF 생성', status: '완료' },
            ],
            summary: { total: 8, success: 8, fail: 0 },
          }
        }));
      }

      // ═══════════════════════════════════════════════════════════════════════════
      // MVP 핵심 테스트 시나리오 (수주→작업지시→자재투입→작업실적→검사→출하)
      // ═══════════════════════════════════════════════════════════════════════════

      // MVP 핵심흐름 테스트
      if (scenario === 'mvp-core') {
        const yymmdd = `${String(today.getFullYear()).slice(-2)}${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`;
        setWorkflowData(prev => ({
          ...prev,
          mvpCoreTest: {
            testType: 'MVP 핵심흐름 테스트',
            description: '수주 → 작업지시 → 자재투입 → 작업실적 → 검사 → 출하 MVP 핵심 프로세스',
            menuPath: 'MVP 핵심 메뉴: 품목관리, 생산현황판, 작업지시관리, 작업실적, 작업자화면',
            testSteps: [
              { step: 1, name: '수주 등록', menu: '판매관리 > 수주관리', status: '완료', orderNo: `KD-TS-${yymmdd}-01` },
              { step: 2, name: '작업지시 생성', menu: '생산관리 > 작업지시관리', status: '완료', woCount: 5 },
              { step: 3, name: '자재투입', menu: '생산관리 > 작업지시관리 > 자재투입', status: '완료', materials: 8 },
              { step: 4, name: '작업실적 입력', menu: '생산관리 > 작업실적', status: '완료', resultCount: 5 },
              { step: 5, name: '품질검사', menu: '품질관리 > 검사관리', status: '완료', inspCount: 6 },
              { step: 6, name: '출하처리', menu: '판매관리 > 출하관리', status: '완료', shipQty: prev.inputs?.QTY || 2 },
            ],
            workOrders: [
              { woNo: `KD-TS-${yymmdd}-01-W01`, process: '스크린', status: '완료', qty: prev.inputs?.QTY || 2 },
              { woNo: `KD-TS-${yymmdd}-01-W02`, process: '절곡', status: '완료', qty: prev.inputs?.QTY || 2 },
              { woNo: `KD-TS-${yymmdd}-01-W03`, process: '샤프트', status: '완료', qty: prev.inputs?.QTY || 2 },
              { woNo: `KD-TS-${yymmdd}-01-W04`, process: '조립', status: '완료', qty: prev.inputs?.QTY || 2 },
              { woNo: `KD-TS-${yymmdd}-01-W05`, process: '전장', status: '완료', qty: prev.inputs?.QTY || 2 },
            ],
            summary: { total: 6, success: 6, fail: 0 },
            testStatus: 'MVP 핵심흐름 테스트 통과',
          }
        }));
      }

      // MVP 자재투입 테스트
      if (scenario === 'mvp-material-input') {
        const yymmdd = `${String(today.getFullYear()).slice(-2)}${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`;
        setWorkflowData(prev => ({
          ...prev,
          mvpMaterialInput: {
            testType: 'MVP 자재투입 테스트',
            description: '작업지시에서 BOM 기반 자재 자동투입 및 수동조정',
            menuPath: '생산관리 > 작업지시관리 > 자재투입',
            testCases: [
              { id: 1, action: 'BOM 전개', data: { orderNo: `KD-TS-${yymmdd}-01`, items: 8 }, result: '성공' },
              { id: 2, action: '자재 자동투입', data: { items: 8, totalQty: 16 }, result: '성공' },
              { id: 3, action: '재고 확인', data: { available: 8, shortage: 0 }, result: '성공' },
              { id: 4, action: '투입량 조정', data: { item: 'SL-001', before: 2, after: 3 }, result: '성공' },
              { id: 5, action: '투입 확정', data: { totalItems: 8, status: '투입완료' }, result: '성공' },
            ],
            materials: [
              { code: 'SL-001', name: '슬랫', unit: 'EA', required: 4, input: 4, status: '투입완료' },
              { code: 'SC-001', name: '스크린', unit: 'M', required: 10, input: 10, status: '투입완료' },
              { code: 'SH-001', name: '샤프트', unit: 'EA', required: 2, input: 2, status: '투입완료' },
              { code: 'MT-001', name: '모터', unit: 'EA', required: 2, input: 2, status: '투입완료' },
              { code: 'CB-001', name: '제어반', unit: 'EA', required: 2, input: 2, status: '투입완료' },
              { code: 'BR-001', name: '브라켓', unit: 'EA', required: 8, input: 8, status: '투입완료' },
              { code: 'BT-001', name: '볼트세트', unit: 'SET', required: 4, input: 4, status: '투입완료' },
              { code: 'LB-001', name: '라벨', unit: 'EA', required: 4, input: 4, status: '투입완료' },
            ],
            summary: { total: 5, success: 5, fail: 0 },
            testStatus: 'MVP 자재투입 테스트 통과',
          }
        }));
      }

      // MVP 작업실적 테스트
      if (scenario === 'mvp-work-result') {
        const yymmdd = `${String(today.getFullYear()).slice(-2)}${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`;
        setWorkflowData(prev => ({
          ...prev,
          mvpWorkResult: {
            testType: 'MVP 작업실적 테스트',
            description: '공정별 작업실적 입력 및 완료처리',
            menuPath: '생산관리 > 작업실적',
            testCases: [
              { id: 1, action: '스크린공정 실적입력', process: '스크린', qty: 2, goodQty: 2, defectQty: 0, result: '성공' },
              { id: 2, action: '절곡공정 실적입력', process: '절곡', qty: 2, goodQty: 2, defectQty: 0, result: '성공' },
              { id: 3, action: '샤프트공정 실적입력', process: '샤프트', qty: 2, goodQty: 2, defectQty: 0, result: '성공' },
              { id: 4, action: '조립공정 실적입력', process: '조립', qty: 2, goodQty: 2, defectQty: 0, result: '성공' },
              { id: 5, action: '전장공정 실적입력', process: '전장', qty: 2, goodQty: 2, defectQty: 0, result: '성공' },
              { id: 6, action: '생산완료 처리', data: { totalQty: 2, status: '생산완료' }, result: '성공' },
            ],
            workResults: [
              { woNo: `KD-TS-${yymmdd}-01-W01`, process: '스크린', worker: '김작업', startTime: '09:00', endTime: '11:00', qty: 2, goodQty: 2, status: '완료' },
              { woNo: `KD-TS-${yymmdd}-01-W02`, process: '절곡', worker: '이작업', startTime: '11:00', endTime: '13:00', qty: 2, goodQty: 2, status: '완료' },
              { woNo: `KD-TS-${yymmdd}-01-W03`, process: '샤프트', worker: '박작업', startTime: '14:00', endTime: '15:30', qty: 2, goodQty: 2, status: '완료' },
              { woNo: `KD-TS-${yymmdd}-01-W04`, process: '조립', worker: '최작업', startTime: '15:30', endTime: '17:00', qty: 2, goodQty: 2, status: '완료' },
              { woNo: `KD-TS-${yymmdd}-01-W05`, process: '전장', worker: '정작업', startTime: '17:00', endTime: '18:00', qty: 2, goodQty: 2, status: '완료' },
            ],
            summary: { total: 6, success: 6, fail: 0 },
            testStatus: 'MVP 작업실적 테스트 통과',
          }
        }));
      }

      // MVP 작업자화면 테스트
      if (scenario === 'mvp-worker-screen') {
        const yymmdd = `${String(today.getFullYear()).slice(-2)}${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`;
        setWorkflowData(prev => ({
          ...prev,
          mvpWorkerScreen: {
            testType: 'MVP 작업자화면 테스트',
            description: '현장 작업자용 간편 입력 화면 테스트',
            menuPath: '생산관리 > 작업자화면',
            testCases: [
              { id: 1, action: '작업자 로그인', data: { workerId: 'W001', name: '김작업' }, result: '성공' },
              { id: 2, action: '할당작업 조회', data: { assignedWO: 3, status: '대기' }, result: '성공' },
              { id: 3, action: '작업시작 처리', data: { woNo: `KD-TS-${yymmdd}-01-W01`, startTime: '09:00' }, result: '성공' },
              { id: 4, action: '진행상황 업데이트', data: { progress: 50, currentQty: 1 }, result: '성공' },
              { id: 5, action: '불량등록', data: { defectType: '외관불량', qty: 0 }, result: '성공' },
              { id: 6, action: '작업완료 처리', data: { endTime: '11:00', goodQty: 2 }, result: '성공' },
              { id: 7, action: '다음작업 할당', data: { nextWO: `KD-TS-${yymmdd}-01-W02` }, result: '성공' },
            ],
            workerInfo: {
              workerId: 'W001',
              name: '김작업',
              department: '생산1팀',
              assignedProcess: '스크린',
              todayTasks: 3,
              completedTasks: 1,
              performance: '100%',
            },
            summary: { total: 7, success: 7, fail: 0 },
            testStatus: 'MVP 작업자화면 테스트 통과',
          }
        }));
      }

      // MVP 생산현황판 테스트
      if (scenario === 'mvp-production-board') {
        setWorkflowData(prev => ({
          ...prev,
          mvpProductionBoard: {
            testType: 'MVP 생산현황판 테스트',
            description: '실시간 생산현황 모니터링 대시보드',
            menuPath: '생산관리 > 생산현황판',
            testCases: [
              { id: 1, action: '전체현황 조회', data: { totalWO: 15, inProgress: 5, completed: 8 }, result: '성공' },
              { id: 2, action: '공정별 현황', data: { processes: 5, bottleneck: '없음' }, result: '성공' },
              { id: 3, action: '실시간 갱신', data: { refreshRate: '10초', lastUpdate: new Date().toLocaleTimeString() }, result: '성공' },
              { id: 4, action: '납기지연 알림', data: { delayedOrders: 0, warningOrders: 1 }, result: '성공' },
              { id: 5, action: '작업자별 현황', data: { activeWorkers: 5, idleWorkers: 0 }, result: '성공' },
              { id: 6, action: '일일 생산실적', data: { planned: 10, actual: 8, achievement: '80%' }, result: '성공' },
            ],
            dashboardData: {
              todayOrders: 5,
              inProgressWO: 3,
              completedWO: 12,
              delayedWO: 0,
              processStatus: [
                { process: '스크린', queue: 2, inProgress: 1, completed: 5 },
                { process: '절곡', queue: 3, inProgress: 1, completed: 4 },
                { process: '샤프트', queue: 2, inProgress: 1, completed: 5 },
                { process: '조립', queue: 1, inProgress: 1, completed: 6 },
                { process: '전장', queue: 2, inProgress: 0, completed: 6 },
              ],
              alerts: [
                { type: 'warning', message: '주문 KD-TS-251210-01 납기 D-3', time: new Date().toLocaleTimeString() },
              ],
            },
            summary: { total: 6, success: 6, fail: 0 },
            testStatus: 'MVP 생산현황판 테스트 통과',
          }
        }));
      }

      // MVP 재고현황 테스트
      if (scenario === 'mvp-stock-status') {
        setWorkflowData(prev => ({
          ...prev,
          mvpStockStatus: {
            testType: 'MVP 재고현황 테스트',
            description: '자재/제품 재고현황 조회',
            menuPath: '자재관리 > 재고현황',
            testCases: [
              { id: 1, action: '전체재고 조회', data: { totalItems: 50, totalQty: 1250 }, result: '성공' },
              { id: 2, action: '품목별 조회', data: { itemCode: 'SL-001', currentQty: 100, unit: 'EA' }, result: '성공' },
              { id: 3, action: '안전재고 확인', data: { belowSafety: 3, warningItems: ['MT-001', 'CB-001', 'BR-001'] }, result: '성공' },
              { id: 4, action: '창고별 조회', data: { warehouses: 2, mainStock: 1000, subStock: 250 }, result: '성공' },
              { id: 5, action: '재고이력 조회', data: { item: 'SL-001', period: '최근30일', movements: 25 }, result: '성공' },
            ],
            stockData: [
              { code: 'SL-001', name: '슬랫', category: '원자재', qty: 100, safetyStock: 50, status: '정상' },
              { code: 'SC-001', name: '스크린', category: '원자재', qty: 200, safetyStock: 100, status: '정상' },
              { code: 'MT-001', name: '모터', category: '부품', qty: 15, safetyStock: 20, status: '부족' },
              { code: 'CB-001', name: '제어반', category: '부품', qty: 10, safetyStock: 15, status: '부족' },
              { code: 'FG-001', name: '완제품', category: '제품', qty: 5, safetyStock: 0, status: '정상' },
            ],
            summary: { total: 5, success: 5, fail: 0 },
            testStatus: 'MVP 재고현황 테스트 통과',
          }
        }));
      }

      // MVP 입고관리 테스트
      if (scenario === 'mvp-inbound') {
        setWorkflowData(prev => ({
          ...prev,
          mvpInbound: {
            testType: 'MVP 입고관리 테스트',
            description: '자재입고 등록 및 처리',
            menuPath: '자재관리 > 입고관리',
            testCases: [
              { id: 1, action: '입고예정 조회', data: { expectedItems: 5, supplier: '대한알루미늄' }, result: '성공' },
              { id: 2, action: '입고등록', data: { poNo: 'KD-SO-251209-01', items: 3, totalQty: 150 }, result: '성공' },
              { id: 3, action: '검수확인', data: { inspResult: '합격', passQty: 150, failQty: 0 }, result: '성공' },
              { id: 4, action: '입고확정', data: { inboundNo: 'KD-IN-251209-01', warehouse: '본창고' }, result: '성공' },
              { id: 5, action: '재고반영', data: { updatedItems: 3, totalIncreased: 150 }, result: '성공' },
              { id: 6, action: '입고이력 조회', data: { period: '오늘', totalInbound: 2 }, result: '성공' },
            ],
            inboundData: [
              {
                inboundNo: 'KD-IN-251209-01', poNo: 'KD-SO-251209-01', supplier: '대한알루미늄',
                items: [
                  { code: 'SL-001', name: '슬랫', qty: 50, unit: 'EA', status: '입고완료' },
                  { code: 'SC-001', name: '스크린', qty: 50, unit: 'M', status: '입고완료' },
                  { code: 'BR-001', name: '브라켓', qty: 50, unit: 'EA', status: '입고완료' },
                ],
                inboundDate: today.toISOString().slice(0, 10),
                status: '입고완료',
              }
            ],
            summary: { total: 6, success: 6, fail: 0 },
            testStatus: 'MVP 입고관리 테스트 통과',
          }
        }));
      }

      // MVP 전체흐름 테스트
      if (scenario === 'mvp-full-flow') {
        const yymmdd = `${String(today.getFullYear()).slice(-2)}${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`;
        setWorkflowData(prev => ({
          ...prev,
          mvpFullFlow: {
            testType: 'MVP 전체흐름 통합 테스트',
            description: 'MVP 전 과정(수주→작업지시→자재투입→실적→검사→출하) 통합 테스트',
            menuPath: 'MVP 메뉴 전체',
            mvpMenus: {
              production: ['품목관리', '생산현황판', '작업지시관리', '작업실적', '작업자화면'],
              inventory: ['재고현황', '입고관리'],
              quality: ['검사기준', '검사실적'],
              sales: ['견적관리', '수주관리', '출하관리'],
            },
            testPhases: [
              {
                phase: '수주단계',
                tests: [
                  { name: '견적등록', status: '✅ 통과', time: '0.5s' },
                  { name: '수주전환', status: '✅ 통과', time: '0.3s' },
                ],
              },
              {
                phase: '생산준비',
                tests: [
                  { name: '작업지시생성', status: '✅ 통과', time: '0.4s' },
                  { name: 'BOM전개', status: '✅ 통과', time: '0.3s' },
                  { name: '자재투입', status: '✅ 통과', time: '0.5s' },
                ],
              },
              {
                phase: '생산실행',
                tests: [
                  { name: '작업자할당', status: '✅ 통과', time: '0.2s' },
                  { name: '공정별실적', status: '✅ 통과', time: '0.8s' },
                  { name: '현황판갱신', status: '✅ 통과', time: '0.2s' },
                ],
              },
              {
                phase: '품질검사',
                tests: [
                  { name: '중간검사', status: '✅ 통과', time: '0.4s' },
                  { name: '제품검사', status: '✅ 통과', time: '0.3s' },
                ],
              },
              {
                phase: '출하/완료',
                tests: [
                  { name: '출하처리', status: '✅ 통과', time: '0.3s' },
                  { name: '재고차감', status: '✅ 통과', time: '0.2s' },
                  { name: '완료처리', status: '✅ 통과', time: '0.2s' },
                ],
              },
            ],
            orderInfo: {
              orderNo: `KD-TS-${yymmdd}-01`,
              customer: selectedCustomer?.name || '삼성물산(주)',
              product: '방화셔터 KS60',
              qty: prev.inputs?.QTY || 2,
              status: '출하완료',
            },
            testSummary: {
              totalTests: 13,
              passed: 13,
              failed: 0,
              passRate: '100%',
              totalTime: '4.1s',
              coverage: 'MVP 핵심기능 100%',
            },
            summary: { total: 13, success: 13, fail: 0 },
            testStatus: 'MVP 전체흐름 통합 테스트 통과',
          }
        }));
      }

      setCurrentStep(8);
    };

    return (
      <div className="space-y-6">
        {/* 시나리오 선택 */}
        <div className="bg-white p-4 rounded-lg border shadow-sm">
          <h3 className="font-semibold text-gray-800 mb-3 flex items-center gap-2">
            <ClipboardList className="w-5 h-5 text-purple-600" />
            테스트 시나리오 선택
          </h3>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-2">
            {testScenarios.map(sc => (
              <button
                key={sc.id}
                onClick={() => setSelectedScenario(sc.id)}
                disabled={isAutoRunning}
                className={`p-3 rounded-lg border-2 text-left transition-all ${selectedScenario === sc.id
                    ? 'border-purple-500 bg-purple-50 shadow-md'
                    : 'border-gray-200 hover:border-purple-300 hover:bg-purple-50/50'
                  } ${isAutoRunning ? 'opacity-50 cursor-not-allowed' : ''}`}
              >
                <div className="text-xl mb-1">{sc.icon}</div>
                <div className="font-medium text-sm">{sc.label}</div>
                <div className="text-xs text-gray-500">{sc.desc}</div>
              </button>
            ))}
          </div>
        </div>

        {/* 진행 단계 표시 */}
        <div className="bg-gradient-to-r from-blue-50 to-purple-50 p-4 rounded-lg border">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold text-gray-800 flex items-center gap-2">
              <PlayCircle className="w-5 h-5 text-blue-600" />
              전체 업무 흐름 테스트
              {selectedScenario !== 'normal' && (
                <span className="text-sm font-normal text-purple-600 bg-purple-100 px-2 py-0.5 rounded">
                  {testScenarios.find(s => s.id === selectedScenario)?.icon} {testScenarios.find(s => s.id === selectedScenario)?.label}
                </span>
              )}
            </h3>
            <div className="flex gap-2">
              <button
                onClick={runAutoWorkflow}
                disabled={isAutoRunning}
                className={`px-4 py-1.5 text-sm font-medium rounded-lg transition-all flex items-center gap-2 ${isAutoRunning
                    ? 'bg-blue-300 text-white cursor-not-allowed'
                    : 'bg-gradient-to-r from-blue-600 to-purple-600 text-white hover:from-blue-700 hover:to-purple-700 shadow-md hover:shadow-lg'
                  }`}
              >
                {isAutoRunning ? (
                  <>
                    <RefreshCw className="w-4 h-4 animate-spin" />
                    실행 중...
                  </>
                ) : (
                  <>
                    <Zap className="w-4 h-4" />
                    {selectedScenario === 'full-cycle' ? '전체 시나리오 실행' : '시나리오 실행'}
                  </>
                )}
              </button>
              <button
                onClick={resetWorkflow}
                disabled={isAutoRunning}
                className="px-3 py-1 text-sm bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50"
              >
                초기화
              </button>
            </div>
          </div>

          {/* 전체 사이클 테스트 결과 - 개선된 대시보드 */}
          {selectedScenario === 'full-cycle' && testResults.length > 0 && (
            <div className="mb-4 space-y-3">
              {/* 테스트 요약 대시보드 */}
              {testSummary && (
                <div className="bg-gradient-to-r from-green-50 to-blue-50 p-4 rounded-lg border-2 border-green-200">
                  <div className="flex items-center justify-between mb-3">
                    <h4 className="font-bold text-lg text-gray-800 flex items-center gap-2">
                      🎯 전체 테스트 완료
                    </h4>
                    <span className="text-xs text-gray-500">{testSummary.completedAt}</span>
                  </div>
                  <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
                    <div className="bg-white p-3 rounded-lg border shadow-sm text-center">
                      <div className="text-2xl font-bold text-blue-600">{testSummary.totalScenarios}</div>
                      <div className="text-xs text-gray-500">전체 시나리오</div>
                    </div>
                    <div className="bg-white p-3 rounded-lg border shadow-sm text-center">
                      <div className="text-2xl font-bold text-green-600">{testSummary.passed}</div>
                      <div className="text-xs text-gray-500">통과</div>
                    </div>
                    <div className="bg-white p-3 rounded-lg border shadow-sm text-center">
                      <div className="text-2xl font-bold text-red-600">{testSummary.failed}</div>
                      <div className="text-xs text-gray-500">실패</div>
                    </div>
                    <div className="bg-white p-3 rounded-lg border shadow-sm text-center">
                      <div className="text-2xl font-bold text-purple-600">{testSummary.passRate}%</div>
                      <div className="text-xs text-gray-500">통과율</div>
                    </div>
                    <div className="bg-white p-3 rounded-lg border shadow-sm text-center">
                      <div className="text-2xl font-bold text-orange-600">{testSummary.totalDuration}</div>
                      <div className="text-xs text-gray-500">총 소요시간</div>
                    </div>
                  </div>
                  {/* 진행률 바 */}
                  <div className="mt-3">
                    <div className="flex justify-between text-xs mb-1">
                      <span>테스트 진행률</span>
                      <span>{testSummary.passRate}% 통과</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-3">
                      <div
                        className="bg-gradient-to-r from-green-500 to-green-600 h-3 rounded-full transition-all duration-500"
                        style={{ width: `${testSummary.passRate}%` }}
                      />
                    </div>
                  </div>
                </div>
              )}

              {/* 개별 시나리오 결과 목록 */}
              <div className="bg-white p-3 rounded-lg border">
                <h4 className="font-medium text-sm mb-2 flex items-center gap-2">
                  📋 시나리오별 테스트 결과
                  <span className="text-xs text-gray-500">
                    ({testResults.filter(r => r.passed).length} / {testResults.length} 완료)
                  </span>
                </h4>
                <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-2 max-h-48 overflow-y-auto">
                  {testResults.map((result, idx) => (
                    <div key={idx} className={`p-2 rounded-lg text-xs transition-all ${result.passed === true ? 'bg-green-100 text-green-800 border border-green-200' :
                        result.passed === false ? 'bg-red-100 text-red-800 border border-red-200' :
                          'bg-yellow-100 text-yellow-800 border border-yellow-200 animate-pulse'
                      }`}>
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-base">{result.icon}</span>
                        {result.passed === true ? <CheckCircle className="w-4 h-4 text-green-600" /> :
                          result.passed === false ? <XCircle className="w-4 h-4 text-red-600" /> :
                            <RefreshCw className="w-4 h-4 animate-spin text-yellow-600" />}
                      </div>
                      <div className="font-medium truncate">{result.scenario}</div>
                      <div className="flex justify-between mt-1">
                        <span className="text-[10px] text-gray-500">{result.startTime}</span>
                        {result.duration && <span className="text-[10px] font-mono">{result.duration}</span>}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* 카테고리별 테스트 결과 분류 */}
              {testSummary && (
                <div className="bg-white p-3 rounded-lg border">
                  <h4 className="font-medium text-sm mb-2">📊 카테고리별 테스트 현황</h4>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                    {/* 업무 프로세스 */}
                    <div className="p-2 bg-blue-50 rounded-lg">
                      <div className="text-xs font-medium text-blue-700 mb-1">📦 업무 프로세스</div>
                      <div className="space-y-1">
                        {['normal', 'quote-cancel', 'quote-expire', 'rush-order', 'size-change'].map(id => {
                          const result = allTestResults[id];
                          return result ? (
                            <div key={id} className="flex justify-between text-xs">
                              <span className="truncate">{result.label}</span>
                              <span className={result.passed ? 'text-green-600' : 'text-red-600'}>
                                {result.passed ? '✓' : '✗'}
                              </span>
                            </div>
                          ) : null;
                        })}
                      </div>
                    </div>
                    {/* 품질/검사 */}
                    <div className="p-2 bg-yellow-50 rounded-lg">
                      <div className="text-xs font-medium text-yellow-700 mb-1">🔍 품질/검사</div>
                      <div className="space-y-1">
                        {['quality-fail', 'quality-conditional', 'multi-inspection'].map(id => {
                          const result = allTestResults[id];
                          return result ? (
                            <div key={id} className="flex justify-between text-xs">
                              <span className="truncate">{result.label}</span>
                              <span className={result.passed ? 'text-green-600' : 'text-red-600'}>
                                {result.passed ? '✓' : '✗'}
                              </span>
                            </div>
                          ) : null;
                        })}
                      </div>
                    </div>
                    {/* 기준정보 */}
                    <div className="p-2 bg-purple-50 rounded-lg">
                      <div className="text-xs font-medium text-purple-700 mb-1">⚙️ 기준정보</div>
                      <div className="space-y-1">
                        {['new-item', 'numbering-test', 'code-reference'].map(id => {
                          const result = allTestResults[id];
                          return result ? (
                            <div key={id} className="flex justify-between text-xs">
                              <span className="truncate">{result.label}</span>
                              <span className={result.passed ? 'text-green-600' : 'text-red-600'}>
                                {result.passed ? '✓' : '✗'}
                              </span>
                            </div>
                          ) : null;
                        })}
                      </div>
                    </div>
                    {/* 회계관리 */}
                    <div className="p-2 bg-green-50 rounded-lg">
                      <div className="text-xs font-medium text-green-700 mb-1">💰 회계관리</div>
                      <div className="space-y-1">
                        {['payment-delay', 'partial-shipment', 'accounting-sales', 'accounting-purchase', 'accounting-cashbook', 'accounting-collection', 'accounting-cost'].map(id => {
                          const result = allTestResults[id];
                          return result ? (
                            <div key={id} className="flex justify-between text-xs">
                              <span className="truncate">{result.label}</span>
                              <span className={result.passed ? 'text-green-600' : 'text-red-600'}>
                                {result.passed ? '✓' : '✗'}
                              </span>
                            </div>
                          ) : null;
                        })}
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* 단계 진행 표시 */}
          <div className="flex flex-wrap items-center gap-1 text-xs">
            {steps.map((step, idx) => (
              <React.Fragment key={step.id}>
                <div className={`flex items-center gap-1 px-2 py-1.5 rounded-lg transition-all ${idx < currentStep ? `bg-${step.color}-100 text-${step.color}-800` :
                    idx === currentStep ? `bg-${step.color}-500 text-white shadow-lg` :
                      'bg-gray-100 text-gray-400'
                  }`}>
                  <step.icon className="w-3.5 h-3.5" />
                  <span className="font-medium">{step.label}</span>
                  {idx < currentStep && <CheckCircle className="w-3 h-3 ml-1" />}
                </div>
                {idx < steps.length - 1 && (
                  <ChevronRight className={`w-4 h-4 ${idx < currentStep ? 'text-green-500' : 'text-gray-300'}`} />
                )}
              </React.Fragment>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-1 gap-6">
          {/* 왼쪽: 입력/현재 단계 정보 */}
          <div className="space-y-4">
            {/* Step 0: 견적 입력 */}
            {currentStep === 0 && (
              <div className="bg-white border rounded-lg p-4 shadow-sm">
                <h4 className="font-semibold mb-4 flex items-center gap-2 text-blue-800">
                  <Calculator className="w-5 h-5" />
                  Step 1: 견적 입력
                </h4>

                {/* 거래처/현장 선택 */}
                <div className="grid grid-cols-2 gap-3 mb-4">
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">거래처</label>
                    <select
                      value={workflowData.inputs.customerId}
                      onChange={(e) => handleInputChange('customerId', parseInt(e.target.value))}
                      className="w-full px-3 py-2 border rounded-lg text-sm"
                    >
                      {integratedCustomerMaster.map(c => (
                        <option key={c.id} value={c.id}>{c.name} ({c.creditGrade}등급)</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">현장</label>
                    <select
                      value={workflowData.inputs.siteId}
                      onChange={(e) => handleInputChange('siteId', parseInt(e.target.value))}
                      className="w-full px-3 py-2 border rounded-lg text-sm"
                    >
                      {customerSites.map(s => (
                        <option key={s.id} value={s.id}>{s.name}</option>
                      ))}
                    </select>
                  </div>
                </div>

                {/* 제품 유형 */}
                <div className="mb-4">
                  <label className="block text-xs font-medium text-gray-600 mb-1">제품 유형</label>
                  <div className="grid grid-cols-2 gap-2">
                    {['스크린', '철재'].map(type => (
                      <button
                        key={type}
                        onClick={() => handleInputChange('PC', type)}
                        className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${workflowData.inputs.PC === type
                            ? 'bg-blue-500 text-white shadow-md'
                            : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                          }`}
                      >
                        {type}
                      </button>
                    ))}
                  </div>
                </div>

                {/* 오픈사이즈 */}
                <div className="p-3 bg-blue-50 rounded-lg mb-4">
                  <label className="block text-xs font-medium text-blue-700 mb-2">오픈사이즈 (mm)</label>
                  <div className="grid grid-cols-3 gap-3">
                    <div>
                      <span className="text-xs text-blue-600">가로 (W0)</span>
                      <input
                        type="number"
                        value={workflowData.inputs.W0}
                        onChange={(e) => handleInputChange('W0', parseInt(e.target.value))}
                        className="w-full px-3 py-2 border border-blue-200 rounded-lg text-sm font-mono bg-white"
                      />
                    </div>
                    <div>
                      <span className="text-xs text-blue-600">세로 (H0)</span>
                      <input
                        type="number"
                        value={workflowData.inputs.H0}
                        onChange={(e) => handleInputChange('H0', parseInt(e.target.value))}
                        className="w-full px-3 py-2 border border-blue-200 rounded-lg text-sm font-mono bg-white"
                      />
                    </div>
                    <div>
                      <span className="text-xs text-blue-600">수량</span>
                      <input
                        type="number"
                        value={workflowData.inputs.QTY}
                        onChange={(e) => handleInputChange('QTY', Math.max(1, parseInt(e.target.value)))}
                        min={1}
                        className="w-full px-3 py-2 border border-blue-200 rounded-lg text-sm font-mono bg-white"
                      />
                    </div>
                  </div>
                </div>

                {/* 옵션 설정 */}
                <div className="grid grid-cols-2 gap-3 mb-4">
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">가이드레일 유형</label>
                    <select
                      value={workflowData.inputs.GT}
                      onChange={(e) => handleInputChange('GT', e.target.value)}
                      className="w-full px-3 py-2 border rounded-lg text-sm"
                    >
                      <option value="벽면형">벽면형</option>
                      <option value="코너형">코너형</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">제어기 유형</label>
                    <select
                      value={workflowData.inputs.CT}
                      onChange={(e) => handleInputChange('CT', e.target.value)}
                      className="w-full px-3 py-2 border rounded-lg text-sm"
                    >
                      <option value="매립">매립형</option>
                      <option value="노출">노출형</option>
                    </select>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">층수</label>
                    <input
                      type="text"
                      value={workflowData.inputs.floor}
                      onChange={(e) => handleInputChange('floor', e.target.value)}
                      placeholder="예: 1층"
                      className="w-full px-3 py-2 border rounded-lg text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">부호</label>
                    <input
                      type="text"
                      value={workflowData.inputs.symbol}
                      onChange={(e) => handleInputChange('symbol', e.target.value)}
                      placeholder="예: A"
                      className="w-full px-3 py-2 border rounded-lg text-sm"
                    />
                  </div>
                </div>
              </div>
            )}

            {/* Step 1: 자동 산출 결과 */}
            {currentStep >= 1 && workflowData.calculatedResult && (
              <div className="bg-white border rounded-lg p-4 shadow-sm">
                <h4 className="font-semibold mb-4 flex items-center gap-2 text-purple-800">
                  <Zap className="w-5 h-5" />
                  자동 산출 결과
                </h4>

                {/* 요약 정보 */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-2 mb-4 text-sm">
                  <div className="bg-purple-50 p-2 rounded">
                    <div className="text-xs text-purple-600">제작사이즈</div>
                    <div className="font-mono font-medium">{workflowData.calculatedResult.summary.productionSize}</div>
                  </div>
                  <div className="bg-purple-50 p-2 rounded">
                    <div className="text-xs text-purple-600">면적</div>
                    <div className="font-mono font-medium">{workflowData.calculatedResult.summary.area} ㎡</div>
                  </div>
                  <div className="bg-purple-50 p-2 rounded">
                    <div className="text-xs text-purple-600">중량</div>
                    <div className="font-mono font-medium">{workflowData.calculatedResult.summary.weight} kg</div>
                  </div>
                  <div className="bg-purple-50 p-2 rounded">
                    <div className="text-xs text-purple-600">모터</div>
                    <div className="font-mono font-medium">{workflowData.calculatedResult.summary.motorCapacity}</div>
                  </div>
                </div>

                {/* 품목 리스트 */}
                <div className="max-h-48 overflow-y-auto border rounded">
                  <table className="w-full text-xs">
                    <thead className="bg-gray-50 sticky top-0">
                      <tr>
                        <th className="px-2 py-1 text-left">품목</th>
                        <th className="px-2 py-1 text-left">규격</th>
                        <th className="px-2 py-1 text-right">수량</th>
                        <th className="px-2 py-1 text-right">금액</th>
                      </tr>
                    </thead>
                    <tbody>
                      {workflowData.calculatedResult.items.map(item => (
                        <tr key={item.id} className="border-t">
                          <td className="px-2 py-1">{item.itemName}</td>
                          <td className="px-2 py-1 font-mono text-gray-500">{item.spec}</td>
                          <td className="px-2 py-1 text-right">{item.qty}</td>
                          <td className="px-2 py-1 text-right font-mono">{item.amount.toLocaleString()}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* 합계 */}
                <div className="mt-3 p-3 bg-gradient-to-r from-purple-500 to-purple-600 rounded-lg text-white">
                  <div className="flex justify-between items-center">
                    <span>총 견적금액 (VAT 포함)</span>
                    <span className="text-xl font-bold">{workflowData.calculatedResult.grandTotal.toLocaleString()}원</span>
                  </div>
                </div>
              </div>
            )}

            {/* 다음 단계 실행 버튼 */}
            {currentStep < 8 && (
              <button
                onClick={executeNextStep}
                disabled={isProcessing}
                className={`w-full flex items-center justify-center gap-2 px-4 py-3 rounded-lg font-medium transition-all ${isProcessing
                    ? 'bg-gray-300 cursor-not-allowed'
                    : 'bg-gradient-to-r from-blue-500 to-purple-500 text-white hover:from-blue-600 hover:to-purple-600 shadow-lg hover:shadow-xl'
                  }`}
              >
                {isProcessing ? (
                  <>
                    <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    처리 중...
                  </>
                ) : (
                  <>
                    <Play className="w-5 h-5" />
                    {currentStep === 0 ? '견적 산출 실행' : `다음 단계: ${steps[currentStep + 1]?.label}`}
                  </>
                )}
              </button>
            )}

            {currentStep === 8 && (
              <div className="p-4 bg-emerald-50 border border-emerald-200 rounded-lg text-center">
                <CheckCircle className="w-12 h-12 text-emerald-500 mx-auto mb-2" />
                <h4 className="font-bold text-emerald-800 text-lg">전체 프로세스 완료!</h4>
                <p className="text-sm text-emerald-600">견적 → 수주 → 생산 → 품질 → 출하 → 회계 전 과정이 완료되었습니다.</p>
                <button
                  onClick={resetWorkflow}
                  className="mt-3 px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600"
                >
                  새로운 테스트 시작
                </button>
              </div>
            )}
          </div>

          {/* 오른쪽: 생성된 데이터 표시 */}
          <div className="space-y-4">
            {/* 견적 정보 */}
            {workflowData.quote && (
              <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                <h4 className="font-semibold text-green-800 mb-2 flex items-center gap-2">
                  <FileText className="w-4 h-4" />
                  견적 정보
                </h4>
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div><span className="text-green-600">번호:</span> {workflowData.quote.quoteNo}</div>
                  <div><span className="text-green-600">상태:</span> <span className={`px-2 py-0.5 rounded ${getStatusColor(workflowData.quote.status)}`}>{workflowData.quote.status}</span></div>
                  <div><span className="text-green-600">거래처:</span> {workflowData.quote.customerName}</div>
                  <div><span className="text-green-600">현장:</span> {workflowData.quote.siteName}</div>
                  <div className="col-span-2"><span className="text-green-600">금액:</span> <span className="font-bold">{formatCurrency(workflowData.quote.finalAmount)}</span></div>
                </div>
              </div>
            )}

            {/* 수주 정보 */}
            {workflowData.order && (
              <div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
                <h4 className="font-semibold text-orange-800 mb-2 flex items-center gap-2">
                  <Package className="w-4 h-4" />
                  수주 정보
                </h4>
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div><span className="text-orange-600">수주번호:</span> {workflowData.order.orderNo}</div>
                  <div><span className="text-orange-600">상태:</span> <span className={`px-2 py-0.5 rounded ${getStatusColor(workflowData.order.status)}`}>{workflowData.order.status}</span></div>
                  <div><span className="text-orange-600">납기일:</span> {workflowData.order.dueDate}</div>
                  <div><span className="text-orange-600">금액:</span> <span className="font-bold">{formatCurrency(workflowData.order.totalAmount)}</span></div>
                </div>
              </div>
            )}

            {/* 생산 정보 */}
            {workflowData.workOrders.length > 0 && (
              <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                <h4 className="font-semibold text-yellow-800 mb-2 flex items-center gap-2">
                  <Factory className="w-4 h-4" />
                  생산 지시 ({workflowData.workOrders.length}건)
                </h4>
                <div className="space-y-1 text-sm">
                  {workflowData.workOrders.map(wo => (
                    <div key={wo.id} className="flex items-center justify-between bg-white p-2 rounded">
                      <span className="font-mono text-xs">{wo.workOrderNo}</span>
                      <span>{wo.processName}</span>
                      <span className={`px-2 py-0.5 rounded text-xs ${wo.status === '완료' ? 'bg-green-100 text-green-800' :
                          wo.status === '진행중' ? 'bg-yellow-100 text-yellow-800' :
                            'bg-gray-100'
                        }`}>{wo.status}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* 품질 검사 정보 */}
            {workflowData.qualityInspections.length > 0 && (
              <div className="bg-indigo-50 border border-indigo-200 rounded-lg p-4">
                <h4 className="font-semibold text-indigo-800 mb-2 flex items-center gap-2">
                  <ShieldCheck className="w-4 h-4" />
                  품질 검사 ({workflowData.qualityInspections.length}건)
                </h4>
                <div className="space-y-1 text-sm">
                  {workflowData.qualityInspections.slice(0, 3).map(qi => (
                    <div key={qi.id} className="flex items-center justify-between bg-white p-2 rounded">
                      <span className="font-mono text-xs">{qi.inspectionNo}</span>
                      <span>{qi.inspectionType}</span>
                      <span className={`px-2 py-0.5 rounded text-xs ${getStatusColor(qi.result)}`}>{qi.result}</span>
                    </div>
                  ))}
                  {workflowData.qualityInspections.length > 3 && (
                    <div className="text-center text-gray-500 text-xs">... 외 {workflowData.qualityInspections.length - 3}건</div>
                  )}
                </div>
              </div>
            )}

            {/* 출하 정보 */}
            {workflowData.shipment && (
              <div className="bg-teal-50 border border-teal-200 rounded-lg p-4">
                <h4 className="font-semibold text-teal-800 mb-2 flex items-center gap-2">
                  <Truck className="w-4 h-4" />
                  출하 정보
                </h4>
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div><span className="text-teal-600">출하번호:</span> {workflowData.shipment.shipmentNo}</div>
                  <div><span className="text-teal-600">상태:</span> <span className={`px-2 py-0.5 rounded ${getStatusColor(workflowData.shipment.status)}`}>{workflowData.shipment.status}</span></div>
                  <div><span className="text-teal-600">출하일:</span> {workflowData.shipment.shipmentDate}</div>
                  <div><span className="text-teal-600">운송:</span> {workflowData.shipment.carrier}</div>
                </div>
              </div>
            )}

            {/* 회계 정보 */}
            {workflowData.sales && (
              <div className="bg-pink-50 border border-pink-200 rounded-lg p-4">
                <h4 className="font-semibold text-pink-800 mb-2 flex items-center gap-2">
                  <DollarSign className="w-4 h-4" />
                  회계 정보
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="grid grid-cols-2 gap-2">
                    <div><span className="text-pink-600">매출번호:</span> {workflowData.sales.salesNo}</div>
                    <div><span className="text-pink-600">상태:</span> <span className={`px-2 py-0.5 rounded ${workflowData.sales.paymentStatus === '수금완료' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                      }`}>{workflowData.sales.paymentStatus}</span></div>
                    <div><span className="text-pink-600">공급가:</span> {formatCurrency(workflowData.sales.supplyAmount)}</div>
                    <div><span className="text-pink-600">VAT:</span> {formatCurrency(workflowData.sales.vatAmount)}</div>
                  </div>
                  <div className="pt-2 border-t border-pink-200">
                    <span className="text-pink-600">합계:</span> <span className="font-bold text-lg">{formatCurrency(workflowData.sales.totalAmount)}</span>
                  </div>

                  {workflowData.collection && (
                    <div className="mt-2 p-2 bg-emerald-100 rounded">
                      <div className="text-emerald-800 font-medium">💰 수금 완료</div>
                      <div className="text-xs text-emerald-600">
                        {workflowData.collection.collectionNo} | {workflowData.collection.paymentMethod} | {workflowData.collection.collectionDate}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* 신규 품목 등록 결과 */}
            {workflowData.newItem && (
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h4 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                  📋 신규 품목 등록
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="grid grid-cols-2 gap-2">
                    <div><span className="text-blue-600">품목코드:</span> {workflowData.newItem.itemCode}</div>
                    <div><span className="text-blue-600">품목명:</span> {workflowData.newItem.itemName}</div>
                    <div><span className="text-blue-600">분류:</span> {workflowData.newItem.category}</div>
                    <div><span className="text-blue-600">유형:</span> {workflowData.newItem.itemType}</div>
                  </div>
                  <div className="pt-2 border-t border-blue-200 text-xs text-blue-600">
                    📍 메뉴 경로: {workflowData.newItem.menuPath}
                  </div>
                </div>
              </div>
            )}

            {/* 검사유형 전환 결과 */}
            {workflowData.inspectionFlow && (
              <div className="bg-purple-50 border border-purple-200 rounded-lg p-4">
                <h4 className="font-semibold text-purple-800 mb-2 flex items-center gap-2">
                  🔍 검사유형 통합 테스트
                </h4>
                <div className="space-y-2 text-sm">
                  {['iqc', 'pqc', 'fqc'].map(key => {
                    const insp = workflowData.inspectionFlow[key];
                    return (
                      <div key={key} className="flex items-center justify-between bg-white p-2 rounded">
                        <span className="font-medium">{insp.typeCode}</span>
                        <span>{insp.inspectionType}</span>
                        <span className={`px-2 py-0.5 rounded text-xs ${insp.result === '합격' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                          }`}>{insp.result}</span>
                      </div>
                    );
                  })}
                  <div className="pt-2 border-t border-purple-200 text-xs text-purple-600">
                    📍 메뉴 경로: {workflowData.inspectionFlow.menuPath}
                  </div>
                </div>
              </div>
            )}

            {/* 채번 테스트 결과 */}
            {workflowData.numberingResults && (
              <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
                <h4 className="font-semibold text-amber-800 mb-2 flex items-center gap-2">
                  🔢 채번관리 테스트
                </h4>
                <div className="space-y-2 text-sm max-h-48 overflow-y-auto">
                  {workflowData.numberingResults.rules.map((rule, idx) => (
                    <div key={idx} className="bg-white p-2 rounded border border-amber-100">
                      <div className="flex justify-between items-center">
                        <span className="font-medium text-amber-800">{rule.ruleName}</span>
                        <span className="text-xs text-gray-500">{rule.pattern}</span>
                      </div>
                      <div className="font-mono text-xs text-amber-600 mt-1">{rule.example}</div>
                    </div>
                  ))}
                  <div className="pt-2 border-t border-amber-200 text-xs text-amber-600">
                    📍 메뉴 경로: {workflowData.numberingResults.menuPath}
                  </div>
                </div>
              </div>
            )}

            {/* 공통코드 참조 결과 */}
            {workflowData.codeReferences && (
              <div className="bg-cyan-50 border border-cyan-200 rounded-lg p-4">
                <h4 className="font-semibold text-cyan-800 mb-2 flex items-center gap-2">
                  📑 공통코드관리 테스트
                </h4>
                <div className="space-y-2 text-sm max-h-48 overflow-y-auto">
                  {workflowData.codeReferences.codeGroups.map((group, idx) => (
                    <div key={idx} className="bg-white p-2 rounded border border-cyan-100">
                      <div className="flex justify-between items-center mb-1">
                        <span className="font-medium text-cyan-800">{group.groupName}</span>
                        <span className="text-xs text-gray-500">{group.groupCode}</span>
                      </div>
                      <div className="flex flex-wrap gap-1">
                        {group.codes.map((code, cidx) => (
                          <span key={cidx} className="px-1.5 py-0.5 bg-cyan-100 text-cyan-700 rounded text-xs">
                            {code.code}: {code.name}
                          </span>
                        ))}
                      </div>
                      <div className="text-xs text-gray-500 mt-1">
                        사용: {group.usedIn.join(', ')}
                      </div>
                    </div>
                  ))}
                  <div className="pt-2 border-t border-cyan-200 text-xs text-cyan-600">
                    📍 메뉴 경로: {workflowData.codeReferences.menuPath}
                  </div>
                </div>
              </div>
            )}

            {/* 회계관리 - 매출관리 결과 */}
            {workflowData.accountingSales && (
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h4 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                  📊 매출관리 테스트
                </h4>
                <div className="space-y-2 text-sm">
                  {workflowData.accountingSales.testCases.map((tc, idx) => (
                    <div key={idx} className="flex justify-between items-center bg-white p-2 rounded border border-blue-100">
                      <span className="text-gray-700">{tc.action}</span>
                      <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">{tc.result}</span>
                    </div>
                  ))}
                  <div className="pt-2 border-t border-blue-200 flex justify-between text-xs">
                    <span className="text-blue-600">📍 {workflowData.accountingSales.menuPath}</span>
                    <span className="text-green-600">✓ {workflowData.accountingSales.summary.success}/{workflowData.accountingSales.summary.total} 성공</span>
                  </div>
                </div>
              </div>
            )}

            {/* 회계관리 - 매입관리 결과 */}
            {workflowData.accountingPurchase && (
              <div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
                <h4 className="font-semibold text-orange-800 mb-2 flex items-center gap-2">
                  🛒 매입관리 테스트
                </h4>
                <div className="space-y-2 text-sm">
                  {workflowData.accountingPurchase.testCases.map((tc, idx) => (
                    <div key={idx} className="flex justify-between items-center bg-white p-2 rounded border border-orange-100">
                      <span className="text-gray-700">{tc.action}</span>
                      <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">{tc.result}</span>
                    </div>
                  ))}
                  <div className="pt-2 border-t border-orange-200 flex justify-between text-xs">
                    <span className="text-orange-600">📍 {workflowData.accountingPurchase.menuPath}</span>
                    <span className="text-green-600">✓ {workflowData.accountingPurchase.summary.success}/{workflowData.accountingPurchase.summary.total} 성공</span>
                  </div>
                </div>
              </div>
            )}

            {/* 회계관리 - 금전출납부 결과 */}
            {workflowData.accountingCashbook && (
              <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                <h4 className="font-semibold text-green-800 mb-2 flex items-center gap-2">
                  💵 금전출납부 테스트
                </h4>
                <div className="space-y-2 text-sm">
                  {workflowData.accountingCashbook.testCases.map((tc, idx) => (
                    <div key={idx} className="flex justify-between items-center bg-white p-2 rounded border border-green-100">
                      <span className="text-gray-700">{tc.action}</span>
                      <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">{tc.result}</span>
                    </div>
                  ))}
                  <div className="pt-2 border-t border-green-200 flex justify-between text-xs">
                    <span className="text-green-600">📍 {workflowData.accountingCashbook.menuPath}</span>
                    <span className="text-green-600">✓ {workflowData.accountingCashbook.summary.success}/{workflowData.accountingCashbook.summary.total} 성공</span>
                  </div>
                </div>
              </div>
            )}

            {/* 회계관리 - 수금관리 결과 */}
            {workflowData.accountingCollection && (
              <div className="bg-purple-50 border border-purple-200 rounded-lg p-4">
                <h4 className="font-semibold text-purple-800 mb-2 flex items-center gap-2">
                  💳 수금관리 테스트
                </h4>
                <div className="space-y-2 text-sm">
                  {workflowData.accountingCollection.testCases.map((tc, idx) => (
                    <div key={idx} className="flex justify-between items-center bg-white p-2 rounded border border-purple-100">
                      <span className="text-gray-700">{tc.action}</span>
                      <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">{tc.result}</span>
                    </div>
                  ))}
                  <div className="pt-2 border-t border-purple-200 flex justify-between text-xs">
                    <span className="text-purple-600">📍 {workflowData.accountingCollection.menuPath}</span>
                    <span className="text-green-600">✓ {workflowData.accountingCollection.summary.success}/{workflowData.accountingCollection.summary.total} 성공</span>
                  </div>
                </div>
              </div>
            )}

            {/* 회계관리 - 원가관리 결과 */}
            {workflowData.accountingCost && (
              <div className="bg-pink-50 border border-pink-200 rounded-lg p-4">
                <h4 className="font-semibold text-pink-800 mb-2 flex items-center gap-2">
                  🧮 원가관리 테스트
                </h4>
                <div className="space-y-2 text-sm">
                  {workflowData.accountingCost.testCases.map((tc, idx) => (
                    <div key={idx} className="flex justify-between items-center bg-white p-2 rounded border border-pink-100">
                      <span className="text-gray-700">{tc.action}</span>
                      <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">{tc.result}</span>
                    </div>
                  ))}
                  <div className="pt-2 border-t border-pink-200 flex justify-between text-xs">
                    <span className="text-pink-600">📍 {workflowData.accountingCost.menuPath}</span>
                    <span className="text-green-600">✓ {workflowData.accountingCost.summary.success}/{workflowData.accountingCost.summary.total} 성공</span>
                  </div>
                </div>
              </div>
            )}

            {/* ═══════════════════════════════════════════════════════════════════════════ */}
            {/* 문서 출력 테스트 결과 */}
            {/* ═══════════════════════════════════════════════════════════════════════════ */}
            {workflowData.documentTest && (
              <div className="bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-300 rounded-lg p-4">
                <h4 className="font-bold text-blue-800 mb-3 flex items-center gap-2 text-lg">
                  📄 {workflowData.documentTest.docType} 출력 테스트
                </h4>

                {/* 문서 정보 */}
                <div className="bg-white p-3 rounded-lg border border-blue-200 mb-3">
                  <h5 className="font-semibold text-blue-700 mb-2 text-sm">📋 문서 정보</h5>
                  <div className="grid grid-cols-2 gap-2 text-sm">
                    <div><span className="text-blue-600">문서번호:</span> <span className="font-mono">{workflowData.documentTest.document?.docNo}</span></div>
                    <div><span className="text-blue-600">상태:</span> <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">{workflowData.documentTest.document?.status}</span></div>
                    {workflowData.documentTest.document?.customer && (
                      <div><span className="text-blue-600">거래처:</span> {workflowData.documentTest.document.customer}</div>
                    )}
                    {workflowData.documentTest.document?.amount && (
                      <div><span className="text-blue-600">금액:</span> <span className="font-bold">{workflowData.documentTest.document.amount.toLocaleString()}원</span></div>
                    )}
                  </div>
                </div>

                {/* 결재선 */}
                {workflowData.documentTest.approvalLine && (
                  <div className="bg-white p-3 rounded-lg border border-blue-200 mb-3">
                    <h5 className="font-semibold text-blue-700 mb-2 text-sm">✍️ 결재선</h5>
                    <div className="flex items-center gap-2 overflow-x-auto pb-2">
                      {workflowData.documentTest.approvalLine.map((approver, idx) => (
                        <React.Fragment key={idx}>
                          <div className="flex-shrink-0 bg-blue-100 p-2 rounded-lg text-center min-w-[80px]">
                            <div className="text-xs text-blue-600">{approver.role}</div>
                            <div className="font-medium text-sm">{approver.name}</div>
                            <div className="text-xs text-gray-500">{approver.dept}</div>
                            <div className="text-green-600 font-bold">{approver.signature}</div>
                          </div>
                          {idx < workflowData.documentTest.approvalLine.length - 1 && (
                            <ChevronRight className="w-5 h-5 text-blue-400 flex-shrink-0" />
                          )}
                        </React.Fragment>
                      ))}
                    </div>
                  </div>
                )}

                {/* 테스트 케이스 */}
                <div className="space-y-1">
                  {workflowData.documentTest.testCases?.map((tc, idx) => (
                    <div key={idx} className="flex justify-between items-center bg-white p-2 rounded border border-blue-100">
                      <span className="text-gray-700 text-sm">{tc.action}</span>
                      <div className="flex items-center gap-2">
                        {tc.approver && <span className="text-xs text-gray-500">{tc.approver}</span>}
                        <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">{tc.status}</span>
                      </div>
                    </div>
                  ))}
                </div>

                {/* 요약 */}
                <div className="pt-3 mt-3 border-t border-blue-200 flex justify-between text-xs">
                  <span className="text-blue-600">📍 {workflowData.documentTest.menuPath}</span>
                  <span className="text-green-600 font-medium">✓ {workflowData.documentTest.summary?.success}/{workflowData.documentTest.summary?.total} 성공</span>
                </div>
              </div>
            )}

            {/* ═══════════════════════════════════════════════════════════════════════════ */}
            {/* 결재 프로세스 테스트 결과 */}
            {/* ═══════════════════════════════════════════════════════════════════════════ */}
            {workflowData.approvalTest && (
              <div className="bg-gradient-to-br from-purple-50 to-pink-50 border-2 border-purple-300 rounded-lg p-4">
                <h4 className="font-bold text-purple-800 mb-3 flex items-center gap-2 text-lg">
                  ✍️ {workflowData.approvalTest.testType} 테스트
                </h4>
                <p className="text-sm text-purple-600 mb-3">{workflowData.approvalTest.description}</p>

                {/* 결재 흐름 정보 */}
                {workflowData.approvalTest.approvalFlow && (
                  <div className="bg-white p-3 rounded-lg border border-purple-200 mb-3">
                    <h5 className="font-semibold text-purple-700 mb-2 text-sm">📋 결재 흐름</h5>
                    <div className="grid grid-cols-2 gap-2 text-sm mb-3">
                      <div><span className="text-purple-600">문서유형:</span> {workflowData.approvalTest.approvalFlow.docType}</div>
                      <div><span className="text-purple-600">문서번호:</span> <span className="font-mono">{workflowData.approvalTest.approvalFlow.docNo}</span></div>
                      {workflowData.approvalTest.approvalFlow.totalDuration && (
                        <div><span className="text-purple-600">소요시간:</span> {workflowData.approvalTest.approvalFlow.totalDuration}</div>
                      )}
                      {workflowData.approvalTest.approvalFlow.version && (
                        <div><span className="text-purple-600">버전:</span> {workflowData.approvalTest.approvalFlow.version}</div>
                      )}
                    </div>

                    {/* 결재 단계 표시 */}
                    <div className="flex items-center gap-2 overflow-x-auto pb-2">
                      {workflowData.approvalTest.approvalFlow.steps?.map((step, idx) => (
                        <React.Fragment key={idx}>
                          <div className={`flex-shrink-0 p-2 rounded-lg text-center min-w-[90px] ${step.status === '완료' ? 'bg-green-100' : 'bg-gray-100'
                            }`}>
                            <div className="text-xs text-gray-600">{step.role}</div>
                            <div className="font-medium text-sm">{step.name}</div>
                            {step.dept && <div className="text-xs text-gray-500">{step.dept}</div>}
                            {step.note && <div className="text-xs text-purple-600">{step.note}</div>}
                            {step.action && <div className="text-xs text-orange-600">{step.action}</div>}
                            <div className="text-green-600 font-bold text-xs">✓ {step.status}</div>
                          </div>
                          {idx < workflowData.approvalTest.approvalFlow.steps.length - 1 && (
                            <ChevronRight className="w-5 h-5 text-purple-400 flex-shrink-0" />
                          )}
                        </React.Fragment>
                      ))}
                    </div>
                  </div>
                )}

                {/* 대결 정보 */}
                {workflowData.approvalTest.approvalFlow?.delegateInfo && (
                  <div className="bg-yellow-50 p-3 rounded-lg border border-yellow-200 mb-3">
                    <h5 className="font-semibold text-yellow-700 mb-2 text-sm">👥 대결 정보</h5>
                    <div className="grid grid-cols-2 gap-2 text-sm">
                      <div><span className="text-yellow-600">원결재자:</span> {workflowData.approvalTest.approvalFlow.delegateInfo.originalApprover}</div>
                      <div><span className="text-yellow-600">대결자:</span> {workflowData.approvalTest.approvalFlow.delegateInfo.delegate}</div>
                      <div><span className="text-yellow-600">사유:</span> {workflowData.approvalTest.approvalFlow.delegateInfo.delegateReason}</div>
                      <div><span className="text-yellow-600">기간:</span> {workflowData.approvalTest.approvalFlow.delegateInfo.delegatePeriod}</div>
                    </div>
                  </div>
                )}

                {/* 긴급 결재 정보 */}
                {workflowData.approvalTest.approvalFlow?.urgentInfo && (
                  <div className="bg-red-50 p-3 rounded-lg border border-red-200 mb-3">
                    <h5 className="font-semibold text-red-700 mb-2 text-sm">⚡ 긴급 결재 정보</h5>
                    <div className="grid grid-cols-2 gap-2 text-sm">
                      <div><span className="text-red-600">긴급등급:</span> <span className="px-2 py-0.5 bg-red-200 text-red-800 rounded">{workflowData.approvalTest.approvalFlow.urgentInfo.urgentLevel}</span></div>
                      <div><span className="text-red-600">사유:</span> {workflowData.approvalTest.approvalFlow.urgentInfo.urgentReason}</div>
                      <div><span className="text-red-600">원결재선:</span> {workflowData.approvalTest.approvalFlow.urgentInfo.originalApprovalLine?.join(' → ')}</div>
                      <div><span className="text-red-600">단축결재선:</span> {workflowData.approvalTest.approvalFlow.urgentInfo.reducedApprovalLine?.join(' → ')}</div>
                      <div><span className="text-red-600">처리시간:</span> <span className="font-bold text-green-600">{workflowData.approvalTest.approvalFlow.totalProcessTime}</span></div>
                      <div><span className="text-red-600">절감시간:</span> <span className="font-bold text-blue-600">{workflowData.approvalTest.approvalFlow.timeSaved}</span></div>
                    </div>
                  </div>
                )}

                {/* 반려 이력 */}
                {workflowData.approvalTest.approvalFlow?.rejectionHistory && (
                  <div className="bg-orange-50 p-3 rounded-lg border border-orange-200 mb-3">
                    <h5 className="font-semibold text-orange-700 mb-2 text-sm">↩️ 반려 이력</h5>
                    {workflowData.approvalTest.approvalFlow.rejectionHistory.map((rejection, idx) => (
                      <div key={idx} className="text-sm">
                        <div><span className="text-orange-600">버전:</span> {rejection.version}</div>
                        <div><span className="text-orange-600">반려자:</span> {rejection.rejectedBy}</div>
                        <div><span className="text-orange-600">사유:</span> {rejection.rejectReason}</div>
                        <div><span className="text-orange-600">수정항목:</span> {rejection.modifiedFields?.join(', ')}</div>
                      </div>
                    ))}
                  </div>
                )}

                {/* 알림 내역 */}
                {workflowData.approvalTest.notifications && (
                  <div className="bg-white p-3 rounded-lg border border-purple-200 mb-3">
                    <h5 className="font-semibold text-purple-700 mb-2 text-sm">🔔 알림 내역</h5>
                    <div className="space-y-1">
                      {workflowData.approvalTest.notifications.map((notif, idx) => (
                        <div key={idx} className="flex justify-between items-center text-xs">
                          <span>{notif.type}</span>
                          <span className="text-gray-500">{notif.recipient}</span>
                          <span className="text-gray-400">{notif.sentAt}</span>
                          <span className="text-green-600">{notif.status}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* 테스트 케이스 */}
                <div className="space-y-1">
                  {workflowData.approvalTest.testCases?.map((tc, idx) => (
                    <div key={idx} className="flex justify-between items-center bg-white p-2 rounded border border-purple-100">
                      <span className="text-gray-700 text-sm">{tc.action}</span>
                      <div className="flex items-center gap-2">
                        {tc.actor && <span className="text-xs text-gray-500">{tc.actor}</span>}
                        {tc.reason && <span className="text-xs text-orange-500">{tc.reason}</span>}
                        <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">{tc.status}</span>
                      </div>
                    </div>
                  ))}
                </div>

                {/* 요약 */}
                <div className="pt-3 mt-3 border-t border-purple-200 flex justify-between text-xs">
                  <span className="text-purple-600">📍 {workflowData.approvalTest.menuPath}</span>
                  <span className="text-green-600 font-medium">✓ {workflowData.approvalTest.summary?.success}/{workflowData.approvalTest.summary?.total} 성공</span>
                </div>
              </div>
            )}

            {/* ═══════════════════════════════════════════════════════════════════════════ */}
            {/* 문서 전체흐름 테스트 결과 */}
            {/* ═══════════════════════════════════════════════════════════════════════════ */}
            {workflowData.fullDocumentFlow && (
              <div className="bg-gradient-to-br from-emerald-50 to-teal-50 border-2 border-emerald-300 rounded-lg p-4">
                <h4 className="font-bold text-emerald-800 mb-3 flex items-center gap-2 text-lg">
                  📚 문서 전체흐름 테스트
                </h4>
                <p className="text-sm text-emerald-600 mb-3">{workflowData.fullDocumentFlow.description}</p>

                {/* 단계별 문서 현황 */}
                <div className="space-y-3 mb-4">
                  {workflowData.fullDocumentFlow.testPhases?.map((phase, idx) => (
                    <div key={idx} className="bg-white p-3 rounded-lg border border-emerald-200">
                      <div className="flex justify-between items-center mb-2">
                        <h5 className="font-semibold text-emerald-700">{phase.phase}</h5>
                        <span className="text-xs text-emerald-600">결재 {phase.approvalCount}건 / {phase.totalApprovals}단계</span>
                      </div>
                      <div className="grid grid-cols-2 gap-2">
                        {phase.documents.map((doc, dIdx) => (
                          <div key={dIdx} className="flex justify-between items-center bg-emerald-50 p-2 rounded text-sm">
                            <span>{doc.docType} {doc.count ? `(${doc.count}건)` : ''}</span>
                            <span className={`px-2 py-0.5 rounded text-xs ${doc.status.includes('완료') ? 'bg-green-100 text-green-700' : 'bg-blue-100 text-blue-700'
                              }`}>{doc.status}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>

                {/* 통계 요약 */}
                {workflowData.fullDocumentFlow.testSummary && (
                  <div className="bg-white p-4 rounded-lg border border-emerald-200 mb-3">
                    <h5 className="font-semibold text-emerald-700 mb-3">📊 통합 통계</h5>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                      <div className="text-center p-2 bg-emerald-100 rounded-lg">
                        <div className="text-2xl font-bold text-emerald-700">{workflowData.fullDocumentFlow.testSummary.totalDocuments}</div>
                        <div className="text-xs text-emerald-600">총 문서</div>
                      </div>
                      <div className="text-center p-2 bg-blue-100 rounded-lg">
                        <div className="text-2xl font-bold text-blue-700">{workflowData.fullDocumentFlow.testSummary.totalApprovals}</div>
                        <div className="text-xs text-blue-600">총 결재</div>
                      </div>
                      <div className="text-center p-2 bg-purple-100 rounded-lg">
                        <div className="text-2xl font-bold text-purple-700">{workflowData.fullDocumentFlow.testSummary.totalApprovalTime}</div>
                        <div className="text-xs text-purple-600">총 소요시간</div>
                      </div>
                      <div className="text-center p-2 bg-orange-100 rounded-lg">
                        <div className="text-2xl font-bold text-orange-700">{workflowData.fullDocumentFlow.testSummary.avgApprovalTime}</div>
                        <div className="text-xs text-orange-600">평균 결재시간</div>
                      </div>
                    </div>
                    <div className="mt-3 pt-3 border-t border-emerald-200">
                      <div className="text-sm">
                        <div className="mb-1"><span className="text-emerald-600 font-medium">문서유형:</span> {workflowData.fullDocumentFlow.testSummary.documentTypes?.join(', ')}</div>
                        <div><span className="text-emerald-600 font-medium">결재역할:</span> {workflowData.fullDocumentFlow.testSummary.approvalRoles?.join(', ')}</div>
                      </div>
                    </div>
                  </div>
                )}

                {/* 테스트 케이스 */}
                <div className="space-y-1">
                  {workflowData.fullDocumentFlow.testCases?.map((tc, idx) => (
                    <div key={idx} className="flex justify-between items-center bg-white p-2 rounded border border-emerald-100">
                      <div className="flex items-center gap-2">
                        <span className="px-2 py-0.5 bg-emerald-100 text-emerald-700 rounded text-xs">{tc.phase}</span>
                        <span className="text-gray-700 text-sm">{tc.action}</span>
                      </div>
                      <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">{tc.status}</span>
                    </div>
                  ))}
                </div>

                {/* 요약 */}
                <div className="pt-3 mt-3 border-t border-emerald-200 flex justify-between text-xs">
                  <span className="text-emerald-600">📍 전체 업무 프로세스</span>
                  <span className="text-green-600 font-medium">✓ {workflowData.fullDocumentFlow.summary?.success}/{workflowData.fullDocumentFlow.summary?.total} 성공</span>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  // ═══════════════════════════════════════════════════════════════════════════
  // E2E 50건 테스트 탭 - 공정별 세부 단계 포함 전체 프로세스 검증
  // ═══════════════════════════════════════════════════════════════════════════
  const E2ETestTab = () => {
    const [e2eData, setE2eData] = useState(null);
    const [summary, setSummary] = useState(null);
    const [validation, setValidation] = useState(null);
    const [selectedOrder, setSelectedOrder] = useState(null);
    const [viewMode, setViewMode] = useState('overview'); // overview, detail, issues

    // E2E 테스트 데이터 생성
    useEffect(() => {
      const data = generateE2ETestData(integratedCustomerMaster, integratedSiteMaster);
      setE2eData(data);
      setSummary(generateTestDataSummary(data));
      setValidation(validateE2EDataIntegrity(data));
    }, []);

    if (!e2eData) {
      return <div className="p-6 text-center">테스트 데이터 생성 중...</div>;
    }

    // 선택된 수주의 전체 흐름 조회
    const getOrderFlow = (orderId) => {
      const order = e2eData.orders.find(o => o.id === orderId);
      const quote = e2eData.quotes.find(q => q.id === order?.quoteId);
      const productionOrder = e2eData.productionOrders.find(po => po.orderId === orderId);
      const workOrders = e2eData.workOrders.filter(wo => wo.orderId === orderId);
      const pqcInspections = e2eData.pqcInspections.filter(pqc => pqc.orderId === orderId);
      const packaging = e2eData.packaging.find(p => p.orderId === orderId);
      const shipment = e2eData.shipments.find(s => s.orderId === orderId);

      return { order, quote, productionOrder, workOrders, pqcInspections, packaging, shipment };
    };

    // 개요 뷰
    const OverviewView = () => (
      <div className="space-y-4">
        {/* 데이터 요약 카드 */}
        <div className="grid grid-cols-4 gap-3">
          <div className="bg-blue-50 border border-blue-200 rounded p-3">
            <div className="text-xs text-blue-600">견적</div>
            <div className="text-xl font-bold text-blue-800">{summary.totalQuotes}건</div>
          </div>
          <div className="bg-green-50 border border-green-200 rounded p-3">
            <div className="text-xs text-green-600">수주</div>
            <div className="text-xl font-bold text-green-800">{summary.totalOrders}건</div>
          </div>
          <div className="bg-yellow-50 border border-yellow-200 rounded p-3">
            <div className="text-xs text-yellow-600">작업지시</div>
            <div className="text-xl font-bold text-yellow-800">{summary.totalWorkOrders}건</div>
          </div>
          <div className="bg-purple-50 border border-purple-200 rounded p-3">
            <div className="text-xs text-purple-600">중간검사(PQC)</div>
            <div className="text-xl font-bold text-purple-800">{summary.totalPQCInspections}건</div>
          </div>
        </div>

        {/* 상태별 분포 */}
        <div className="grid grid-cols-2 gap-4">
          <div className="border rounded p-3">
            <h4 className="font-medium text-sm mb-2">수주 상태 분포</h4>
            <div className="space-y-1">
              {Object.entries(summary.orderStatusDistribution).map(([status, count]) => (
                <div key={status} className="flex justify-between text-xs">
                  <span className={getStatusColor(status) + ' px-2 py-0.5 rounded'}>{status}</span>
                  <span className="font-medium">{count}건</span>
                </div>
              ))}
            </div>
          </div>
          <div className="border rounded p-3">
            <h4 className="font-medium text-sm mb-2">공정별 작업지시 분포</h4>
            <div className="space-y-1">
              {Object.entries(summary.workOrdersByProcess).map(([process, count]) => (
                <div key={process} className="flex justify-between text-xs">
                  <span className="text-gray-600">{process}</span>
                  <span className="font-medium">{count}건</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* PQC 검사 결과 */}
        <div className="border rounded p-3">
          <h4 className="font-medium text-sm mb-2">중간검사(PQC) 결과 분포</h4>
          <div className="flex gap-4">
            {Object.entries(summary.pqcResultDistribution).map(([result, count]) => (
              <div key={result} className={`flex items-center gap-2 px-3 py-1 rounded ${result === '합격' ? 'bg-green-100' : 'bg-red-100'}`}>
                <span className="text-sm">{result}</span>
                <span className="font-bold">{count}건</span>
                <span className="text-xs text-gray-500">
                  ({((count / summary.totalPQCInspections) * 100).toFixed(1)}%)
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* 데이터 정합성 검증 */}
        <div className={`border rounded p-3 ${validation.isValid ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'}`}>
          <h4 className="font-medium text-sm mb-2 flex items-center gap-2">
            {validation.isValid ? <CheckCircle className="w-4 h-4 text-green-600" /> : <AlertCircle className="w-4 h-4 text-red-600" />}
            데이터 정합성 검증
          </h4>
          {validation.isValid ? (
            <p className="text-sm text-green-700">모든 데이터 연결이 정상입니다. (견적→수주→생산지시→작업지시→검사→포장→출하)</p>
          ) : (
            <div className="space-y-1">
              <p className="text-sm text-red-700">{validation.issueCount}건의 정합성 문제 발견</p>
              {validation.issues.slice(0, 5).map((issue, idx) => (
                <p key={idx} className="text-xs text-red-600">• {issue}</p>
              ))}
            </div>
          )}
        </div>

        {/* 수주 목록 (클릭하면 상세 흐름 확인) */}
        <div className="border rounded">
          <div className="bg-gray-50 px-3 py-2 border-b">
            <h4 className="font-medium text-sm">E2E 테스트 수주 목록 (클릭하여 전체 흐름 확인)</h4>
          </div>
          <div className="max-h-60 overflow-y-auto">
            <table className="w-full text-xs">
              <thead className="bg-gray-50 sticky top-0">
                <tr>
                  <th className="px-2 py-1 text-left">수주번호</th>
                  <th className="px-2 py-1 text-left">거래처</th>
                  <th className="px-2 py-1 text-left">제품유형</th>
                  <th className="px-2 py-1 text-left">수량</th>
                  <th className="px-2 py-1 text-left">상태</th>
                  <th className="px-2 py-1 text-center">작업지시</th>
                  <th className="px-2 py-1 text-center">PQC</th>
                </tr>
              </thead>
              <tbody>
                {e2eData.orders.slice(0, 20).map(order => {
                  const woCount = e2eData.workOrders.filter(wo => wo.orderId === order.id).length;
                  const pqcCount = e2eData.pqcInspections.filter(pqc => pqc.orderId === order.id).length;
                  return (
                    <tr
                      key={order.id}
                      className={`border-b hover:bg-blue-50 cursor-pointer ${selectedOrder === order.id ? 'bg-blue-100' : ''}`}
                      onClick={() => { setSelectedOrder(order.id); setViewMode('detail'); }}
                    >
                      <td className="px-2 py-1 font-medium">{order.orderNo}</td>
                      <td className="px-2 py-1">{order.customerName}</td>
                      <td className="px-2 py-1">{order.productType}</td>
                      <td className="px-2 py-1">{order.qty}대</td>
                      <td className="px-2 py-1">
                        <span className={`px-1.5 py-0.5 rounded text-xs ${getStatusColor(order.status)}`}>{order.status}</span>
                      </td>
                      <td className="px-2 py-1 text-center">{woCount}건</td>
                      <td className="px-2 py-1 text-center">{pqcCount}건</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    );

    // 상세 흐름 뷰
    const DetailView = () => {
      if (!selectedOrder) {
        return <div className="p-6 text-center text-gray-500">수주를 선택하세요</div>;
      }

      const flow = getOrderFlow(selectedOrder);
      const workflows = processMasterConfigModule.processWorkflows;

      return (
        <div className="space-y-4">
          {/* 뒤로가기 */}
          <button onClick={() => setViewMode('overview')} className="flex items-center gap-1 text-sm text-blue-600 hover:underline">
            <ArrowLeft className="w-4 h-4" /> 목록으로
          </button>

          {/* 수주 정보 */}
          <div className="bg-blue-50 border border-blue-200 rounded p-3">
            <h4 className="font-medium text-sm mb-2">수주 정보</h4>
            <div className="grid grid-cols-4 gap-2 text-xs">
              <div><span className="text-gray-500">수주번호:</span> <span className="font-medium">{flow.order?.orderNo}</span></div>
              <div><span className="text-gray-500">거래처:</span> {flow.order?.customerName}</div>
              <div><span className="text-gray-500">제품유형:</span> {flow.order?.productType}</div>
              <div><span className="text-gray-500">상태:</span> <span className={`px-1.5 py-0.5 rounded ${getStatusColor(flow.order?.status)}`}>{flow.order?.status}</span></div>
            </div>
          </div>

          {/* 견적 → 수주 연결 */}
          <div className="grid grid-cols-2 gap-3">
            <div className="border rounded p-2">
              <h5 className="text-xs font-medium text-gray-500 mb-1">견적</h5>
              <p className="font-medium text-sm">{flow.quote?.quoteNo}</p>
              <p className="text-xs text-gray-500">{flow.quote?.quoteDate}</p>
            </div>
            <div className="border rounded p-2">
              <h5 className="text-xs font-medium text-gray-500 mb-1">생산지시</h5>
              <p className="font-medium text-sm">{flow.productionOrder?.productionOrderNo}</p>
              <p className="text-xs text-gray-500">공정 {flow.productionOrder?.completedProcesses}/{flow.productionOrder?.totalProcesses} 완료</p>
            </div>
          </div>

          {/* 공정별 작업지시 및 세부 단계 */}
          <div className="border rounded">
            <div className="bg-gray-50 px-3 py-2 border-b">
              <h4 className="font-medium text-sm">공정별 작업지시 (세부 단계 포함)</h4>
            </div>
            <div className="p-3 space-y-3">
              {Object.keys(workflows).map(workflowCode => {
                const workflowWOs = flow.workOrders.filter(wo => wo.workflowCode === workflowCode);
                if (workflowWOs.length === 0) return null;

                const workflow = workflows[workflowCode];
                return (
                  <div key={workflowCode} className="border rounded p-2">
                    <h5 className="font-medium text-sm mb-2 flex items-center gap-2">
                      <span className="w-2 h-2 bg-blue-500 rounded-full"></span>
                      {workflow.name} ({workflowWOs.length}단계)
                    </h5>
                    <div className="space-y-1">
                      {workflowWOs.map(wo => {
                        const pqc = flow.pqcInspections.find(p => p.workOrderId === wo.id);
                        return (
                          <div key={wo.id} className="flex items-center gap-2 text-xs bg-gray-50 rounded px-2 py-1">
                            <span className={`w-1.5 h-1.5 rounded-full ${wo.status === '완료' ? 'bg-green-500' : wo.status === '진행중' ? 'bg-yellow-500' : 'bg-gray-300'}`}></span>
                            <span className="w-16 font-mono">{wo.stepCode}</span>
                            <span className="flex-1">{wo.stepName}</span>
                            <span className={`px-1.5 py-0.5 rounded ${getStatusColor(wo.status)}`}>{wo.status}</span>
                            {wo.isQCStep && (
                              <span className={`px-1.5 py-0.5 rounded ${pqc?.result === '합격' ? 'bg-green-100 text-green-800' : pqc?.result === '불합격' ? 'bg-red-100 text-red-800' : 'bg-gray-100'}`}>
                                {pqc ? `PQC:${pqc.result}` : 'PQC대기'}
                              </span>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* 포장 및 출하 */}
          <div className="grid grid-cols-2 gap-3">
            <div className={`border rounded p-2 ${flow.packaging ? 'bg-green-50 border-green-200' : 'bg-gray-50'}`}>
              <h5 className="text-xs font-medium text-gray-500 mb-1">포장</h5>
              {flow.packaging ? (
                <>
                  <p className="font-medium text-sm">{flow.packaging.packagingNo}</p>
                  <p className="text-xs">{flow.packaging.packedQty}대 / {flow.packaging.packageCount}박스</p>
                </>
              ) : (
                <p className="text-xs text-gray-400">포장 대기</p>
              )}
            </div>
            <div className={`border rounded p-2 ${flow.shipment ? 'bg-green-50 border-green-200' : 'bg-gray-50'}`}>
              <h5 className="text-xs font-medium text-gray-500 mb-1">출하</h5>
              {flow.shipment ? (
                <>
                  <p className="font-medium text-sm">{flow.shipment.shipmentNo}</p>
                  <p className="text-xs">{flow.shipment.status} (진행률: {flow.shipment.progress}%)</p>
                </>
              ) : (
                <p className="text-xs text-gray-400">출하 대기</p>
              )}
            </div>
          </div>
        </div>
      );
    };

    // 문제점/보완점 뷰
    const IssuesView = () => (
      <div className="space-y-4">
        <h3 className="font-bold text-lg">E2E 테스트 분석 결과 - 문제점 및 보완점</h3>

        {/* 현재 구현된 사항 */}
        <div className="border rounded p-3 bg-green-50 border-green-200">
          <h4 className="font-medium text-sm mb-2 flex items-center gap-2">
            <CheckCircle className="w-4 h-4 text-green-600" />
            정상 구현된 사항
          </h4>
          <ul className="text-xs space-y-1 text-green-800">
            <li>• 견적 → 수주 → 생산지시 연계 정상</li>
            <li>• 공정별 세부 단계(SCREEN 8단계, SLAT 4단계, FOLD 5단계, STOCK 3단계) 작업지시 생성</li>
            <li>• isQCStep=true 단계에서 PQC 검사 자동 생성</li>
            <li>• 품목-공정 매핑 테이블 연계 (bomItemProcessMapping)</li>
            <li>• 포장 및 출하 데이터 연계</li>
          </ul>
        </div>

        {/* 해결된 문제점 */}
        <div className="border rounded p-3 bg-green-50 border-green-200">
          <h4 className="font-medium text-sm mb-2 flex items-center gap-2">
            <CheckCircle className="w-4 h-4 text-green-600" />
            해결된 문제점
          </h4>
          <ul className="text-xs space-y-2 text-green-800">
            <li>
              <strong>✅ 1. 공정코드 통일 완료</strong>
              <p className="text-gray-600 mt-0.5">itemProcessMapping을 SCR-001, SLT-001, FLD-001, STK-001 형식으로 통일</p>
            </li>
            <li>
              <strong>✅ 2. 자재 LOT 추적 구현</strong>
              <p className="text-gray-600 mt-0.5">materialLotMaster 추가, 자재투입 단계에서 LOT 할당 및 사용이력 추적</p>
            </li>
            <li>
              <strong>✅ 3. 포장 합류점(mergePoint) 구현</strong>
              <p className="text-gray-600 mt-0.5">포장 데이터에 mergedProcesses 정보 포함, 모든 공정의 PACK 단계 합류 추적</p>
            </li>
            <li>
              <strong>✅ 4. 재작업 프로세스 구현</strong>
              <p className="text-gray-600 mt-0.5">PQC 불합격 시 reworkInfo 생성, 재작업지시→재작업완료→재검사 합격 흐름 구현</p>
            </li>
            <li>
              <strong>✅ 5. 작업실적 연계 구현</strong>
              <p className="text-gray-600 mt-0.5">workResults 추가, 작업지시 완료/진행중 시 자동 실적 생성</p>
            </li>
          </ul>
        </div>

        {/* 추가 보완 가능 항목 */}
        <div className="border rounded p-3 bg-yellow-50 border-yellow-200">
          <h4 className="font-medium text-sm mb-2 flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-yellow-600" />
            추가 보완 가능 항목
          </h4>
          <ul className="text-xs space-y-2 text-yellow-800">
            <li>
              <strong>5. 작업실적 입력 연계</strong>
              <p className="text-gray-600 mt-0.5">작업자 화면에서 단계별 실적 입력 시 다음 단계 자동 활성화</p>
            </li>
          </ul>
        </div>

        {/* 데이터 흐름도 */}
        <div className="border rounded p-3">
          <h4 className="font-medium text-sm mb-2">E2E 데이터 흐름도</h4>
          <div className="text-xs font-mono bg-gray-50 p-3 rounded">
            <pre>{`
견적(Quote) ──┬──→ 수주(Order) ──→ 생산지시(ProductionOrder)
              │                          │
              │                          ├──→ SCREEN 작업지시 (8단계)
              │                          │    ├─ SCR-MAT (자재투입)
              │                          │    ├─ SCR-CNT (절단매수확인)
              │                          │    ├─ SCR-CUT (원단절단)
              │                          │    ├─ SCR-CHK (절단Check) → PQC
              │                          │    ├─ SCR-SEW (미싱)
              │                          │    ├─ SCR-END (앤드락)
              │                          │    ├─ SCR-QC (중간검사) → PQC
              │                          │    └─ SCR-PACK (포장)
              │                          │
              │                          ├──→ SLAT 작업지시 (4단계)
              │                          ├──→ FOLD 작업지시 (5단계)
              │                          └──→ STOCK 작업지시 (3단계)
              │                                    │
              │                                    ▼
              │                              ┌─────────┐
              │                              │  포장   │ ← 모든 공정 합류
              │                              └────┬────┘
              │                                   │
              └─────────────────────────────→  출하(Shipment)
            `}</pre>
          </div>
        </div>
      </div>
    );

    return (
      <div className="space-y-4">
        {/* 뷰 모드 선택 */}
        <div className="flex gap-2 border-b pb-2">
          <button
            onClick={() => setViewMode('overview')}
            className={`px-3 py-1 rounded text-sm ${viewMode === 'overview' ? 'bg-blue-600 text-white' : 'bg-gray-100 hover:bg-gray-200'}`}
          >
            개요
          </button>
          <button
            onClick={() => setViewMode('detail')}
            className={`px-3 py-1 rounded text-sm ${viewMode === 'detail' ? 'bg-blue-600 text-white' : 'bg-gray-100 hover:bg-gray-200'}`}
          >
            상세 흐름
          </button>
          <button
            onClick={() => setViewMode('issues')}
            className={`px-3 py-1 rounded text-sm ${viewMode === 'issues' ? 'bg-blue-600 text-white' : 'bg-gray-100 hover:bg-gray-200'}`}
          >
            문제점/보완점
          </button>
        </div>

        {/* 뷰 렌더링 */}
        {viewMode === 'overview' && <OverviewView />}
        {viewMode === 'detail' && <DetailView />}
        {viewMode === 'issues' && <IssuesView />}
      </div>
    );
  };

  // 요약 탭
  const SummaryTab = () => {
    // 견적 상태별 통계
    const quoteStats = {
      total: integratedQuoteMaster.length,
      견적중: integratedQuoteMaster.filter(q => q.status === '견적중').length,
      제출완료: integratedQuoteMaster.filter(q => q.status === '제출완료').length,
      수주전환: integratedQuoteMaster.filter(q => q.status === '수주전환').length,
      취소: integratedQuoteMaster.filter(q => q.status === '취소').length,
      만료: integratedQuoteMaster.filter(q => q.status === '만료').length,
    };

    // 수주 상태별 통계 (생산지시완료까지만 표시)
    const orderStats = {
      total: integratedOrderMaster.length,
      수주확정: integratedOrderMaster.filter(o => o.status === '수주확정').length,
      생산지시: integratedOrderMaster.filter(o => o.status === '생산지시').length,
      생산중: integratedOrderMaster.filter(o => o.status === '생산중').length,
      생산완료: integratedOrderMaster.filter(o => o.status === '생산완료').length,
      생산지시완료: integratedOrderMaster.filter(o => o.status === '생산지시완료').length,
    };

    // 생산 상태별 통계
    const workOrderStats = {
      total: integratedWorkOrderMaster.length,
      대기: integratedWorkOrderMaster.filter(w => w.status === '대기').length,
      진행중: integratedWorkOrderMaster.filter(w => w.status === '진행중').length,
      완료: integratedWorkOrderMaster.filter(w => w.status === '완료').length,
    };

    // 품질검사 결과별 통계
    const qualityStats = {
      total: integratedQualityInspection.length,
      합격: integratedQualityInspection.filter(q => q.result === '합격').length,
      조건부합격: integratedQualityInspection.filter(q => q.result === '조건부합격').length,
      불합격: integratedQualityInspection.filter(q => q.result === '불합격').length,
    };

    // 수금 현황
    const collectionStats = {
      total: integratedDataSummary.totalSalesAmount,
      collected: integratedDataSummary.totalCollectedAmount,
      uncollected: integratedDataSummary.totalSalesAmount - integratedDataSummary.totalCollectedAmount,
      collectionRate: integratedDataSummary.totalSalesAmount > 0
        ? ((integratedDataSummary.totalCollectedAmount / integratedDataSummary.totalSalesAmount) * 100).toFixed(1)
        : 0,
    };

    // 신용등급별 거래처
    const creditStats = {
      A: integratedCustomerMaster.filter(c => c.creditGrade === 'A').length,
      B: integratedCustomerMaster.filter(c => c.creditGrade === 'B').length,
      C: integratedCustomerMaster.filter(c => c.creditGrade === 'C').length,
    };

    return (
      <div className="space-y-6">
        {/* 핵심 KPI 카드 */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
            <div className="flex items-center gap-2 mb-2">
              <Building className="w-5 h-5 text-blue-600" />
              <span className="text-sm text-blue-600 font-medium">거래처</span>
            </div>
            <div className="text-2xl font-bold text-blue-800">{integratedDataSummary.customers}개</div>
            <div className="text-xs text-blue-600 mt-1 flex gap-2">
              <span className="bg-green-100 px-1.5 rounded">A:{creditStats.A}</span>
              <span className="bg-yellow-100 px-1.5 rounded">B:{creditStats.B}</span>
              <span className="bg-red-100 px-1.5 rounded">C:{creditStats.C}</span>
            </div>
          </div>
          <div className="bg-purple-50 p-4 rounded-lg border border-purple-200">
            <div className="flex items-center gap-2 mb-2">
              <MapPin className="w-5 h-5 text-purple-600" />
              <span className="text-sm text-purple-600 font-medium">현장</span>
            </div>
            <div className="text-2xl font-bold text-purple-800">{integratedDataSummary.sites}개</div>
            <div className="text-xs text-purple-600 mt-1">
              평균 {(integratedDataSummary.sites / integratedDataSummary.customers).toFixed(1)}개/거래처
            </div>
          </div>
          <div className="bg-green-50 p-4 rounded-lg border border-green-200">
            <div className="flex items-center gap-2 mb-2">
              <FileText className="w-5 h-5 text-green-600" />
              <span className="text-sm text-green-600 font-medium">견적</span>
            </div>
            <div className="text-2xl font-bold text-green-800">{integratedDataSummary.quotes}건</div>
            <div className="text-xs text-green-600 mt-1">{formatCurrency(integratedDataSummary.totalQuoteAmount)}</div>
          </div>
          <div className="bg-orange-50 p-4 rounded-lg border border-orange-200">
            <div className="flex items-center gap-2 mb-2">
              <Package className="w-5 h-5 text-orange-600" />
              <span className="text-sm text-orange-600 font-medium">수주</span>
            </div>
            <div className="text-2xl font-bold text-orange-800">{integratedDataSummary.orders}건</div>
            <div className="text-xs text-orange-600 mt-1">{formatCurrency(integratedDataSummary.totalOrderAmount)}</div>
          </div>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
          <div className="bg-yellow-50 p-4 rounded-lg border border-yellow-200">
            <div className="flex items-center gap-2 mb-2">
              <Factory className="w-5 h-5 text-yellow-600" />
              <span className="text-sm text-yellow-600 font-medium">작업지시</span>
            </div>
            <div className="text-2xl font-bold text-yellow-800">{integratedDataSummary.workOrders}건</div>
          </div>
          <div className="bg-indigo-50 p-4 rounded-lg border border-indigo-200">
            <div className="flex items-center gap-2 mb-2">
              <ShieldCheck className="w-5 h-5 text-indigo-600" />
              <span className="text-sm text-indigo-600 font-medium">품질검사</span>
            </div>
            <div className="text-2xl font-bold text-indigo-800">{integratedDataSummary.qualityInspections}건</div>
          </div>
          <div className="bg-teal-50 p-4 rounded-lg border border-teal-200">
            <div className="flex items-center gap-2 mb-2">
              <Truck className="w-5 h-5 text-teal-600" />
              <span className="text-sm text-teal-600 font-medium">출하</span>
            </div>
            <div className="text-2xl font-bold text-teal-800">{integratedDataSummary.shipments}건</div>
          </div>
          <div className="bg-pink-50 p-4 rounded-lg border border-pink-200">
            <div className="flex items-center gap-2 mb-2">
              <TrendingUp className="w-5 h-5 text-pink-600" />
              <span className="text-sm text-pink-600 font-medium">매출</span>
            </div>
            <div className="text-2xl font-bold text-pink-800">{integratedDataSummary.sales}건</div>
            <div className="text-xs text-pink-600 mt-1">{formatCurrency(integratedDataSummary.totalSalesAmount)}</div>
          </div>
          <div className="bg-emerald-50 p-4 rounded-lg border border-emerald-200">
            <div className="flex items-center gap-2 mb-2">
              <DollarSign className="w-5 h-5 text-emerald-600" />
              <span className="text-sm text-emerald-600 font-medium">수금</span>
            </div>
            <div className="text-2xl font-bold text-emerald-800">{integratedDataSummary.collections}건</div>
            <div className="text-xs text-emerald-600 mt-1">{formatCurrency(integratedDataSummary.totalCollectedAmount)}</div>
          </div>
        </div>

        {/* 프로세스 흐름도 */}
        <div className="bg-white p-4 rounded-lg border">
          <h3 className="font-semibold mb-4 flex items-center gap-2">
            <GitBranch className="w-5 h-5" />
            데이터 흐름 요약
          </h3>
          <div className="flex flex-wrap items-center justify-center gap-2 text-sm">
            <div className="flex items-center gap-1 bg-blue-100 px-3 py-2 rounded">
              <Building className="w-4 h-4" />
              <span>거래처 {integratedDataSummary.customers}</span>
            </div>
            <ChevronRight className="w-4 h-4 text-gray-400" />
            <div className="flex items-center gap-1 bg-purple-100 px-3 py-2 rounded">
              <MapPin className="w-4 h-4" />
              <span>현장 {integratedDataSummary.sites}</span>
            </div>
            <ChevronRight className="w-4 h-4 text-gray-400" />
            <div className="flex items-center gap-1 bg-green-100 px-3 py-2 rounded">
              <FileText className="w-4 h-4" />
              <span>견적 {integratedDataSummary.quotes}</span>
            </div>
            <ChevronRight className="w-4 h-4 text-gray-400" />
            <div className="flex items-center gap-1 bg-orange-100 px-3 py-2 rounded">
              <Package className="w-4 h-4" />
              <span>수주 {integratedDataSummary.orders}</span>
            </div>
            <ChevronRight className="w-4 h-4 text-gray-400" />
            <div className="flex items-center gap-1 bg-yellow-100 px-3 py-2 rounded">
              <Factory className="w-4 h-4" />
              <span>작업 {integratedDataSummary.workOrders}</span>
            </div>
            <ChevronRight className="w-4 h-4 text-gray-400" />
            <div className="flex items-center gap-1 bg-indigo-100 px-3 py-2 rounded">
              <ShieldCheck className="w-4 h-4" />
              <span>검사 {integratedDataSummary.qualityInspections}</span>
            </div>
            <ChevronRight className="w-4 h-4 text-gray-400" />
            <div className="flex items-center gap-1 bg-teal-100 px-3 py-2 rounded">
              <Truck className="w-4 h-4" />
              <span>출하 {integratedDataSummary.shipments}</span>
            </div>
            <ChevronRight className="w-4 h-4 text-gray-400" />
            <div className="flex items-center gap-1 bg-pink-100 px-3 py-2 rounded">
              <TrendingUp className="w-4 h-4" />
              <span>매출 {integratedDataSummary.sales}</span>
            </div>
            <ChevronRight className="w-4 h-4 text-gray-400" />
            <div className="flex items-center gap-1 bg-emerald-100 px-3 py-2 rounded">
              <DollarSign className="w-4 h-4" />
              <span>수금 {integratedDataSummary.collections}</span>
            </div>
          </div>
        </div>

        {/* 상세 통계 그리드 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {/* 견적 상태별 분포 */}
          <div className="bg-white p-4 rounded-lg border shadow-sm">
            <h4 className="font-semibold text-sm mb-3 flex items-center gap-2">
              <FileText className="w-4 h-4 text-green-600" />
              견적 상태 분포
            </h4>
            <div className="space-y-2 text-xs">
              {Object.entries(quoteStats).filter(([k]) => k !== 'total').map(([status, count]) => (
                <div key={status} className="flex items-center justify-between">
                  <span className={`px-2 py-0.5 rounded ${status === '수주전환' ? 'bg-green-100 text-green-700' :
                      status === '견적중' ? 'bg-blue-100 text-blue-700' :
                        status === '제출완료' ? 'bg-yellow-100 text-yellow-700' :
                          status === '취소' ? 'bg-red-100 text-red-700' :
                            'bg-gray-100 text-gray-700'
                    }`}>{status}</span>
                  <div className="flex items-center gap-2">
                    <div className="w-20 h-2 bg-gray-100 rounded-full overflow-hidden">
                      <div
                        className={`h-full rounded-full ${status === '수주전환' ? 'bg-green-500' :
                            status === '견적중' ? 'bg-blue-500' :
                              status === '제출완료' ? 'bg-yellow-500' :
                                status === '취소' ? 'bg-red-500' :
                                  'bg-gray-500'
                          }`}
                        style={{ width: `${(count / quoteStats.total) * 100}%` }}
                      />
                    </div>
                    <span className="font-medium w-8 text-right">{count}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 수주 상태별 분포 */}
          <div className="bg-white p-4 rounded-lg border shadow-sm">
            <h4 className="font-semibold text-sm mb-3 flex items-center gap-2">
              <Package className="w-4 h-4 text-orange-600" />
              수주 상태 분포
            </h4>
            <div className="space-y-2 text-xs">
              {Object.entries(orderStats).filter(([k]) => k !== 'total').map(([status, count]) => (
                <div key={status} className="flex items-center justify-between">
                  <span className={`px-2 py-0.5 rounded ${status === '완료' ? 'bg-emerald-100 text-emerald-700' :
                      status === '출하완료' ? 'bg-teal-100 text-teal-700' :
                        status === '출하중' ? 'bg-cyan-100 text-cyan-700' :
                          status === '생산완료' ? 'bg-indigo-100 text-indigo-700' :
                            status === '생산중' ? 'bg-yellow-100 text-yellow-700' :
                              'bg-orange-100 text-orange-700'
                    }`}>{status}</span>
                  <div className="flex items-center gap-2">
                    <div className="w-20 h-2 bg-gray-100 rounded-full overflow-hidden">
                      <div
                        className={`h-full rounded-full ${status === '완료' ? 'bg-emerald-500' :
                            status === '출하완료' ? 'bg-teal-500' :
                              status === '출하중' ? 'bg-cyan-500' :
                                status === '생산완료' ? 'bg-indigo-500' :
                                  status === '생산중' ? 'bg-yellow-500' :
                                    'bg-orange-500'
                          }`}
                        style={{ width: `${orderStats.total > 0 ? (count / orderStats.total) * 100 : 0}%` }}
                      />
                    </div>
                    <span className="font-medium w-8 text-right">{count}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 생산/품질 현황 */}
          <div className="bg-white p-4 rounded-lg border shadow-sm">
            <h4 className="font-semibold text-sm mb-3 flex items-center gap-2">
              <Factory className="w-4 h-4 text-yellow-600" />
              생산 현황
            </h4>
            <div className="space-y-3">
              <div className="text-xs">
                <div className="flex justify-between mb-1">
                  <span>진행률</span>
                  <span className="font-medium">
                    {workOrderStats.total > 0
                      ? ((workOrderStats.완료 / workOrderStats.total) * 100).toFixed(0)
                      : 0}%
                  </span>
                </div>
                <div className="w-full h-3 bg-gray-100 rounded-full overflow-hidden">
                  <div className="h-full bg-gradient-to-r from-yellow-400 to-green-500 transition-all"
                    style={{ width: `${workOrderStats.total > 0 ? (workOrderStats.완료 / workOrderStats.total) * 100 : 0}%` }} />
                </div>
              </div>
              <div className="grid grid-cols-3 gap-2 text-xs text-center">
                <div className="bg-gray-50 p-2 rounded">
                  <div className="font-bold text-gray-700">{workOrderStats.대기}</div>
                  <div className="text-gray-500">대기</div>
                </div>
                <div className="bg-yellow-50 p-2 rounded">
                  <div className="font-bold text-yellow-700">{workOrderStats.진행중}</div>
                  <div className="text-yellow-600">진행중</div>
                </div>
                <div className="bg-green-50 p-2 rounded">
                  <div className="font-bold text-green-700">{workOrderStats.완료}</div>
                  <div className="text-green-600">완료</div>
                </div>
              </div>
            </div>
          </div>

          {/* 수금 현황 */}
          <div className="bg-white p-4 rounded-lg border shadow-sm">
            <h4 className="font-semibold text-sm mb-3 flex items-center gap-2">
              <DollarSign className="w-4 h-4 text-emerald-600" />
              수금 현황
            </h4>
            <div className="space-y-3">
              <div className="text-xs">
                <div className="flex justify-between mb-1">
                  <span>수금률</span>
                  <span className="font-medium text-emerald-600">{collectionStats.collectionRate}%</span>
                </div>
                <div className="w-full h-3 bg-gray-100 rounded-full overflow-hidden">
                  <div className="h-full bg-gradient-to-r from-emerald-400 to-emerald-600 transition-all"
                    style={{ width: `${collectionStats.collectionRate}%` }} />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-2 text-xs">
                <div className="bg-emerald-50 p-2 rounded text-center">
                  <div className="font-bold text-emerald-700">{formatCurrency(collectionStats.collected)}</div>
                  <div className="text-emerald-600">수금완료</div>
                </div>
                <div className="bg-red-50 p-2 rounded text-center">
                  <div className="font-bold text-red-700">{formatCurrency(collectionStats.uncollected)}</div>
                  <div className="text-red-600">미수금</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 품질검사 결과 요약 */}
        <div className="bg-white p-4 rounded-lg border shadow-sm">
          <h4 className="font-semibold text-sm mb-3 flex items-center gap-2">
            <ShieldCheck className="w-4 h-4 text-indigo-600" />
            품질검사 결과 요약 (총 {qualityStats.total}건)
          </h4>
          <div className="flex items-center gap-4">
            <div className="flex-1">
              <div className="flex h-6 rounded-full overflow-hidden bg-gray-100">
                <div className="bg-green-500 transition-all"
                  style={{ width: `${qualityStats.total > 0 ? (qualityStats.합격 / qualityStats.total) * 100 : 0}%` }}
                  title={`합격 ${qualityStats.합격}건`} />
                <div className="bg-yellow-500 transition-all"
                  style={{ width: `${qualityStats.total > 0 ? (qualityStats.조건부합격 / qualityStats.total) * 100 : 0}%` }}
                  title={`조건부합격 ${qualityStats.조건부합격}건`} />
                <div className="bg-red-500 transition-all"
                  style={{ width: `${qualityStats.total > 0 ? (qualityStats.불합격 / qualityStats.total) * 100 : 0}%` }}
                  title={`불합격 ${qualityStats.불합격}건`} />
              </div>
            </div>
            <div className="flex gap-4 text-xs">
              <div className="flex items-center gap-1">
                <div className="w-3 h-3 bg-green-500 rounded" />
                <span>합격 {qualityStats.합격}</span>
              </div>
              <div className="flex items-center gap-1">
                <div className="w-3 h-3 bg-yellow-500 rounded" />
                <span>조건부 {qualityStats.조건부합격}</span>
              </div>
              <div className="flex items-center gap-1">
                <div className="w-3 h-3 bg-red-500 rounded" />
                <span>불합격 {qualityStats.불합격}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  // 거래처 탭
  const CustomersTab = () => (
    <div className="space-y-4">
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead className="bg-gray-100">
            <tr>
              <th className="px-3 py-2 text-left">코드</th>
              <th className="px-3 py-2 text-left">거래처명</th>
              <th className="px-3 py-2 text-left">신용등급</th>
              <th className="px-3 py-2 text-left">할인율</th>
              <th className="px-3 py-2 text-left">담당자</th>
              <th className="px-3 py-2 text-left">현장수</th>
              <th className="px-3 py-2 text-left">결제조건</th>
            </tr>
          </thead>
          <tbody>
            {integratedCustomerMaster.map(customer => {
              const siteCount = integratedSiteMaster.filter(s => s.customerId === customer.id).length;
              return (
                <tr key={customer.id} className="border-b hover:bg-gray-50 cursor-pointer"
                  onClick={() => setSelectedCustomer(customer)}>
                  <td className="px-3 py-2 font-mono text-xs">{customer.code}</td>
                  <td className="px-3 py-2 font-medium">{customer.name}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-1 rounded text-xs font-medium ${customer.creditGrade === 'A' ? 'bg-green-100 text-green-800' :
                        customer.creditGrade === 'B' ? 'bg-yellow-100 text-yellow-800' :
                          'bg-red-100 text-red-800'
                      }`}>{customer.creditGrade}등급</span>
                  </td>
                  <td className="px-3 py-2">{customer.discountRate}%</td>
                  <td className="px-3 py-2">{customer.manager}</td>
                  <td className="px-3 py-2">{siteCount}개</td>
                  <td className="px-3 py-2 text-xs">{customer.paymentTerms}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );

  // 견적 탭
  const QuotesTab = () => {
    const [quoteFilter, setQuoteFilter] = useState('all');
    const [quoteSearch, setQuoteSearch] = useState('');
    const [quotePage, setQuotePage] = useState(1);
    const pageSize = 15;

    // 필터링된 견적 목록
    const filteredQuotes = integratedQuoteMaster.filter(quote => {
      const matchStatus = quoteFilter === 'all' || quote.status === quoteFilter;
      const matchSearch = quoteSearch === '' ||
        quote.quoteNo.toLowerCase().includes(quoteSearch.toLowerCase()) ||
        quote.customerName.toLowerCase().includes(quoteSearch.toLowerCase()) ||
        quote.siteName.toLowerCase().includes(quoteSearch.toLowerCase());
      return matchStatus && matchSearch;
    }).sort((a, b) => new Date(b.quoteDate) - new Date(a.quoteDate)); // 최신순 정렬

    // 페이지네이션
    const totalPages = Math.ceil(filteredQuotes.length / pageSize);
    const paginatedQuotes = filteredQuotes.slice((quotePage - 1) * pageSize, quotePage * pageSize);

    // 목록 선택 훅
    const { selectedIds, handleSelect, handleSelectAll, isAllSelected, hasSelection, isMultiSelect, isSelected } = useListSelection(paginatedQuotes);

    // 필터 변경시 페이지 초기화
    const handleFilterChange = (filter) => {
      setQuoteFilter(filter);
      setQuotePage(1);
    };

    const handleEdit = (quote) => alert(`견적 수정: ${quote.quoteNo}`);
    const handleDelete = (quote) => window.confirm(`${quote.quoteNo} 견적을 삭제하시겠습니까?`) && alert(`견적 삭제: ${quote.quoteNo}`);
    const handleBulkDelete = () => window.confirm(`선택한 ${selectedIds.length}건을 삭제하시겠습니까?`) && alert(`${selectedIds.length}건 삭제`);

    return (
      <div className="space-y-4">
        {/* 필터 및 검색 영역 */}
        <div className="flex flex-wrap items-center gap-3">
          <div className="flex gap-1">
            <button
              onClick={() => handleFilterChange('all')}
              className={`px-3 py-1.5 text-xs font-medium rounded-lg transition-all ${quoteFilter === 'all' ? 'bg-gray-800 text-white' : 'bg-gray-100 hover:bg-gray-200'
                }`}
            >
              전체 ({integratedQuoteMaster.length})
            </button>
            {['견적중', '제출완료', '수주전환', '취소', '만료'].map(status => {
              const count = integratedQuoteMaster.filter(q => q.status === status).length;
              return (
                <button
                  key={status}
                  onClick={() => handleFilterChange(status)}
                  className={`px-3 py-1.5 text-xs font-medium rounded-lg transition-all ${quoteFilter === status
                      ? `${getStatusColor(status)} ring-2 ring-offset-1`
                      : `${getStatusColor(status)} opacity-60 hover:opacity-100`
                    }`}
                >
                  {status} ({count})
                </button>
              );
            })}
          </div>
          <div className="flex-1" />
          <div className="flex items-center gap-2">
            {isMultiSelect && (
              <Button variant="danger" size="sm" onClick={handleBulkDelete}>
                <Trash2 className="w-4 h-4" /> 선택 삭제 ({selectedIds.length})
              </Button>
            )}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder="검색 (견적번호, 거래처, 현장)"
                value={quoteSearch}
                onChange={(e) => { setQuoteSearch(e.target.value); setQuotePage(1); }}
                className="pl-9 pr-4 py-1.5 text-sm border rounded-lg w-64 focus:ring-2 focus:ring-blue-300 focus:outline-none"
              />
            </div>
          </div>
        </div>

        {/* 테이블 */}
        <div className="overflow-x-auto border rounded-lg">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 border-b">
              <tr>
                <th className="px-3 py-2.5 text-center w-10">
                  <input type="checkbox" checked={isAllSelected} onChange={handleSelectAll} className="rounded" />
                </th>
                <th className="px-3 py-2.5 text-left text-xs font-semibold text-gray-600">견적번호</th>
                <th className="px-3 py-2.5 text-left text-xs font-semibold text-gray-600">견적일</th>
                <th className="px-3 py-2.5 text-left text-xs font-semibold text-gray-600">거래처</th>
                <th className="px-3 py-2.5 text-left text-xs font-semibold text-gray-600">현장</th>
                <th className="px-3 py-2.5 text-left text-xs font-semibold text-gray-600">제품</th>
                <th className="px-3 py-2.5 text-left text-xs font-semibold text-gray-600">사이즈</th>
                <th className="px-3 py-2.5 text-left text-xs font-semibold text-gray-600">수량</th>
                <th className="px-3 py-2.5 text-right text-xs font-semibold text-gray-600">공급가</th>
                <th className="px-3 py-2.5 text-right text-xs font-semibold text-gray-600">총액</th>
                <th className="px-3 py-2.5 text-left text-xs font-semibold text-gray-600">상태</th>
                {hasSelection && <th className="px-3 py-2.5 text-center text-xs font-semibold text-gray-600">작업</th>}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {paginatedQuotes.map((quote, idx) => (
                <tr key={quote.id}
                  className={`hover:bg-blue-50 cursor-pointer transition-colors ${isSelected(quote.id) ? 'bg-blue-50' : idx % 2 === 0 ? 'bg-white' : 'bg-gray-50/50'}`}>
                  <td className="px-3 py-2 text-center" onClick={(e) => e.stopPropagation()}>
                    <input type="checkbox" checked={isSelected(quote.id)} onChange={() => handleSelect(quote.id)} className="rounded" />
                  </td>
                  <td className="px-3 py-2 font-mono text-xs text-blue-600" onClick={() => setSelectedQuote(quote)}>{quote.quoteNo}</td>
                  <td className="px-3 py-2 text-xs" onClick={() => setSelectedQuote(quote)}>{quote.quoteDate}</td>
                  <td className="px-3 py-2 font-medium" onClick={() => setSelectedQuote(quote)}>{quote.customerName}</td>
                  <td className="px-3 py-2 text-xs text-gray-600" onClick={() => setSelectedQuote(quote)}>{quote.siteName}</td>
                  <td className="px-3 py-2 text-xs" onClick={() => setSelectedQuote(quote)}>{quote.productType}</td>
                  <td className="px-3 py-2 text-xs font-mono" onClick={() => setSelectedQuote(quote)}>{quote.width}x{quote.height}</td>
                  <td className="px-3 py-2 text-xs text-center" onClick={() => setSelectedQuote(quote)}>{quote.qty}</td>
                  <td className="px-3 py-2 text-right font-mono text-xs" onClick={() => setSelectedQuote(quote)}>{formatCurrency(quote.supplyAmount || quote.finalAmount / 1.1)}</td>
                  <td className="px-3 py-2 text-right font-mono text-xs font-medium" onClick={() => setSelectedQuote(quote)}>{formatCurrency(quote.totalWithVat || quote.finalAmount)}</td>
                  <td className="px-3 py-2" onClick={() => setSelectedQuote(quote)}>
                    <span className={`px-2 py-1 rounded text-xs font-medium ${getStatusColor(quote.status)}`}>{quote.status}</span>
                  </td>
                  {hasSelection && (
                    <td className="px-3 py-2 text-center" onClick={(e) => e.stopPropagation()}>
                      {isSelected(quote.id) && (
                        <div className="flex items-center justify-center gap-1">
                          <button onClick={() => handleEdit(quote)} className="p-1 hover:bg-gray-200 rounded" title="수정">
                            <Edit2 className="w-4 h-4 text-blue-600" />
                          </button>
                          <button onClick={() => handleDelete(quote)} className="p-1 hover:bg-gray-200 rounded" title="삭제">
                            <Trash2 className="w-4 h-4 text-red-600" />
                          </button>
                        </div>
                      )}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* 페이지네이션 */}
        <div className="flex items-center justify-between px-2">
          <div className="text-sm text-gray-600">
            총 <span className="font-semibold">{filteredQuotes.length}</span>건 중{' '}
            <span className="font-semibold">{(quotePage - 1) * pageSize + 1}</span>-
            <span className="font-semibold">{Math.min(quotePage * pageSize, filteredQuotes.length)}</span>건 표시
          </div>
          <div className="flex items-center gap-1">
            <button
              onClick={() => setQuotePage(1)}
              disabled={quotePage === 1}
              className="p-1.5 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed"
            >
              <ChevronsLeft className="w-4 h-4" />
            </button>
            <button
              onClick={() => setQuotePage(p => Math.max(1, p - 1))}
              disabled={quotePage === 1}
              className="p-1.5 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed"
            >
              <ChevronLeft className="w-4 h-4" />
            </button>
            <div className="flex gap-1 mx-2">
              {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                let pageNum;
                if (totalPages <= 5) pageNum = i + 1;
                else if (quotePage <= 3) pageNum = i + 1;
                else if (quotePage >= totalPages - 2) pageNum = totalPages - 4 + i;
                else pageNum = quotePage - 2 + i;
                return (
                  <button
                    key={pageNum}
                    onClick={() => setQuotePage(pageNum)}
                    className={`w-8 h-8 text-sm rounded-lg transition-all ${quotePage === pageNum
                        ? 'bg-blue-600 text-white font-medium'
                        : 'hover:bg-gray-100'
                      }`}
                  >
                    {pageNum}
                  </button>
                );
              })}
            </div>
            <button
              onClick={() => setQuotePage(p => Math.min(totalPages, p + 1))}
              disabled={quotePage === totalPages}
              className="p-1.5 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed"
            >
              <ChevronRight className="w-4 h-4" />
            </button>
            <button
              onClick={() => setQuotePage(totalPages)}
              disabled={quotePage === totalPages}
              className="p-1.5 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed"
            >
              <ChevronsRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>
    );
  };

  // 수주 탭
  const OrdersTab = () => {
    const { selectedIds, handleSelect, handleSelectAll, isAllSelected, hasSelection, isMultiSelect, isSelected } = useListSelection(integratedOrderMaster);
    const handleEdit = (order) => alert(`수주 수정: ${order.orderNo}`);
    const handleDelete = (order) => window.confirm(`${order.orderNo} 수주를 삭제하시겠습니까?`) && alert(`수주 삭제: ${order.orderNo}`);
    const handleBulkDelete = () => window.confirm(`선택한 ${selectedIds.length}건을 삭제하시겠습니까?`) && alert(`${selectedIds.length}건 삭제`);

    return (
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <div className="flex gap-2 text-sm flex-wrap">
            {['수주확정', '생산지시', '생산중', '생산완료', '생산지시완료'].map(status => (
              <span key={status} className={`px-2 py-1 rounded ${getStatusColor(status)}`}>
                {status}: {integratedOrderMaster.filter(o => o.status === status).length}
              </span>
            ))}
          </div>
          {isMultiSelect && (
            <Button variant="danger" size="sm" onClick={handleBulkDelete}>
              <Trash2 className="w-4 h-4" /> 선택 삭제 ({selectedIds.length})
            </Button>
          )}
        </div>
        <div className="overflow-x-auto max-h-96">
          <table className="w-full text-sm">
            <thead className="bg-gray-100 sticky top-0">
              <tr>
                <th className="px-3 py-2 text-center w-10">
                  <input type="checkbox" checked={isAllSelected} onChange={handleSelectAll} className="rounded" />
                </th>
                <th className="px-3 py-2 text-left">수주번호</th>
                <th className="px-3 py-2 text-left">견적번호</th>
                <th className="px-3 py-2 text-left">거래처</th>
                <th className="px-3 py-2 text-left">현장</th>
                <th className="px-3 py-2 text-right">금액</th>
                <th className="px-3 py-2 text-left">납기일</th>
                <th className="px-3 py-2 text-left">상태</th>
                {hasSelection && <th className="px-3 py-2 text-center">작업</th>}
              </tr>
            </thead>
            <tbody>
              {integratedOrderMaster.map(order => (
                <tr key={order.id} className={`border-b hover:bg-gray-50 ${isSelected(order.id) ? 'bg-blue-50' : ''}`}>
                  <td className="px-3 py-2 text-center">
                    <input type="checkbox" checked={isSelected(order.id)} onChange={() => handleSelect(order.id)} className="rounded" />
                  </td>
                  <td className="px-3 py-2 font-mono text-xs">{order.orderNo}</td>
                  <td className="px-3 py-2 font-mono text-xs">{order.quoteNo}</td>
                  <td className="px-3 py-2">{order.customerName}</td>
                  <td className="px-3 py-2 text-xs">{order.siteName}</td>
                  <td className="px-3 py-2 text-right font-mono">{formatCurrency(order.totalAmount)}</td>
                  <td className="px-3 py-2">{order.dueDate}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-1 rounded text-xs ${getStatusColor(order.status)}`}>{order.status}</span>
                  </td>
                  {hasSelection && (
                    <td className="px-3 py-2 text-center">
                      {isSelected(order.id) && (
                        <div className="flex items-center justify-center gap-1">
                          <button onClick={() => handleEdit(order)} className="p-1 hover:bg-gray-200 rounded" title="수정">
                            <Edit2 className="w-4 h-4 text-blue-600" />
                          </button>
                          <button onClick={() => handleDelete(order)} className="p-1 hover:bg-gray-200 rounded" title="삭제">
                            <Trash2 className="w-4 h-4 text-red-600" />
                          </button>
                        </div>
                      )}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  };

  // 생산 탭
  const ProductionTab = () => {
    const displayData = integratedWorkOrderMaster.slice(0, 30);
    const { selectedIds, handleSelect, handleSelectAll, isAllSelected, hasSelection, isMultiSelect, isSelected } = useListSelection(displayData);
    const handleEdit = (wo) => alert(`작업지시 수정: ${wo.workOrderNo}`);
    const handleDelete = (wo) => window.confirm(`${wo.workOrderNo} 작업지시를 삭제하시겠습니까?`) && alert(`작업지시 삭제: ${wo.workOrderNo}`);
    const handleBulkDelete = () => window.confirm(`선택한 ${selectedIds.length}건을 삭제하시겠습니까?`) && alert(`${selectedIds.length}건 삭제`);

    return (
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <div className="flex gap-2 text-sm flex-wrap">
            {['대기', '진행중', '완료'].map(status => (
              <span key={status} className={`px-2 py-1 rounded ${status === '완료' ? 'bg-green-100 text-green-800' :
                  status === '진행중' ? 'bg-yellow-100 text-yellow-800' :
                    'bg-gray-100 text-gray-800'
                }`}>
                {status}: {integratedWorkOrderMaster.filter(w => w.status === status).length}
              </span>
            ))}
          </div>
          {isMultiSelect && (
            <Button variant="danger" size="sm" onClick={handleBulkDelete}>
              <Trash2 className="w-4 h-4" /> 선택 삭제 ({selectedIds.length})
            </Button>
          )}
        </div>
        <div className="overflow-x-auto max-h-96">
          <table className="w-full text-sm">
            <thead className="bg-gray-100 sticky top-0">
              <tr>
                <th className="px-3 py-2 text-center w-10">
                  <input type="checkbox" checked={isAllSelected} onChange={handleSelectAll} className="rounded" />
                </th>
                <th className="px-3 py-2 text-left">작업지시번호</th>
                <th className="px-3 py-2 text-left">수주번호</th>
                <th className="px-3 py-2 text-left">공정</th>
                <th className="px-3 py-2 text-left">지시수량</th>
                <th className="px-3 py-2 text-left">생산수량</th>
                <th className="px-3 py-2 text-left">불량</th>
                <th className="px-3 py-2 text-left">상태</th>
                {hasSelection && <th className="px-3 py-2 text-center">작업</th>}
              </tr>
            </thead>
            <tbody>
              {displayData.map(wo => (
                <tr key={wo.id} className={`border-b hover:bg-gray-50 ${isSelected(wo.id) ? 'bg-blue-50' : ''}`}>
                  <td className="px-3 py-2 text-center">
                    <input type="checkbox" checked={isSelected(wo.id)} onChange={() => handleSelect(wo.id)} className="rounded" />
                  </td>
                  <td className="px-3 py-2 font-mono text-xs">{wo.workOrderNo}</td>
                  <td className="px-3 py-2 font-mono text-xs">{wo.orderNo}</td>
                  <td className="px-3 py-2">{wo.processName}</td>
                  <td className="px-3 py-2 text-center">{wo.qty}</td>
                  <td className="px-3 py-2 text-center">{wo.producedQty}</td>
                  <td className="px-3 py-2 text-center text-red-600">{wo.defectQty}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-1 rounded text-xs ${wo.status === '완료' ? 'bg-green-100 text-green-800' :
                        wo.status === '진행중' ? 'bg-yellow-100 text-yellow-800' :
                          'bg-gray-100 text-gray-800'
                      }`}>{wo.status}</span>
                  </td>
                  {hasSelection && (
                    <td className="px-3 py-2 text-center">
                      {isSelected(wo.id) && (
                        <div className="flex items-center justify-center gap-1">
                          <button onClick={() => handleEdit(wo)} className="p-1 hover:bg-gray-200 rounded" title="수정">
                            <Edit2 className="w-4 h-4 text-blue-600" />
                          </button>
                          <button onClick={() => handleDelete(wo)} className="p-1 hover:bg-gray-200 rounded" title="삭제">
                            <Trash2 className="w-4 h-4 text-red-600" />
                          </button>
                        </div>
                      )}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {integratedWorkOrderMaster.length > 30 && (
          <p className="text-sm text-gray-500 text-center">... 외 {integratedWorkOrderMaster.length - 30}건</p>
        )}
      </div>
    );
  };

  // 품질 탭
  const QualityTab = () => {
    const displayData = integratedQualityMaster.slice(0, 30);
    const { selectedIds, handleSelect, handleSelectAll, isAllSelected, hasSelection, isMultiSelect, isSelected } = useListSelection(displayData);
    const handleEdit = (insp) => alert(`검사 수정: ${insp.inspectionNo}`);
    const handleDelete = (insp) => window.confirm(`${insp.inspectionNo} 검사를 삭제하시겠습니까?`) && alert(`검사 삭제: ${insp.inspectionNo}`);
    const handleBulkDelete = () => window.confirm(`선택한 ${selectedIds.length}건을 삭제하시겠습니까?`) && alert(`${selectedIds.length}건 삭제`);

    return (
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <div className="flex gap-2 text-sm">
            <span className="px-2 py-1 bg-green-100 text-green-800 rounded">합격: {integratedQualityMaster.filter(q => q.result === '합격').length}</span>
            <span className="px-2 py-1 bg-red-100 text-red-800 rounded">불합격: {integratedQualityMaster.filter(q => q.result === '불합격').length}</span>
          </div>
          {isMultiSelect && (
            <Button variant="danger" size="sm" onClick={handleBulkDelete}>
              <Trash2 className="w-4 h-4" /> 선택 삭제 ({selectedIds.length})
            </Button>
          )}
        </div>
        <div className="overflow-x-auto max-h-96">
          <table className="w-full text-sm">
            <thead className="bg-gray-100 sticky top-0">
              <tr>
                <th className="px-3 py-2 text-center w-10">
                  <input type="checkbox" checked={isAllSelected} onChange={handleSelectAll} className="rounded" />
                </th>
                <th className="px-3 py-2 text-left">검사번호</th>
                <th className="px-3 py-2 text-left">작업지시</th>
                <th className="px-3 py-2 text-left">검사유형</th>
                <th className="px-3 py-2 text-left">검사항목</th>
                <th className="px-3 py-2 text-left">검사일</th>
                <th className="px-3 py-2 text-left">결과</th>
                {hasSelection && <th className="px-3 py-2 text-center">작업</th>}
              </tr>
            </thead>
            <tbody>
              {displayData.map(insp => (
                <tr key={insp.id} className={`border-b hover:bg-gray-50 ${isSelected(insp.id) ? 'bg-blue-50' : ''}`}>
                  <td className="px-3 py-2 text-center">
                    <input type="checkbox" checked={isSelected(insp.id)} onChange={() => handleSelect(insp.id)} className="rounded" />
                  </td>
                  <td className="px-3 py-2 font-mono text-xs">{insp.inspectionNo}</td>
                  <td className="px-3 py-2 font-mono text-xs">{insp.workOrderNo}</td>
                  <td className="px-3 py-2">{insp.inspectionType}</td>
                  <td className="px-3 py-2 text-xs">{insp.inspectionItems?.slice(0, 2).join(', ')}</td>
                  <td className="px-3 py-2">{insp.inspectionDate}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-1 rounded text-xs ${getStatusColor(insp.result)}`}>{insp.result}</span>
                  </td>
                  {hasSelection && (
                    <td className="px-3 py-2 text-center">
                      {isSelected(insp.id) && (
                        <div className="flex items-center justify-center gap-1">
                          <button onClick={() => handleEdit(insp)} className="p-1 hover:bg-gray-200 rounded" title="수정">
                            <Edit2 className="w-4 h-4 text-blue-600" />
                          </button>
                          <button onClick={() => handleDelete(insp)} className="p-1 hover:bg-gray-200 rounded" title="삭제">
                            <Trash2 className="w-4 h-4 text-red-600" />
                          </button>
                        </div>
                      )}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  };

  // 출하 탭
  const ShipmentTab = () => {
    const { selectedIds, handleSelect, handleSelectAll, isAllSelected, hasSelection, isMultiSelect, isSelected } = useListSelection(integratedShipmentMaster);
    const handleEdit = (ship) => alert(`출하 수정: ${ship.shipmentNo}`);
    const handleDelete = (ship) => window.confirm(`${ship.shipmentNo} 출하를 삭제하시겠습니까?`) && alert(`출하 삭제: ${ship.shipmentNo}`);
    const handleBulkDelete = () => window.confirm(`선택한 ${selectedIds.length}건을 삭제하시겠습니까?`) && alert(`${selectedIds.length}건 삭제`);

    return (
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <div className="flex gap-2 text-sm">
            <span className="px-2 py-1 bg-gray-100 rounded">출하대기: {integratedShipmentMaster.filter(s => s.status === '출하대기').length}</span>
            <span className="px-2 py-1 bg-blue-100 rounded">배송중: {integratedShipmentMaster.filter(s => s.status === '배송중').length}</span>
            <span className="px-2 py-1 bg-green-100 rounded">배송완료: {integratedShipmentMaster.filter(s => s.status === '배송완료').length}</span>
          </div>
          {isMultiSelect && (
            <Button variant="danger" size="sm" onClick={handleBulkDelete}>
              <Trash2 className="w-4 h-4" /> 선택 삭제 ({selectedIds.length})
            </Button>
          )}
        </div>
        <div className="overflow-x-auto max-h-96">
          <table className="w-full text-sm">
            <thead className="bg-gray-100 sticky top-0">
              <tr>
                <th className="px-3 py-2 text-center w-10">
                  <input type="checkbox" checked={isAllSelected} onChange={handleSelectAll} className="rounded" />
                </th>
                <th className="px-3 py-2 text-left">출하번호</th>
                <th className="px-3 py-2 text-left">수주번호</th>
                <th className="px-3 py-2 text-left">거래처</th>
                <th className="px-3 py-2 text-left">현장</th>
                <th className="px-3 py-2 text-left">출하일</th>
                <th className="px-3 py-2 text-left">상태</th>
                {hasSelection && <th className="px-3 py-2 text-center">작업</th>}
              </tr>
            </thead>
            <tbody>
              {integratedShipmentMaster.map(ship => (
                <tr key={ship.id} className={`border-b hover:bg-gray-50 ${isSelected(ship.id) ? 'bg-blue-50' : ''}`}>
                  <td className="px-3 py-2 text-center">
                    <input type="checkbox" checked={isSelected(ship.id)} onChange={() => handleSelect(ship.id)} className="rounded" />
                  </td>
                  <td className="px-3 py-2 font-mono text-xs">{ship.shipmentNo}</td>
                  <td className="px-3 py-2 font-mono text-xs">{ship.orderNo}</td>
                  <td className="px-3 py-2">{ship.customerName}</td>
                  <td className="px-3 py-2 text-xs">{ship.siteName}</td>
                  <td className="px-3 py-2">{ship.shipmentDate}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-1 rounded text-xs ${getStatusColor(ship.status)}`}>{ship.status}</span>
                  </td>
                  {hasSelection && (
                    <td className="px-3 py-2 text-center">
                      {isSelected(ship.id) && (
                        <div className="flex items-center justify-center gap-1">
                          <button onClick={() => handleEdit(ship)} className="p-1 hover:bg-gray-200 rounded" title="수정">
                            <Edit2 className="w-4 h-4 text-blue-600" />
                          </button>
                          <button onClick={() => handleDelete(ship)} className="p-1 hover:bg-gray-200 rounded" title="삭제">
                            <Trash2 className="w-4 h-4 text-red-600" />
                          </button>
                        </div>
                      )}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  };

  // 회계 탭
  const AccountingTab = () => (
    <div className="space-y-6">
      {/* 매출 */}
      <div>
        <h3 className="font-semibold mb-2 flex items-center gap-2">
          <TrendingUp className="w-5 h-5 text-pink-600" />
          매출 ({integratedSalesMaster.length}건)
        </h3>
        <div className="overflow-x-auto max-h-48">
          <table className="w-full text-sm">
            <thead className="bg-pink-50 sticky top-0">
              <tr>
                <th className="px-3 py-2 text-left">매출번호</th>
                <th className="px-3 py-2 text-left">거래처</th>
                <th className="px-3 py-2 text-right">공급가</th>
                <th className="px-3 py-2 text-right">VAT</th>
                <th className="px-3 py-2 text-right">합계</th>
                <th className="px-3 py-2 text-left">상태</th>
              </tr>
            </thead>
            <tbody>
              {integratedSalesMaster.slice(0, 10).map(sale => (
                <tr key={sale.id} className="border-b hover:bg-gray-50">
                  <td className="px-3 py-2 font-mono text-xs">{sale.salesNo}</td>
                  <td className="px-3 py-2">{sale.customerName}</td>
                  <td className="px-3 py-2 text-right font-mono">{formatCurrency(sale.supplyAmount)}</td>
                  <td className="px-3 py-2 text-right font-mono">{formatCurrency(sale.vatAmount)}</td>
                  <td className="px-3 py-2 text-right font-mono font-medium">{formatCurrency(sale.totalAmount)}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-1 rounded text-xs ${sale.paymentStatus === '수금완료' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                      }`}>{sale.paymentStatus}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 수금 */}
      <div>
        <h3 className="font-semibold mb-2 flex items-center gap-2">
          <DollarSign className="w-5 h-5 text-emerald-600" />
          수금 ({integratedCollectionMaster.length}건)
        </h3>
        <div className="overflow-x-auto max-h-48">
          <table className="w-full text-sm">
            <thead className="bg-emerald-50 sticky top-0">
              <tr>
                <th className="px-3 py-2 text-left">수금번호</th>
                <th className="px-3 py-2 text-left">매출번호</th>
                <th className="px-3 py-2 text-left">거래처</th>
                <th className="px-3 py-2 text-right">수금액</th>
                <th className="px-3 py-2 text-left">수금일</th>
                <th className="px-3 py-2 text-left">수금방법</th>
              </tr>
            </thead>
            <tbody>
              {integratedCollectionMaster.slice(0, 10).map(col => (
                <tr key={col.id} className="border-b hover:bg-gray-50">
                  <td className="px-3 py-2 font-mono text-xs">{col.collectionNo}</td>
                  <td className="px-3 py-2 font-mono text-xs">{col.salesNo}</td>
                  <td className="px-3 py-2">{col.customerName}</td>
                  <td className="px-3 py-2 text-right font-mono font-medium text-emerald-600">{formatCurrency(col.amount)}</td>
                  <td className="px-3 py-2">{col.collectionDate}</td>
                  <td className="px-3 py-2">{col.paymentMethod}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );

  // 전체 흐름 탭 (특정 건의 전체 프로세스 추적)
  const FlowTab = () => {
    const [selectedOrderId, setSelectedOrderId] = useState(integratedOrderMaster[0]?.id);
    const selectedOrder = integratedOrderMaster.find(o => o.id === selectedOrderId);

    if (!selectedOrder) return <div>수주 데이터가 없습니다.</div>;

    const relatedQuote = integratedQuoteMaster.find(q => q.id === selectedOrder.quoteId);
    const relatedCustomer = integratedCustomerMaster.find(c => c.id === selectedOrder.customerId);
    const relatedSite = integratedSiteMaster.find(s => s.id === selectedOrder.siteId);
    const relatedWorkOrders = integratedWorkOrderMaster.filter(w => w.orderId === selectedOrder.id);
    const relatedQuality = integratedQualityMaster.filter(q =>
      relatedWorkOrders.some(w => w.id === q.workOrderId)
    );
    const relatedShipment = integratedShipmentMaster.find(s => s.orderId === selectedOrder.id);
    const relatedSales = integratedSalesMaster.find(s => s.orderId === selectedOrder.id);
    const relatedCollection = relatedSales ? integratedCollectionMaster.find(c => c.salesId === relatedSales.id) : null;

    return (
      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <label className="text-sm font-medium">수주 선택:</label>
          <select
            className="border rounded px-3 py-1 text-sm"
            value={selectedOrderId}
            onChange={(e) => setSelectedOrderId(parseInt(e.target.value))}
          >
            {integratedOrderMaster.map(order => (
              <option key={order.id} value={order.id}>
                {order.orderNo} - {order.customerName} ({order.status})
              </option>
            ))}
          </select>
        </div>

        <div className="grid gap-4">
          {/* 거래처 정보 */}
          <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
            <h4 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
              <Building className="w-4 h-4" />
              1. 거래처
            </h4>
            {relatedCustomer && (
              <div className="text-sm grid grid-cols-2 md:grid-cols-4 gap-2">
                <span><strong>코드:</strong> {relatedCustomer.code}</span>
                <span><strong>명칭:</strong> {relatedCustomer.name}</span>
                <span><strong>등급:</strong> {relatedCustomer.creditGrade}</span>
                <span><strong>할인:</strong> {relatedCustomer.discountRate}%</span>
              </div>
            )}
          </div>

          {/* 현장 정보 */}
          <div className="bg-purple-50 p-4 rounded-lg border border-purple-200">
            <h4 className="font-semibold text-purple-800 mb-2 flex items-center gap-2">
              <MapPin className="w-4 h-4" />
              2. 현장
            </h4>
            {relatedSite && (
              <div className="text-sm grid grid-cols-2 md:grid-cols-4 gap-2">
                <span><strong>코드:</strong> {relatedSite.code}</span>
                <span><strong>현장명:</strong> {relatedSite.name}</span>
                <span><strong>담당자:</strong> {relatedSite.manager}</span>
                <span><strong>상태:</strong> {relatedSite.status}</span>
              </div>
            )}
          </div>

          {/* 견적 정보 */}
          <div className="bg-green-50 p-4 rounded-lg border border-green-200">
            <h4 className="font-semibold text-green-800 mb-2 flex items-center gap-2">
              <FileText className="w-4 h-4" />
              3. 견적
            </h4>
            {relatedQuote && (
              <div className="text-sm grid grid-cols-2 md:grid-cols-4 gap-2">
                <span><strong>번호:</strong> {relatedQuote.quoteNo}</span>
                <span><strong>일자:</strong> {relatedQuote.quoteDate}</span>
                <span><strong>금액:</strong> {formatCurrency(relatedQuote.finalAmount)}</span>
                <span><strong>상태:</strong> {relatedQuote.status}</span>
              </div>
            )}
          </div>

          {/* 수주 정보 */}
          <div className="bg-orange-50 p-4 rounded-lg border border-orange-200">
            <h4 className="font-semibold text-orange-800 mb-2 flex items-center gap-2">
              <Package className="w-4 h-4" />
              4. 수주
            </h4>
            <div className="text-sm grid grid-cols-2 md:grid-cols-4 gap-2">
              <span><strong>번호:</strong> {selectedOrder.orderNo}</span>
              <span><strong>일자:</strong> {selectedOrder.orderDate}</span>
              <span><strong>금액:</strong> {formatCurrency(selectedOrder.totalAmount)}</span>
              <span><strong>상태:</strong> <span className={`px-2 py-0.5 rounded ${getStatusColor(selectedOrder.status)}`}>{selectedOrder.status}</span></span>
            </div>
          </div>

          {/* 생산 정보 */}
          <div className="bg-yellow-50 p-4 rounded-lg border border-yellow-200">
            <h4 className="font-semibold text-yellow-800 mb-2 flex items-center gap-2">
              <Factory className="w-4 h-4" />
              5. 생산 ({relatedWorkOrders.length}건)
            </h4>
            <div className="text-sm space-y-1">
              {relatedWorkOrders.map(wo => (
                <div key={wo.id} className="flex items-center gap-2">
                  <span className="font-mono text-xs">{wo.workOrderNo}</span>
                  <span>{wo.processName}</span>
                  <span className={`px-2 py-0.5 rounded text-xs ${wo.status === '완료' ? 'bg-green-100 text-green-800' :
                      wo.status === '진행중' ? 'bg-yellow-100 text-yellow-800' :
                        'bg-gray-100'
                    }`}>{wo.status}</span>
                  <span className="text-gray-500">{wo.producedQty}/{wo.qty}</span>
                </div>
              ))}
            </div>
          </div>

          {/* 품질 정보 */}
          <div className="bg-indigo-50 p-4 rounded-lg border border-indigo-200">
            <h4 className="font-semibold text-indigo-800 mb-2 flex items-center gap-2">
              <ShieldCheck className="w-4 h-4" />
              6. 품질검사 ({relatedQuality.length}건)
            </h4>
            <div className="text-sm space-y-1">
              {relatedQuality.length > 0 ? relatedQuality.map(q => (
                <div key={q.id} className="flex items-center gap-2">
                  <span className="font-mono text-xs">{q.inspectionNo}</span>
                  <span>{q.inspectionType}</span>
                  <span className={`px-2 py-0.5 rounded text-xs ${getStatusColor(q.result)}`}>{q.result}</span>
                </div>
              )) : <span className="text-gray-500">검사 대기중</span>}
            </div>
          </div>

          {/* 출하 정보 */}
          <div className="bg-teal-50 p-4 rounded-lg border border-teal-200">
            <h4 className="font-semibold text-teal-800 mb-2 flex items-center gap-2">
              <Truck className="w-4 h-4" />
              7. 출하
            </h4>
            {relatedShipment ? (
              <div className="text-sm grid grid-cols-2 md:grid-cols-4 gap-2">
                <span><strong>번호:</strong> {relatedShipment.shipmentNo}</span>
                <span><strong>일자:</strong> {relatedShipment.shipmentDate}</span>
                <span><strong>운송:</strong> {relatedShipment.carrier}</span>
                <span><strong>상태:</strong> <span className={`px-2 py-0.5 rounded ${getStatusColor(relatedShipment.status)}`}>{relatedShipment.status}</span></span>
              </div>
            ) : <span className="text-sm text-gray-500">출하 대기중</span>}
          </div>

          {/* 매출/수금 정보 */}
          <div className="bg-pink-50 p-4 rounded-lg border border-pink-200">
            <h4 className="font-semibold text-pink-800 mb-2 flex items-center gap-2">
              <DollarSign className="w-4 h-4" />
              8. 매출/수금
            </h4>
            {relatedSales ? (
              <div className="text-sm space-y-2">
                <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
                  <span><strong>매출번호:</strong> {relatedSales.salesNo}</span>
                  <span><strong>공급가:</strong> {formatCurrency(relatedSales.supplyAmount)}</span>
                  <span><strong>VAT:</strong> {formatCurrency(relatedSales.vatAmount)}</span>
                  <span><strong>합계:</strong> {formatCurrency(relatedSales.totalAmount)}</span>
                </div>
                {relatedCollection && (
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-2 bg-emerald-100 p-2 rounded">
                    <span><strong>수금번호:</strong> {relatedCollection.collectionNo}</span>
                    <span><strong>수금액:</strong> {formatCurrency(relatedCollection.amount)}</span>
                    <span><strong>수금일:</strong> {relatedCollection.collectionDate}</span>
                    <span><strong>방법:</strong> {relatedCollection.paymentMethod}</span>
                  </div>
                )}
              </div>
            ) : <span className="text-sm text-gray-500">매출 미발생</span>}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="bg-white rounded-lg shadow-sm border p-6">
      <div className="space-y-3 mb-6">
        <h2 className="text-xl font-bold flex items-center gap-2">
          <Database className="w-6 h-6 text-blue-500" />
          통합 테스트 대시보드
        </h2>
        <span className="text-sm text-gray-500">
          거래처→현장→견적→수주→생산→품질→출하→회계 전 과정 연동
        </span>
      </div>

      {/* 탭 네비게이션 */}
      <div className="flex flex-wrap gap-1 mb-6 border-b pb-2">
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`flex items-center gap-1 px-3 py-2 rounded-t text-sm font-medium transition-colors ${activeTab === tab.id
                ? 'bg-blue-100 text-blue-800 border-b-2 border-blue-500'
                : 'text-gray-600 hover:bg-gray-100'
              }`}
          >
            <tab.icon className="w-4 h-4" />
            {tab.label}
          </button>
        ))}
      </div>

      {/* 탭 콘텐츠 */}
      <div>
        {activeTab === 'process-integration' && <ProcessIntegrationTestTab />}
        {activeTab === 'complete-integration' && <CompleteIntegrationTestTab />}
        {activeTab === 'full-integration' && <FullIntegrationTestTab />}
        {activeTab === 'workflow' && <WorkflowTestTab />}
        {activeTab === 'e2e-test' && <E2ETestTab />}
        {activeTab === 'summary' && <SummaryTab />}
        {activeTab === 'customers' && <CustomersTab />}
        {activeTab === 'quotes' && <QuotesTab />}
        {activeTab === 'orders' && <OrdersTab />}
        {activeTab === 'production' && <ProductionTab />}
        {activeTab === 'quality' && <QualityTab />}
        {activeTab === 'shipment' && <ShipmentTab />}
        {activeTab === 'accounting' && <AccountingTab />}
        {activeTab === 'flow' && <FlowTab />}
      </div>
    </div>
  );
};

// 단가 계산 분류 (카테고리 그룹)
const initialPriceClassifications = [
  { id: 1, name: '스크린 제품', description: '스크린 관련 모든 제품', categories: ['스크린', '오픈사이즈', '제작사이즈', '실리카', '와이어'], itemCount: 5 },
  { id: 2, name: '철재 제품', description: '철재 관련 모든 제품', categories: ['철재', '가이드레일', '케이스', '프레임'], itemCount: 4 },
  { id: 3, name: '전기 부품', description: '전기/전자 관련 부품', categories: ['모터', '제어기', '센서', '스위치'], itemCount: 4 },
  { id: 4, name: '기타 부자재', description: '기타 부자재 및 소모품', categories: ['볼트', '너트', '와셔', '접착제', '테이프'], itemCount: 5 },
];

// 단가 수식 연결
const initialPriceFormulas = [
  { id: 1, classificationId: 2, classificationName: '철재 제품', formula: 'W0 * H0 / 1000000', description: '철재 면적 기반 단가', isActive: true, qtyCalc: 'UP' },
];

// 수식 계산 엔진 (Enhanced)
const formulaEngine = {
  // 변수 저장소
  variables: {},

  // 룩업 테이블 참조
  lookupTables: {
    motorCapacityTable,
    bracketTable,
    shaftInchTableSteel,
    shaftInchTableScreen,
    shaftLengthTable,
    guideRailLengthTable,
    caseLengthTable,
    bottomBarTable,
    hwanbongQtyTable,
    squarePipeTableScreen,
    squarePipeTableSteel,
    subShaftTable,
  },

  // 변수 설정
  setVariable(name, value) {
    this.variables[name] = value;
  },

  // 변수 가져오기
  getVariable(name) {
    return this.variables[name] || 0;
  },

  // 조건 평가
  evaluateCondition(condition) {
    if (!condition) return true;
    try {
      let evalCondition = condition;
      for (const [key, value] of Object.entries(this.variables)) {
        const regex = new RegExp(`\\b${key}\\b`, 'g');
        evalCondition = evalCondition.replace(regex, typeof value === 'string' ? `'${value}'` : value);
      }
      return Function('"use strict";return (' + evalCondition + ')')();
    } catch (e) {
      console.error('Condition evaluation error:', condition, e);
      return false;
    }
  },

  // 수식 평가
  evaluate(formula) {
    if (!formula || formula === '-' || formula === '') return null;

    try {
      // 변수 치환
      let evalFormula = formula;
      for (const [key, value] of Object.entries(this.variables)) {
        const regex = new RegExp(`\\b${key}\\b`, 'g');
        evalFormula = evalFormula.replace(regex, typeof value === 'string' ? `'${value}'` : value);
      }

      // 내장 함수 치환
      evalFormula = evalFormula
        .replace(/CEIL\(/g, 'Math.ceil(')
        .replace(/FLOOR\(/g, 'Math.floor(')
        .replace(/ROUND\(/g, 'Math.round(')
        .replace(/IF\(/g, '((')
        .replace(/SUM\(/g, '(')
        .replace(/MAX\(/g, 'Math.max(')
        .replace(/MIN\(/g, 'Math.min(');

      // 평가
      const result = Function('"use strict";return (' + evalFormula + ')')();
      return isNaN(result) ? 0 : result;
    } catch (e) {
      console.error('Formula evaluation error:', formula, e);
      return 0;
    }
  },

  // 룩업 테이블 평가 (새 테이블 형식 지원)
  evaluateLookup(lookupTable, params) {
    const { W1, K, PC, S, B, G } = params;
    const productType = PC === '스크린' ? 'screen' : 'steel';

    switch (lookupTable) {
      case 'motorCapacityTable': {
        // 샤프트 인치 결정
        const shaftInch = this.getShaftInch(W1, K, productType);
        this.setVariable('SHAFT_INCH', shaftInch);

        // 모터 용량 결정
        const table = motorCapacityTable[productType]?.[String(shaftInch)];
        if (!table) return { motor: 300, shaftInch };

        for (const row of table) {
          if (K >= row.min && K <= row.max) {
            return { motor: row.motor, shaftInch };
          }
        }
        return { motor: table[table.length - 1]?.motor || 300, shaftInch };
      }

      case 'bracketTable': {
        const motorKG = this.getVariable('MOTOR_KG') || 300;
        const bracket = bracketTable[productType]?.[String(motorKG)];
        return bracket || bracketTable.screen['150'];
      }

      case 'shaftLengthTable': {
        // 인치별 W1 구간에 따라 샤프트 자재 길이 결정
        const shaftInch = this.getVariable('SHAFT_INCH') || '5';
        const inchTable = shaftLengthTable[String(shaftInch)];
        if (inchTable) {
          for (const row of inchTable) {
            if (W1 >= row.w1Min && W1 < row.w1Max) {
              return row.length;
            }
          }
        }
        return 8200; // default max
      }

      case 'guideRailLengthTable': {
        // G값에 따라 가이드레일 자재 길이 결정
        for (const row of guideRailLengthTable) {
          if (G >= row.gMin && G < row.gMax) {
            // materials 배열에서 자재 정보 추출
            const materials = row.materials || [{ length: row.length || 3000, qty: 2 }];
            const primaryMat = materials[0];
            return {
              length: primaryMat.length,
              qty: materials.reduce((sum, m) => sum + m.qty, 0),
              materials: materials,
              code: `RC${Math.floor(primaryMat.length / 100)}`
            };
          }
        }
        return { length: 4300, qty: 2, code: 'RC43' };
      }

      case 'caseLengthTable': {
        // S값에 따라 케이스 자재 길이/수량 결정
        for (const row of caseLengthTable) {
          if (S >= row.sMin && S < row.sMax) {
            const materials = row.materials || [{ length: row.length, qty: row.qty || 1 }];
            const primaryMat = materials[0];
            return {
              length: primaryMat.length,
              qty: row.qty || materials.reduce((sum, m) => sum + m.qty, 0),
              materials: materials,
              combo: row.combo || null,
              code: `CB${Math.floor(primaryMat.length / 100)}`
            };
          }
        }
        return { length: 1219, qty: 1, code: 'CB12' };
      }

      case 'bottomBarLengthTable': {
        // B값에 따라 하장바 자재 길이/수량 결정
        for (const row of bottomBarTable) {
          if (B >= row.bMin && B < row.bMax) {
            const materials = row.materials || [{ length: 3000, qty: 1 }];
            const totalQty = materials.reduce((sum, m) => sum + m.qty, 0);
            return {
              length: materials[0].length,
              materials: materials,
              barQty: totalQty,
              elbarQty: totalQty * 2,  // 엘바는 2량1세트
              reinforceQty: totalQty,
              combo: row.combo || null
            };
          }
        }
        return { length: 4000, barQty: 2, elbarQty: 4, reinforceQty: 2 };
      }

      case 'hwanbongQtyTable': {
        // W1값에 따라 환봉 수량 결정 (스크린 전용)
        for (const row of hwanbongQtyTable) {
          if (W1 >= row.w1Min && W1 < row.w1Max) {
            return row.qty;
          }
        }
        return 4;
      }

      case 'squarePipeTable': {
        // S값에 따라 각파이프 수량 결정 (스크린/철재 구분)
        const table = productType === 'screen' ? squarePipeTableScreen : squarePipeTableSteel;
        for (const row of table) {
          if (S >= row.lMin && S < row.lMax) {
            return { qty3000: row.mat3000, qty6000: row.mat6000 };
          }
        }
        return { qty3000: 3, qty6000: 0 };
      }

      default:
        return null;
    }
  },

  // 샤프트 인치 결정 (W1, K, 제품유형 기반) - 새 테이블 형식 지원
  getShaftInch(W1, K, productType) {
    // 철재는 W1과 K 두 조건 모두 만족해야 함
    if (productType === 'steel') {
      for (const row of shaftInchTableSteel) {
        if (W1 >= row.w1Min && W1 < row.w1Max && K >= row.kMin && K < row.kMax) {
          return row.inch;
        }
      }
      return '5'; // 철재 기본값
    }

    // 스크린은 W1 기준으로만 결정
    for (const row of shaftInchTableScreen) {
      if (W1 >= row.w1Min && W1 < row.w1Max) {
        return row.inch;
      }
    }
    return '5'; // 스크린 기본값
  },

  // 동적 품목코드 생성
  generateItemCode(template, params) {
    let code = template;
    for (const [key, value] of Object.entries(params)) {
      code = code.replace(`{${key}}`, value);
    }
    return code;
  },

  // 견적 품목 산출 (Enhanced)
  calculateQuoteItems(inputs, formulas, priceList) {
    // 입력값 설정
    this.variables = { ...inputs };

    // 기본 변수 설정
    const PC = inputs.PC || '스크린';
    const W0 = inputs.W0 || 2000;
    const H0 = inputs.H0 || 2500;
    const QTY = inputs.QTY || 1;
    const V = inputs.V || '220';
    const WIRE = inputs.WIRE || '유선';
    const CT = inputs.CT || '매립';
    const GT = inputs.GT || '벽면형';

    this.setVariable('PC', PC);
    this.setVariable('QTY', QTY);
    this.setVariable('V', V);
    this.setVariable('WIRE', WIRE);
    this.setVariable('CT', CT);
    this.setVariable('GT', GT);

    // 제작사이즈 계산
    const W1 = PC === '스크린' ? W0 + 140 : W0 + 110;
    const H1 = H0 + 350;
    this.setVariable('W0', W0);
    this.setVariable('H0', H0);
    this.setVariable('W1', W1);
    this.setVariable('H1', H1);

    // 면적 및 중량 계산
    const M = (W1 * H1) / 1000000;
    const K = PC === '스크린' ? (M * 2) + (W0 * 14.17 / 1000) : M * 25;
    this.setVariable('M', M);
    this.setVariable('K', K);

    // 주요 제작 사이즈
    const S = W1; // 케이스 제작사이즈
    const B = W0; // 하단마감재 제작사이즈
    const G = H0 + 250; // 가이드레일 제작길이
    this.setVariable('S', S);
    this.setVariable('B', B);
    this.setVariable('G', G);

    // 룩업 테이블 평가
    const lookupParams = { W1, K, PC, S, B, G };

    // 모터 용량 결정
    const motorResult = this.evaluateLookup('motorCapacityTable', lookupParams);
    const MOTOR_KG = motorResult.motor;
    const SHAFT_INCH = motorResult.shaftInch;
    this.setVariable('MOTOR_KG', MOTOR_KG);
    this.setVariable('SHAFT_INCH', SHAFT_INCH);

    // 브라켓/앵글 규격
    const bracketResult = this.evaluateLookup('bracketTable', lookupParams);
    this.setVariable('BRACKET_SPEC', bracketResult.bracket);
    this.setVariable('ANGLE_SPEC', bracketResult.angle);
    this.setVariable('BRACKET_CODE', bracketResult.bracketCode);
    this.setVariable('ANGLE_CODE', bracketResult.angleCode);

    // 샤프트 자재 길이
    const shaftLength = this.evaluateLookup('shaftLengthTable', lookupParams);
    this.setVariable('MAIN_SHAFT_LEN', shaftLength);

    // 가이드레일 자재 길이
    const grResult = this.evaluateLookup('guideRailLengthTable', lookupParams);
    this.setVariable('GR_MAT_LEN', grResult.length);
    this.setVariable('GR_CODE', grResult.code);

    // 케이스 자재 길이/수량
    const caseResult = this.evaluateLookup('caseLengthTable', lookupParams);
    this.setVariable('CASE_MAT_LEN', caseResult.length);
    this.setVariable('CASE_MAT_QTY', caseResult.qty);
    this.setVariable('CASE_CODE', caseResult.code);

    // 하장바/엘바/보강평철
    const bottomResult = this.evaluateLookup('bottomBarLengthTable', lookupParams);
    this.setVariable('HJ_MAT_LEN', bottomResult.length);
    this.setVariable('HJ_QTY', bottomResult.barQty);
    this.setVariable('ELBAR_QTY', bottomResult.elbarQty);
    this.setVariable('REINFORCE_QTY', bottomResult.reinforceQty);

    // 환봉 수량 (스크린 전용)
    if (PC === '스크린') {
      const hwanbongQty = this.evaluateLookup('hwanbongQtyTable', lookupParams);
      this.setVariable('HWANBONG_QTY', hwanbongQty);
    }

    // 각파이프 수량
    const sqpResult = this.evaluateLookup('squarePipeTable', lookupParams);
    this.setVariable('SQP3000_QTY', sqpResult.qty3000);
    this.setVariable('SQP6000_QTY', sqpResult.qty6000);

    // 추가 수식 계산
    const TOP_COVER_QTY = Math.ceil(S / 1219);
    const CASE_SMOKE_QTY = Math.ceil(S / 3000) * 2;
    const JOINTBAR_QTY = 2 + Math.floor((W1 - 500) / 1000);
    const WEIGHT_FLAT_QTY = PC === '스크린' ? Math.ceil(B / 2000) * 2 : 0;
    const SUB_SHAFT_LEN = W1 <= 8200 ? 300 : 500;

    this.setVariable('TOP_COVER_QTY', TOP_COVER_QTY);
    this.setVariable('CASE_SMOKE_QTY', CASE_SMOKE_QTY);
    this.setVariable('JOINTBAR_QTY', JOINTBAR_QTY);
    this.setVariable('WEIGHT_FLAT_QTY', WEIGHT_FLAT_QTY);
    this.setVariable('SUB_SHAFT_LEN', SUB_SHAFT_LEN);

    // 동적 품목 코드 생성
    const MOTOR_CODE = `E-${MOTOR_KG}K${V}V-${WIRE === '유선' ? 'W' : 'R'}`;
    const CTL_CODE = `CTL-${CT === '매립' ? 'EMBED' : 'EXPOSE'}-${WIRE === '유선' ? 'W' : 'R'}`;
    this.setVariable('MOTOR_CODE', MOTOR_CODE);
    this.setVariable('CTL_CODE', CTL_CODE);

    // 출력 품목 생성
    const outputItems = [];
    const addItem = (code, name, spec, qty, category, process) => {
      const priceItem = priceList.find(p => p.itemCode === code || p.itemCode.startsWith(code.split('-')[0] + '-'));
      const unitPrice = priceItem?.sellingPrice || 0;
      const itemQty = Math.ceil(qty * QTY);
      if (itemQty > 0) {
        outputItems.push({
          id: Date.now() + outputItems.length + Math.random(),
          itemCode: code,
          itemName: name,
          spec,
          qty: itemQty,
          unit: priceItem?.unit || 'EA',
          unitPrice,
          amount: itemQty * unitPrice,
          category,
          process,
        });
      }
    };

    // === 구매부품 ===
    // 전동개폐기
    addItem(MOTOR_CODE, `전동개폐기 ${MOTOR_KG}KG ${V}V ${WIRE}`, `${MOTOR_KG}KG/${V}V`, 1, 'purchased-parts', '조립');

    // 연동제어기
    addItem(CTL_CODE, `연동제어기 ${CT}형 ${WIRE}`, `${CT}/${WIRE}`, 1, 'purchased-parts', '조립');

    // 브라켓/앵글
    addItem(bracketResult.bracketCode, `브라켓 ${bracketResult.bracket}`, bracketResult.bracket, 1, 'bracket-angle', '조립');
    addItem(bracketResult.angleCode, `받침용앵글 ${bracketResult.angle}`, bracketResult.angle, 1, 'bracket-angle', '조립');

    // === 감기샤프트 ===
    // 메인샤프트
    addItem(`SHAFT-${SHAFT_INCH}IN-${shaftLength}`, `감기샤프트(메인) ${SHAFT_INCH}인치`, `${SHAFT_INCH}인치 L:${shaftLength}`, 1, 'shaft', '샤프트');

    // 보조샤프트 (스크린 전용)
    if (PC === '스크린') {
      addItem(`SHAFT-SUB-3-${SUB_SHAFT_LEN}`, `감기샤프트(보조) 3인치`, `3인치 L:${SUB_SHAFT_LEN}`, 1, 'shaft', '샤프트');
    }

    // === 가이드레일 ===
    addItem(grResult.code, `가이드레일`, `L:${grResult.length}mm`, 2, 'guide-rail', '절곡');

    // 하부 BASE
    const baseCode = GT === '벽면형' ? 'BP-BASE-WALL' : 'BP-BASE-CORNER';
    addItem(baseCode, `하부BASE(${GT})`, GT, 1, 'guide-rail', '절곡');

    // === 연기차단재 ===
    const smokeQty = PC === '스크린' ? 2 : 1;
    addItem('BP-SMOKE', '연기차단재', `L:${G}mm`, smokeQty, 'smoke-block', '절곡');

    // === 셔터박스(케이스) ===
    addItem(caseResult.code, '케이스판재', `L:${caseResult.length}mm`, caseResult.qty, 'shutter-box', '절곡');
    addItem('BP-MARG', '마구리', '1SET=2EA', 1, 'shutter-box', '절곡');
    addItem('BP-TOPCOVER', '상부덮개', 'L:1219mm', TOP_COVER_QTY, 'shutter-box', '절곡');
    addItem('BP-CASE-SMOKE', '케이스용연기차단재', 'L:3000mm', CASE_SMOKE_QTY, 'shutter-box', '절곡');

    // === 하단마감재 ===
    const hjCode = bottomResult.length === 3000 ? 'BP-HJ-30' : 'BP-HJ-40';
    addItem(hjCode, `하장바 60×${PC === '스크린' ? '40' : '30'}`, `L:${bottomResult.length}mm`, bottomResult.barQty, 'bottom-finish', '절곡');

    if (PC === '스크린') {
      const elCode = bottomResult.length === 3000 ? 'BP-ELBAR-30' : 'BP-ELBAR-40';
      addItem(elCode, '엘바 17×60', `L:${bottomResult.length}mm`, bottomResult.elbarQty, 'bottom-finish', '절곡');

      const reCode = bottomResult.length === 3000 ? 'BP-REINFORCE-30' : 'BP-REINFORCE-40';
      addItem(reCode, '보강평철 50mm', `L:${bottomResult.length}mm`, bottomResult.reinforceQty, 'bottom-finish', '절곡');

      addItem('BP-WEIGHT-20', '무게평철 50×12T', 'L:2000mm', WEIGHT_FLAT_QTY, 'bottom-finish', '절곡');
    }

    // === 부자재 ===
    if (PC === '스크린') {
      addItem('SM-HWANBONG-30', '환봉', 'L:3000mm', this.getVariable('HWANBONG_QTY'), 'sub-material', '스크린');
    }
    addItem('SM-JOINTBAR', '조인트바', '', JOINTBAR_QTY, 'sub-material', '샤프트');
    addItem('SQP-30-30', '각파이프 30×30', 'L:3000mm', sqpResult.qty3000, 'sub-material', '조립');
    addItem('SQP-30-60', '각파이프 30×30', 'L:6000mm', sqpResult.qty6000, 'sub-material', '조립');

    // === 검사비 ===
    addItem('INSP-FEE', '검사비', '', 1, 'purchased-parts', '검사');

    return {
      variables: { ...this.variables },
      items: outputItems,
      totalAmount: outputItems.reduce((sum, item) => sum + item.amount, 0),
      summary: {
        productType: PC,
        openSize: `${W0} × ${H0}`,
        productionSize: `${W1} × ${H1}`,
        area: M.toFixed(2),
        weight: K.toFixed(2),
        motorCapacity: `${MOTOR_KG}KG`,
        shaftInch: `${SHAFT_INCH}인치`,
        qty: QTY,
      }
    };
  },
};

// ============ 공정 마스터 데이터 ============
const sampleProcesses = [
  {
    id: 1,
    processCode: 'P-001',
    processName: '스크린',
    processType: '생산',
    department: '스크린생산부서',
    equipment: '미싱기 3대, 절단기 1대',
    personnel: 3,
    workSheetType: 'WL-SCR',
    isActive: true,
    description: '방화스크린 원단 가공 및 조립',
    workSteps: ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'],
    assignedWorkers: ['김스크린', '이스크린', '박스크린'], // 배정된 작업자
    createdAt: '2025-01-01',
    updatedAt: '2025-01-15',
  },
  {
    id: 2,
    processCode: 'P-002',
    processName: '절곡',
    processType: '생산',
    department: '절곡생산부서',
    equipment: '절곡기 2대, 용접기 1대',
    personnel: 4,
    workSheetType: 'WL-FLD',
    isActive: true,
    description: '가이드레일, 케이스, 하단마감재 제작',
    workSteps: ['가이드레일 제작', '케이스 제작', '하단마감재 제작', '검사'],
    assignedWorkers: ['김절곡', '이절곡', '박절곡', '최절곡'], // 배정된 작업자
    createdAt: '2025-01-01',
    updatedAt: '2025-01-15',
  },
  {
    id: 3,
    processCode: 'P-003',
    processName: '슬랫',
    processType: '생산',
    department: '슬랫생산부서',
    equipment: '코일절단기 1대, 성형기 2대',
    personnel: 3,
    workSheetType: 'WL-SLT',
    isActive: true,
    description: '슬랫 코일 절단 및 성형',
    workSteps: ['코일절단', '성형', '미미작업', '검사', '포장'],
    assignedWorkers: ['김슬랫', '이슬랫', '박슬랫'], // 배정된 작업자
    createdAt: '2025-01-01',
    updatedAt: '2025-01-15',
  },
  {
    id: 4,
    processCode: 'P-004',
    processName: '재고(포밍)',
    processType: '생산',
    department: '포밍생산부서',
    equipment: '포밍기, 프레스, 바코드스캐너',
    personnel: 2,
    workSheetType: 'WL-STK',
    isActive: true,
    description: '철판을 포밍하여 절곡 부품(반제품) 생산 후 재고 입고',
    workSteps: ['포밍', '검사', '포장'],
    assignedWorkers: ['김포밍', '이포밍'], // 배정된 작업자
    createdAt: '2025-01-01',
    updatedAt: '2025-01-15',
  },
];

// 샘플 상세 발주서 데이터 (용산고등학교 현장)
const sampleDetailedOrderData = {
  // 기본 정보
  orderInfo: {
    lotNo: 'KD-WE-251015-01-(3)',
    productName: '국민방화스크린셔터스테',
    productType: 'KWE01',
    certNo: 'FDS-OTS23-0117-4',
    orderDate: '2025-10-15',
    siteName: '용산고등학교(4층)',
    customerName: '주말건설',
    dueDate: '2025-10-30',
    receiverManager: '오전식반장',
    receiverContact: '010-6414-7929',
    orderManager: '김명현과장',
    deliveryDate: '2025-10-29',
    totalQty: 11, // 셔터총수량
    deliveryMethod: '선배',
    deliveryAddress: '경기도 용인시 처인구 고림동 320-8 용산고등학교',
  },

  // 1. 스크린 품목 테이블
  screenItems: [
    { seq: 1, type: '와이어', drawingNo: '4층 FSS1', openWidth: 7260, openHeight: 2600, prodWidth: 7400, prodHeight: 2950, guideRailType: '백면형', guideRailSpec: '120-70', shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감' },
    { seq: 2, type: '와이어', drawingNo: '4층 FSS5', openWidth: 4560, openHeight: 2600, prodWidth: 4700, prodHeight: 2950, guideRailType: '백면형', guideRailSpec: '120-70', shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감' },
    { seq: 3, type: '와이어', drawingNo: 'FSS17A', openWidth: 6650, openHeight: 2600, prodWidth: 6790, prodHeight: 2950, guideRailType: '백면형', guideRailSpec: '120-70', shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감' },
    { seq: 4, type: '와이어', drawingNo: '4층 FSS3', openWidth: 3560, openHeight: 2600, prodWidth: 3700, prodHeight: 2950, guideRailType: '백면형', guideRailSpec: '120-70', shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감' },
    { seq: 5, type: '와이어', drawingNo: '4층 FSS7', openWidth: 5860, openHeight: 2600, prodWidth: 6000, prodHeight: 2950, guideRailType: '백면형', guideRailSpec: '120-70', shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감' },
    { seq: 6, type: '와이어', drawingNo: '4층 FSS16', openWidth: 7160, openHeight: 2600, prodWidth: 7300, prodHeight: 2950, guideRailType: '백면형', guideRailSpec: '120-70', shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감' },
    { seq: 7, type: '와이어', drawingNo: '4층 FSS3-2', openWidth: 3560, openHeight: 2600, prodWidth: 3700, prodHeight: 2950, guideRailType: '백면형', guideRailSpec: '120-70', shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감' },
    { seq: 8, type: '와이어', drawingNo: '4층 FSS6', openWidth: 5760, openHeight: 2600, prodWidth: 5900, prodHeight: 2950, guideRailType: '백면형', guideRailSpec: '120-70', shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감' },
    { seq: 9, type: '와이어', drawingNo: '4층 FSS3-3', openWidth: 3770, openHeight: 2600, prodWidth: 3910, prodHeight: 2950, guideRailType: '백면형', guideRailSpec: '120-70', shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감' },
    { seq: 10, type: '와이어', drawingNo: '4층 FSS17', openWidth: 7260, openHeight: 2600, prodWidth: 7400, prodHeight: 2950, guideRailType: '백면형', guideRailSpec: '120-70', shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감' },
    { seq: 11, type: '와이어', drawingNo: '4층 FSS15', openWidth: 6860, openHeight: 2600, prodWidth: 7000, prodHeight: 2950, guideRailType: '백면형', guideRailSpec: '120-70', shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감' },
  ],

  // 2. 모터/전장품
  motorSpec: {
    motors220V: [
      { model: 'KD-150K', qty: 0 },
      { model: 'KD-300K', qty: 0 },
      { model: 'KD-400K', qty: 0 },
    ],
    motors380V: [
      { model: 'KD-150K', qty: 6 },
      { model: 'KD-300K', qty: 5 },
      { model: 'KD-400K', qty: 0 },
    ],
    brackets: [
      { spec: '380-180 [2-4"]', qty: 0 },
      { spec: '380-180 [2-5"]', qty: 5 },
    ],
    heatSinks: [
      { spec: '40-60', qty: 44 },
      { spec: 'L-380', qty: 0 },
    ],
    controllers: [
      { type: '매입형', qty: 0 },
      { type: '노출형', qty: 0 },
      { type: '핫라스', qty: 0 },
    ],
  },

  // 3. 절곡물 BOM
  bomData: {
    // 3-1. 가이드레일 (EGI 1.55T + 마감재 EGI 1.15T + 별도마감재 SUS 1.15T)
    guideRails: {
      description: '가이드레일 - EGI 1.55T + 마감재 EGI 1.15T + 별도마감재 SUS 1.15T',
      items: [
        // 백면형 (120-70)
        {
          type: '백면형', spec: '120-70', code: 'KSS01', lengths: [
            { length: 4300, qty: 0 },
            { length: 3500, qty: 0 },
          ]
        },
        {
          type: '백면형', spec: '120-70', code: 'KSE01/KWE01', lengths: [
            { length: 3000, qty: 22 },
            { length: 2438, qty: 0 },
          ]
        },
        // 측면형 (120-120)
        {
          type: '측면형', spec: '120-120', code: 'KSS01', lengths: [
            { length: 4300, qty: 0 },
            { length: 4000, qty: 0 },
            { length: 3500, qty: 0 },
            { length: 3000, qty: 0 },
            { length: 2438, qty: 0 },
          ]
        },
        // 하부BASE
        {
          type: '하부BASE', spec: '130-80', code: '', lengths: [
            { length: 0, qty: 22 },
          ]
        },
      ],
      smokeBarrier: { // 연기차단재
        spec: 'W80',
        material: '원 0.8T 화이바글라스크탑직물',
        lengths: [
          { length: 2438, qty: 44 },
        ],
        note: '* 전면부, 린텔부 양쪽에 설치',
      },
    },

    // 3-2. 케이스(셔터박스) - EGI 1.55T
    cases: {
      description: '케이스(셔터박스) - EGI 1.55T',
      mainSpec: '500-330 (150,300,400/K용)',
      items: [
        { length: 4150, qty: 1 },
        { length: 4000, qty: 7 },
        { length: 3500, qty: 5 },
        { length: 3000, qty: 3 },
        { length: 2438, qty: 3 },
        { length: 1219, qty: 0 },
      ],
      sideCover: { spec: '500-355', qty: 22 }, // 측면덮개
      topCover: { qty: 3 }, // 상부덮개
      extension: { spec: '1219+무게', qty: 59 },
      smokeBarrier: { spec: 'W80', length: 3000, qty: 47 }, // 연기차단재
    },

    // 3-3. 하단마감재
    bottomFinish: {
      description: '하단마감재 - 마단마감재(EGI 1.55T) + 하단보강별바(EGI 1.55T) + 하단 보강횡철(EGI 1.15T) + 하단 부재횡철(50-12T)',
      items: [
        {
          name: '하단마감재', spec: '50-40', lengths: [
            { length: 4000, qty: 11 },
            { length: 3000, qty: 8 },
          ]
        },
        {
          name: '하단보강빔바', spec: '80-17', lengths: [
            { length: 4000, qty: 28 },
            { length: 3000, qty: 12 },
          ]
        },
        {
          name: '하단보강철', spec: '', lengths: [
            { length: 4000, qty: 13 },
            { length: 3000, qty: 0 },
          ]
        },
        {
          name: '하단부재횡철', spec: '50-12T', lengths: [
            { length: 2000, qty: 67 },
          ]
        },
      ],
    },
  },
};

// 수주 (로트번호 = 수주번호 = 모든 추적의 기준)
// ⚠️ 배열 순서: 최신 등록일 순 (내림차순) - 가장 최근 수주가 맨 앞에 위치
// 채번규칙: SO-YYMMDD-## (수주확인서), QT-YYMMDD-## (견적서), WO-YYMMDD-## (작업지시서)
// 현장코드: S-### (현장), 거래처코드: CUS-### (고객)
const initialOrders = [
  /*
   * ============================================================
   * 📋 수주 데이터 - 8개 테스트 시나리오 (최신순 정렬)
   * - customerMasterConfig.sampleCustomers 기준 (거래처 연동)
   * - siteMasterConfig.sampleSites 기준 (현장 연동)
   * - 채번규칙: 스크린=KD-TS, 슬랫=KD-SL, 절곡=KD-BD + YYMMDD-##
   * ============================================================
   * [최신] KD-TS-251210-01 (용산고등학교 - 직접수주) → 생산중
   * [2] KD-TS-251208-01 (현대건설 - 힐스테이트 용인) → 생산중
   * [3] KD-TS-251207-01 (삼성물산 - 래미안 강남 2차) → 재작업중
   * [4] KD-TS-251206-01 (서울인테리어 - 강남 오피스타워) → 분할 진행중
   * [5] KD-TS-251205-01 (삼성물산 추가분, 래미안 강남 1차) → 생산중
   * [6] KD-TS-251204-01 (대우건설 - 푸르지오 일산) → 경리승인 대기
   * [7] KD-TS-251203-01 (현대건설 - 힐스테이트 판교) → 생산완료, 출고보류
   * [8] KD-TS-251201-01 (삼성물산 - 래미안 강남 1차) → 생산지시완료
   * ============================================================
   */

  // ========== 시나리오 1: A등급 정상 플로우 (삼성물산 - 래미안 강남 1차) ==========
  {
    id: 1,
    orderNo: 'KD-TS-251201-01',
    lotNo: 'KD-TS-251201-01',
    orderDate: '2025-12-01',
    quoteId: 1,
    quoteNo: 'KD-PR-251201-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 1,  // 삼성물산(주) - customerMasterConfig.sampleCustomers[0]
    customerCode: 'CUS-001',
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteId: 1,  // siteMasterConfig.sampleSites[0]
    siteName: '삼성물산 래미안 강남 1차',
    siteCode: 'PJ-250110-01',
    manager: '이건설',
    contact: '010-1111-1111',
    dueDate: '2025-12-20',
    scheduledShipDate: '2025-12-18',  // 출고예정일
    status: '생산지시완료',
    paymentStatus: '전액입금',
    // 회계 상태 (A등급: 자동 진행)
    accountingStatus: '회계확인완료',
    accountingConfirmedBy: '회계팀 박회계',
    accountingConfirmedAt: '2025-02-06 10:00',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    // 거래명세서/세금계산서
    invoiceIssued: true,
    invoiceIssuedAt: '2025-02-05 15:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-02-05 15:30',
    // 금액
    totalAmount: 52000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 52000000,
    paidAmount: 52000000,
    remainingAmount: 0,
    deliveryMethod: '상차',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    receiverName: '이건설',
    receiverPhone: '010-1111-1111',
    // 품목 목록 (상세 제작 스펙 포함)
    items: [
      {
        id: 1,
        productCode: 'SCR-001',
        productName: '스크린 셔터 (표준형)',
        floor: '1층',
        location: 'A-01',
        spec: '7660×2550',
        qty: 1,
        unit: 'EA',
        unitPrice: 35000000,
        amount: 35000000,
        // 상세 제작 스펙 (발주서 양식)
        productionSpec: {
          type: '와이어',
          drawingNo: '1층 FSS1',
          openWidth: 7660,
          openHeight: 2550,
          prodWidth: 7800,
          prodHeight: 2950,
          guideRailType: '백면형',
          guideRailSpec: '120-70',
          shaft: 5,
          caseSpec: '500-330',
          motorBracket: '380-180',
          capacity: 300,
          finish: 'SUS마감',
        },
      },
      {
        id: 2,
        productCode: 'SCR-001',
        productName: '스크린 셔터 (표준형)',
        floor: '1층',
        location: 'A-02',
        spec: '6500×2400',
        qty: 1,
        unit: 'EA',
        unitPrice: 17000000,
        amount: 17000000,
        productionSpec: {
          type: '와이어',
          drawingNo: '1층 FSS2',
          openWidth: 6500,
          openHeight: 2400,
          prodWidth: 6640,
          prodHeight: 2950,
          guideRailType: '백면형',
          guideRailSpec: '120-70',
          shaft: 4,
          caseSpec: '500-330',
          motorBracket: '380-180',
          capacity: 160,
          finish: 'SUS마감',
        },
      },
    ],
    // 모터/전장품 스펙
    motorSpec: {
      motors220V: [
        { model: 'KD-150K', qty: 0 },
        { model: 'KD-300K', qty: 0 },
      ],
      motors380V: [
        { model: 'KD-150K', qty: 1 },
        { model: 'KD-300K', qty: 1 },
      ],
      brackets: [
        { spec: '380-180 [2-5"]', qty: 2 },
      ],
      heatSinks: [
        { spec: '40-60', qty: 4 },
      ],
      controllers: [
        { type: '매입형', qty: 0 },
        { type: '노출형', qty: 0 },
      ],
    },
    // 절곡물 BOM (자동 계산된 자재 소요량)
    bomData: {
      guideRails: {
        items: [
          {
            type: '백면형', spec: '120-70', lengths: [
              { length: 3000, qty: 4 },
            ]
          },
          {
            type: '하부BASE', spec: '130-80', lengths: [
              { length: 0, qty: 4 },
            ]
          },
        ],
        smokeBarrier: { lengths: [{ length: 2950, qty: 4 }] },
      },
      cases: {
        mainSpec: '500-330',
        items: [
          { length: 4000, qty: 2 },
        ],
        sideCover: { spec: '500-355', qty: 4 },
        topCover: { qty: 0 },
        smokeBarrier: { length: 3000, qty: 2 },
      },
      bottomFinish: {
        items: [
          { name: '하단마감재', spec: '50-40', lengths: [{ length: 4000, qty: 2 }] },
          { name: '하단보강빔바', spec: '80-17', lengths: [{ length: 4000, qty: 4 }] },
        ],
      },
    },
    splits: [
      {
        id: 1,
        splitNo: 'KD-TS-251201-01-01',
        lotNo: 'KD-TS-251201-01',
        splitOrder: 1,
        splitType: '일괄',
        itemIds: [1, 2],
        dueDate: '2025-12-15',
        productionStatus: '작업완료',
        shipmentStatus: '출하완료',
        productionOrderNo: 'KD-WO-251201-01',
        totalQty: 2,
        completedQty: 2,
        remainingQty: 0,
      },
    ],
    documentHistory: [
      { id: 1, docType: '거래명세서', sentAt: '2025-12-01 15:00', sentBy: '판매팀', sentMethod: '이메일', recipient: 'procurement@samsung.com', status: '발송완료' },
      { id: 2, docType: '세금계산서', sentAt: '2025-12-01 15:30', sentBy: '회계팀', sentMethod: '전자발행', recipient: '1248100998', status: '발행완료' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-12-01 14:00', changeType: '수주등록', description: 'A등급 거래처 - 자동 진행', changedBy: '판매팀 김판매' },
      { id: 2, changedAt: '2025-12-02 10:00', changeType: '회계확인', description: '전액 입금 확인', changedBy: '회계팀 박회계' },
      { id: 3, changedAt: '2025-12-18 16:00', changeType: '출하완료', description: '배송 완료', changedBy: '물류팀 박배송' },
    ],
    createdAt: '2025-12-01',
    createdBy: '판매팀 김판매',
    note: '[시나리오1] A등급 정상 플로우 - 자동 진행 완료',
  },

  // ========== 시나리오 2: A등급 생산완료 후 입금대기 (현대건설 - 힐스테이트 판교) ==========
  {
    id: 2,
    orderNo: 'KD-TS-251203-01',
    lotNo: 'KD-TS-251203-01',
    orderDate: '2025-12-03',
    quoteId: 2,
    quoteNo: 'KD-PR-251203-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 2,  // 현대건설(주) - customerMasterConfig.sampleCustomers[1]
    customerName: '현대건설(주)',
    creditGrade: 'A',
    siteId: 3,  // siteMasterConfig.sampleSites[2] - 현대건설 힐스테이트 판교
    siteName: '현대건설 힐스테이트 판교',
    siteCode: 'PJ-250112-01',
    manager: '이현장',
    contact: '010-2345-6789',
    dueDate: '2025-12-25',
    scheduledShipDate: '미정',  // 출고예정일 미정
    status: '생산지시완료',
    paymentStatus: '미입금',
    // 회계 상태 (입금확인 후 출고)
    accountingStatus: '세금계산서발행',
    accountingConfirmedBy: null,
    accountingConfirmedAt: null,
    requireApproval: false,
    requirePaymentBeforeShip: true,  // 입금 후 출고
    shipmentHold: true,              // 출고 보류
    shipmentHoldReason: '입금 미확인',
    // 거래명세서/세금계산서
    invoiceIssued: true,
    invoiceIssuedAt: '2025-02-08 14:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-02-08 14:30',
    // 금액
    totalAmount: 28000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 28000000,
    paidAmount: 0,
    remainingAmount: 28000000,
    deliveryMethod: '직접배차',
    deliveryAddress: '경기도 성남시 분당구 판교동 100-1',
    receiverName: '이현장',
    receiverPhone: '010-2345-6789',
    items: [
      { id: 1, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: 'B1', location: 'C-01', spec: '6000×2400', qty: 2, unit: 'EA', unitPrice: 8000000, amount: 16000000 },
      { id: 2, productCode: 'SLT-001', productName: '슬랫 셔터', floor: '1층', location: 'D-01', spec: '4500×2000', qty: 2, unit: 'EA', unitPrice: 6000000, amount: 12000000 },
    ],
    splits: [
      {
        id: 1,
        splitNo: 'KD-TS-251203-01-01',
        lotNo: 'KD-TS-251203-01',
        splitOrder: 1,
        splitType: '층별',
        itemIds: [1],
        dueDate: '2025-12-20',
        productionStatus: '작업완료',
        shipmentStatus: '출고보류',  // 입금대기
        productionOrderNo: 'KD-WO-251203-01',
        totalQty: 2,
        completedQty: 2,
        remainingQty: 0,
      },
      {
        id: 2,
        splitNo: 'KD-TS-251203-01-02',
        lotNo: 'KD-TS-251203-01',
        splitOrder: 2,
        splitType: '층별',
        itemIds: [2],
        dueDate: '2025-12-25',
        productionStatus: '작업완료',
        shipmentStatus: '출고보류',  // 입금대기
        productionOrderNo: 'KD-WO-251203-02',
        totalQty: 2,
        completedQty: 2,
        remainingQty: 0,
      },
    ],
    documentHistory: [
      { id: 1, docType: '거래명세서', sentAt: '2025-12-03 14:00', sentBy: '판매팀', sentMethod: '이메일', status: '발송완료' },
      { id: 2, docType: '세금계산서', sentAt: '2025-12-03 14:30', sentBy: '회계팀', sentMethod: '전자발행', status: '발행완료' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-12-03 13:00', changeType: '수주등록', description: '입금확인 후 출고 조건', changedBy: '판매팀 이판매' },
      { id: 2, changedAt: '2025-12-15 09:00', changeType: '생산완료', description: '전량 생산 완료, 출고 대기', changedBy: '생산팀 박생산' },
      { id: 3, changedAt: '2025-12-16 10:00', changeType: '출고보류', description: '입금 미확인으로 출고 보류', changedBy: '물류팀 김물류' },
    ],
    createdAt: '2025-12-03',
    createdBy: '판매팀 이판매',
    note: '[시나리오2] 생산완료, 입금확인 대기 중 (출고보류)',
  },

  // ========== 시나리오 3: 경리승인 후 생산 (대우건설 - 푸르지오 일산) ==========
  {
    id: 3,
    orderNo: 'KD-TS-251204-01',
    lotNo: 'KD-TS-251204-01',
    orderDate: '2025-12-05',
    quoteId: 3,
    quoteNo: 'KD-PR-251204-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 3,  // 대우건설(주) - customerMasterConfig.sampleCustomers[2]
    customerName: '대우건설(주)',
    creditGrade: 'A',
    siteId: 4,  // siteMasterConfig.sampleSites[3] - 대우건설 푸르지오 일산
    siteName: '대우건설 푸르지오 일산',
    siteCode: 'PJ-250118-01',
    manager: '박건설',
    contact: '010-3456-7890',
    dueDate: '2025-12-30',
    scheduledShipDate: '미정',  // 출고예정일 미정 (경리승인 대기)
    status: '수주확정',  // 아직 생산지시 안됨
    paymentStatus: '선입금대기',
    // 회계 상태 (경리승인 필요)
    accountingStatus: '미확인',
    accountingConfirmedBy: null,
    accountingConfirmedAt: null,
    requireApproval: true,           // 경리 승인 필요
    approvalStatus: '승인대기',
    approvalRequestedAt: '2025-02-10 15:00',
    requirePaymentBeforeShip: true,  // 입금 후 출고
    productionHold: true,            // 생산 보류
    productionHoldReason: '경리 승인 대기',
    // 거래명세서/세금계산서
    invoiceIssued: false,
    taxInvoiceIssued: false,
    // 금액
    totalAmount: 18000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 18000000,
    paidAmount: 0,
    remainingAmount: 18000000,
    depositRequired: 9000000,  // 선입금 50%
    deliveryMethod: '화물',
    deliveryAddress: '경기도 고양시 일산동구 마두동 200-5',
    receiverName: '박건설',
    receiverPhone: '010-3456-7890',
    items: [
      { id: 1, productCode: 'SLT-001', productName: '슬랫 셔터', floor: '1층', location: 'G-01', spec: '4000×2000', qty: 6, unit: 'EA', unitPrice: 3000000, amount: 18000000 },
    ],
    splits: [],  // 아직 분할 안됨
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-05 14:00', changeType: '수주등록', description: '경리승인 필요', changedBy: '판매팀 박판매' },
      { id: 2, changedAt: '2025-12-05 15:00', changeType: '승인요청', description: '경리팀에 생산 승인 요청', changedBy: '판매팀 박판매' },
      { id: 3, changedAt: '2025-12-06 09:00', changeType: '경리확인', description: '거래처 통화 - 선입금 50% 약속 확인', changedBy: '회계팀 김회계' },
    ],
    createdAt: '2025-12-05',
    createdBy: '판매팀 박판매',
    note: '[시나리오3] 경리승인 대기 중 (생산보류)',
  },

  // ========== 시나리오 4: 추가분 수주 (삼성물산 - 래미안 강남 1차 추가분) ==========
  {
    id: 4,
    orderNo: 'KD-TS-251205-01-A',
    lotNo: 'KD-TS-251205-01-A',
    orderDate: '2025-12-08',
    quoteId: 4,
    quoteNo: 'KD-PR-251205-01',
    orderType: 'additional',  // 추가분
    parentLotNo: 'KD-TS-251201-01',  // 원 로트번호
    customerId: 1,  // 삼성물산(주)
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteId: 1,  // 래미안 강남 1차
    siteName: '삼성물산 래미안 강남 1차',
    siteCode: 'PJ-250110-01',
    manager: '김건설',
    contact: '010-1234-5678',
    dueDate: '2025-12-28',
    scheduledShipDate: '2025-12-26',  // 출고예정일
    status: '생산지시완료',
    paymentStatus: '계약금입금',
    accountingStatus: '입금확인',
    accountingConfirmedBy: '회계팀 박회계',
    accountingConfirmedAt: '2025-12-09 10:00',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    invoiceIssuedAt: '2025-12-08 16:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-12-08 16:30',
    totalAmount: 12000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 12000000,
    paidAmount: 6000000,
    remainingAmount: 6000000,
    deliveryMethod: '상차',
    deliveryAddress: '서울특별시 강남구 도곡동 123-45',
    receiverName: '김건설',
    receiverPhone: '010-1234-5678',
    items: [
      { id: 1, productCode: 'SCR-002', productName: '스크린 셔터 (프리미엄)', floor: '3층', location: 'C-01', spec: '8000×2800', qty: 3, unit: 'EA', unitPrice: 4000000, amount: 12000000 },
    ],
    splits: [
      {
        id: 1,
        splitNo: 'KD-TS-251205-01-A-01',
        lotNo: 'KD-TS-251205-01-A',
        splitOrder: 1,
        splitType: '일괄',
        itemIds: [1],
        dueDate: '2025-12-24',
        productionStatus: '작업중',
        shipmentStatus: '대기',
        productionOrderNo: 'KD-WO-251205-01',
        totalQty: 3,
        completedQty: 1,
        remainingQty: 2,
      },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-08 15:00', changeType: '추가분등록', description: '원 수주 KD-TS-251201-01의 3층 추가분', changedBy: '판매팀 김판매' },
      { id: 2, changedAt: '2025-12-10 09:00', changeType: '생산지시', description: '생산지시 완료', changedBy: '판매팀 김판매' },
    ],
    createdAt: '2025-12-08',
    createdBy: '판매팀 김판매',
    note: '[시나리오4] 추가분 수주 - 기존 현장 3층 추가',
  },

  // ========== 시나리오 5: 분할 출하 (서울인테리어 - 강남 오피스타워) ==========
  {
    id: 5,
    orderNo: 'KD-TS-251206-01',
    lotNo: 'KD-TS-251206-01',
    orderDate: '2025-12-09',
    quoteId: 5,
    quoteNo: 'KD-PR-251206-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 4,  // (주)서울인테리어
    customerName: '(주)서울인테리어',
    creditGrade: 'B',
    siteId: 5,  // 강남 오피스타워 인테리어
    siteName: '강남 오피스타워 인테리어',
    siteCode: 'PJ-250201-01',
    manager: '김담당',
    contact: '010-4567-8901',
    dueDate: '2025-12-29',
    scheduledShipDate: '2025-12-27',  // 출고예정일 (2차)
    status: '생산지시완료',
    paymentStatus: '전액입금',
    accountingStatus: '회계확인완료',
    accountingConfirmedBy: '회계팀 박회계',
    accountingConfirmedAt: '2025-12-10 10:00',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    invoiceIssuedAt: '2025-12-09 15:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-12-09 15:30',
    totalAmount: 35000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 35000000,
    paidAmount: 35000000,
    remainingAmount: 0,
    deliveryMethod: '직접배차',
    deliveryAddress: '서울특별시 강남구 역삼동 300-10',
    receiverName: '김담당',
    receiverPhone: '010-4567-8901',
    items: [
      { id: 1, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'E-01', spec: '7000×2500', qty: 3, unit: 'EA', unitPrice: 8000000, amount: 24000000 },
      { id: 2, productCode: 'SLT-001', productName: '슬랫 셔터', floor: '2층', location: 'F-01', spec: '5000×2200', qty: 2, unit: 'EA', unitPrice: 5500000, amount: 11000000 },
    ],
    splits: [
      {
        id: 1,
        splitNo: 'KD-TS-251206-01-01',
        lotNo: 'KD-TS-251206-01',
        splitOrder: 1,
        splitType: '층별',
        itemIds: [1],
        dueDate: '2025-12-22',  // 1차 출고일
        productionStatus: '작업완료',
        shipmentStatus: '배송완료',
        productionOrderNo: 'KD-WO-251206-01',
        totalQty: 3,
        completedQty: 3,
        remainingQty: 0,
      },
      {
        id: 2,
        splitNo: 'KD-TS-251206-01-02',
        lotNo: 'KD-TS-251206-01',
        splitOrder: 2,
        splitType: '층별',
        itemIds: [2],
        dueDate: '2025-12-27',  // 2차 출고일
        productionStatus: '작업완료',
        shipmentStatus: '출하준비',
        productionOrderNo: 'KD-WO-251206-02',
        totalQty: 2,
        completedQty: 2,
        remainingQty: 0,
      },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-09 14:00', changeType: '수주등록', description: '분할 출하 설정 - 1차 12/22, 2차 12/27', changedBy: '판매팀 최판매' },
      { id: 2, changedAt: '2025-12-22 16:00', changeType: '1차출하', description: '1층 스크린 셔터 출하 완료', changedBy: '물류팀 박배송' },
    ],
    createdAt: '2025-12-09',
    createdBy: '판매팀 최판매',
    note: '[시나리오5] 분할 출하 - 1차 완료, 2차 대기',
  },

  // ========== 시나리오 6: 품질 불량 (삼성물산 - 래미안 강남 2차) ==========
  {
    id: 6,
    orderNo: 'KD-TS-251207-01',
    lotNo: 'KD-TS-251207-01',
    orderDate: '2025-12-10',
    quoteId: 6,
    quoteNo: 'KD-PR-251207-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 1,  // 삼성물산(주)
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteId: 2,  // 래미안 강남 2차
    siteName: '삼성물산 래미안 강남 2차',
    siteCode: 'PJ-250115-01',
    manager: '이건설',
    contact: '010-1111-1111',
    dueDate: '2025-12-28',
    scheduledShipDate: '미정',  // 출고예정일 미정 (재작업 중)
    status: '생산지시완료',
    paymentStatus: '계약금입금',
    accountingStatus: '입금확인',
    accountingConfirmedBy: '회계팀 박회계',
    accountingConfirmedAt: '2025-12-11 10:00',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    invoiceIssuedAt: '2025-12-10 15:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-12-10 15:30',
    totalAmount: 16000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 16000000,
    paidAmount: 8000000,
    remainingAmount: 8000000,
    deliveryMethod: '화물',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    receiverName: '이건설',
    receiverPhone: '010-1111-1111',
    items: [
      { id: 1, productCode: 'SLT-001', productName: '슬랫 셔터', floor: '1층', location: 'H-01', spec: '4500×2000', qty: 4, unit: 'EA', unitPrice: 4000000, amount: 16000000 },
    ],
    splits: [
      {
        id: 1,
        splitNo: 'KD-TS-251207-01-01',
        lotNo: 'KD-TS-251207-01',
        splitOrder: 1,
        splitType: '일괄',
        itemIds: [1],
        dueDate: '2025-12-24',
        productionStatus: '재작업중',  // ⚠️ 품질불량으로 재작업
        shipmentStatus: '대기',
        productionOrderNo: 'KD-WO-251207-01',
        totalQty: 4,
        completedQty: 2,
        remainingQty: 2,
        qualityIssue: true,
        qualityIssueNote: '중간검사 불합격 - 치수불량 2EA 재작업',
      },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-10 14:00', changeType: '수주등록', description: 'B동 슬랫 셔터', changedBy: '판매팀 김판매' },
      { id: 2, changedAt: '2025-12-13 14:00', changeType: '품질불량', description: '중간검사 불합격 - 치수불량 2EA', changedBy: '품질팀 이검사' },
      { id: 3, changedAt: '2025-12-14 09:00', changeType: '재작업지시', description: '불량 2EA 재작업 지시', changedBy: '생산팀 박생산' },
    ],
    createdAt: '2025-12-10',
    createdBy: '판매팀 김판매',
    note: '[시나리오6] 품질 불량 - 중간검사 불합격, 재작업 진행 중',
  },

  // ========== 시나리오 7: 할인 적용 (현대건설 - 힐스테이트 용인) ==========
  {
    id: 7,
    orderNo: 'KD-TS-251208-01',
    lotNo: 'KD-TS-251208-01',
    orderDate: '2025-12-12',
    quoteId: 7,
    quoteNo: 'KD-PR-251208-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 2,  // 현대건설(주) - customerMasterConfig.sampleCustomers[1]
    customerName: '현대건설(주)',
    creditGrade: 'A',
    siteId: 7,  // siteMasterConfig.sampleSites[6] - 현대건설 힐스테이트 용인
    siteName: '현대건설 힐스테이트 용인',
    siteCode: 'PJ-240915-01',
    manager: '이현장',
    contact: '010-2345-6789',
    dueDate: '2026-01-05',
    scheduledShipDate: '2026-01-03',  // 출고예정일
    status: '생산지시완료',
    paymentStatus: '미입금',
    accountingStatus: '세금계산서발행',
    accountingConfirmedBy: null,
    accountingConfirmedAt: null,
    requireApproval: false,
    requirePaymentBeforeShip: true,
    invoiceIssued: true,
    invoiceIssuedAt: '2025-12-12 15:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-12-12 15:30',
    // 할인 적용
    totalAmount: 30000000,
    discountRate: 10,
    discountAmount: 3000000,
    finalAmount: 27000000,  // 할인 후 금액
    paidAmount: 0,
    remainingAmount: 27000000,
    deliveryMethod: '택배',
    deliveryAddress: '경기도 용인시 수지구 상현동 400-20',
    receiverName: '강현장',
    receiverPhone: '010-7777-8888',
    items: [
      { id: 1, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'I-01', spec: '6000×2400', qty: 6, unit: 'EA', unitPrice: 5000000, amount: 30000000 },
    ],
    splits: [
      {
        id: 1,
        splitNo: 'KD-TS-251208-01-01',
        lotNo: 'KD-TS-251208-01',
        splitOrder: 1,
        splitType: '일괄',
        itemIds: [1],
        dueDate: '2025-12-30',
        productionStatus: '작업중',
        shipmentStatus: '대기',
        productionOrderNo: 'KD-WO-251208-01',
        totalQty: 6,
        completedQty: 2,
        remainingQty: 4,
      },
    ],
    documentHistory: [
      { id: 1, docType: '거래명세서', sentAt: '2025-12-12 15:00', sentBy: '판매팀', sentMethod: '이메일', status: '발송완료', note: '할인 10% 적용' },
      { id: 2, docType: '세금계산서', sentAt: '2025-12-12 15:30', sentBy: '회계팀', sentMethod: '전자발행', status: '발행완료', note: '공급가액 24,545,455원' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-12-12 14:00', changeType: '수주등록', description: '대량 주문 10% 할인 적용', changedBy: '판매팀 이판매' },
      { id: 2, changedAt: '2025-12-12 14:30', changeType: '할인적용', description: '할인 10% (3,000,000원) 적용', changedBy: '회계팀 김회계' },
    ],
    createdAt: '2025-12-12',
    createdBy: '판매팀 이판매',
    note: '[시나리오7] 할인 적용 - 대량 주문 10% 할인',
  },

  // ========== 시나리오 8: 발주서 양식 테스트 (용산고등학교 - 직접수주) - 가장 최신 ==========
  {
    id: 8,
    orderNo: 'KD-TS-251210-01',
    lotNo: 'KD-TS-251210-01',
    orderDate: '2025-12-15',
    quoteId: null,
    quoteNo: null,
    orderType: 'direct',  // 직접수주 (견적 없이 바로 수주)
    parentLotNo: null,
    customerId: null,  // 신규 거래처 - 미등록
    customerName: '주말건설',
    creditGrade: 'B',
    siteId: null,  // 신규 현장 - 미등록
    siteName: '용산고등학교(4층)',
    siteCode: 'PJ-251215-02',
    manager: '김명현과장',
    contact: '010-6414-7929',
    dueDate: '2026-01-10',
    scheduledShipDate: '미정',  // 출고예정일 미정 (신규 직접수주)
    status: '생산지시완료',
    paymentStatus: '미입금',
    accountingStatus: '미확인',
    accountingConfirmedBy: null,
    accountingConfirmedAt: null,
    requireApproval: false,
    requirePaymentBeforeShip: true,
    invoiceIssued: false,
    taxInvoiceIssued: false,
    totalAmount: 88000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 88000000,
    paidAmount: 0,
    remainingAmount: 88000000,
    deliveryMethod: '선배',
    deliveryAddress: '경기도 용인시 처인구 고림동 320-8 용산고등학교',
    receiverName: '오전식반장',
    receiverPhone: '010-6414-7929',
    // ====== 품목 11개 (발주서 이미지와 동일) ======
    items: [
      {
        id: 1, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터',
        floor: '4층', location: 'FSS1', spec: '7260×2600', qty: 1, unit: 'EA',
        unitPrice: 8000000, amount: 8000000,
        productionSpec: {
          type: '와이어', drawingNo: '4층 FSS1',
          openWidth: 7260, openHeight: 2600, prodWidth: 7400, prodHeight: 2950,
          guideRailType: '백면형', guideRailSpec: '120-70',
          shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감',
        },
      },
      {
        id: 2, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터',
        floor: '4층', location: 'FSS5', spec: '4560×2600', qty: 1, unit: 'EA',
        unitPrice: 8000000, amount: 8000000,
        productionSpec: {
          type: '와이어', drawingNo: '4층 FSS5',
          openWidth: 4560, openHeight: 2600, prodWidth: 4700, prodHeight: 2950,
          guideRailType: '백면형', guideRailSpec: '120-70',
          shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감',
        },
      },
      {
        id: 3, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터',
        floor: '4층', location: 'FSS17A', spec: '6650×2600', qty: 1, unit: 'EA',
        unitPrice: 8000000, amount: 8000000,
        productionSpec: {
          type: '와이어', drawingNo: 'FSS17A',
          openWidth: 6650, openHeight: 2600, prodWidth: 6790, prodHeight: 2950,
          guideRailType: '백면형', guideRailSpec: '120-70',
          shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감',
        },
      },
      {
        id: 4, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터',
        floor: '4층', location: 'FSS3', spec: '3560×2600', qty: 1, unit: 'EA',
        unitPrice: 8000000, amount: 8000000,
        productionSpec: {
          type: '와이어', drawingNo: '4층 FSS3',
          openWidth: 3560, openHeight: 2600, prodWidth: 3700, prodHeight: 2950,
          guideRailType: '백면형', guideRailSpec: '120-70',
          shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감',
        },
      },
      {
        id: 5, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터',
        floor: '4층', location: 'FSS7', spec: '5860×2600', qty: 1, unit: 'EA',
        unitPrice: 8000000, amount: 8000000,
        productionSpec: {
          type: '와이어', drawingNo: '4층 FSS7',
          openWidth: 5860, openHeight: 2600, prodWidth: 6000, prodHeight: 2950,
          guideRailType: '백면형', guideRailSpec: '120-70',
          shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감',
        },
      },
      {
        id: 6, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터',
        floor: '4층', location: 'FSS16', spec: '7160×2600', qty: 1, unit: 'EA',
        unitPrice: 8000000, amount: 8000000,
        productionSpec: {
          type: '와이어', drawingNo: '4층 FSS16',
          openWidth: 7160, openHeight: 2600, prodWidth: 7300, prodHeight: 2950,
          guideRailType: '백면형', guideRailSpec: '120-70',
          shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감',
        },
      },
      {
        id: 7, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터',
        floor: '4층', location: 'FSS3-2', spec: '3560×2600', qty: 1, unit: 'EA',
        unitPrice: 8000000, amount: 8000000,
        productionSpec: {
          type: '와이어', drawingNo: '4층 FSS3-2',
          openWidth: 3560, openHeight: 2600, prodWidth: 3700, prodHeight: 2950,
          guideRailType: '백면형', guideRailSpec: '120-70',
          shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감',
        },
      },
      {
        id: 8, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터',
        floor: '4층', location: 'FSS6', spec: '5760×2600', qty: 1, unit: 'EA',
        unitPrice: 8000000, amount: 8000000,
        productionSpec: {
          type: '와이어', drawingNo: '4층 FSS6',
          openWidth: 5760, openHeight: 2600, prodWidth: 5900, prodHeight: 2950,
          guideRailType: '백면형', guideRailSpec: '120-70',
          shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감',
        },
      },
      {
        id: 9, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터',
        floor: '4층', location: 'FSS3-3', spec: '3770×2600', qty: 1, unit: 'EA',
        unitPrice: 8000000, amount: 8000000,
        productionSpec: {
          type: '와이어', drawingNo: '4층 FSS3-3',
          openWidth: 3770, openHeight: 2600, prodWidth: 3910, prodHeight: 2950,
          guideRailType: '백면형', guideRailSpec: '120-70',
          shaft: 4, caseSpec: '500-330', motorBracket: '380-180', capacity: 160, finish: 'SUS마감',
        },
      },
      {
        id: 10, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터',
        floor: '4층', location: 'FSS17', spec: '7260×2600', qty: 1, unit: 'EA',
        unitPrice: 8000000, amount: 8000000,
        productionSpec: {
          type: '와이어', drawingNo: '4층 FSS17',
          openWidth: 7260, openHeight: 2600, prodWidth: 7400, prodHeight: 2950,
          guideRailType: '백면형', guideRailSpec: '120-70',
          shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감',
        },
      },
      {
        id: 11, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터',
        floor: '4층', location: 'FSS15', spec: '6860×2600', qty: 1, unit: 'EA',
        unitPrice: 8000000, amount: 8000000,
        productionSpec: {
          type: '와이어', drawingNo: '4층 FSS15',
          openWidth: 6860, openHeight: 2600, prodWidth: 7000, prodHeight: 2950,
          guideRailType: '백면형', guideRailSpec: '120-70',
          shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감',
        },
      },
    ],
    // ====== 모터/전장품 (발주서 이미지와 동일) ======
    motorSpec: {
      motors220V: [
        { model: 'KD-150K', qty: 0 },
        { model: 'KD-300K', qty: 0 },
        { model: 'KD-400K', qty: 0 },
      ],
      motors380V: [
        { model: 'KD-150K', qty: 6 },  // 160K 모터 (작은 셔터용)
        { model: 'KD-300K', qty: 5 },  // 300K 모터 (큰 셔터용)
        { model: 'KD-400K', qty: 0 },
      ],
      brackets: [
        { spec: '380-180 [2-4"]', qty: 0 },
        { spec: '380-180 [2-5"]', qty: 5 },
      ],
      heatSinks: [
        { spec: '40-60', qty: 44 },
        { spec: 'L-380', qty: 0 },
      ],
      controllers: [
        { type: '매입형', qty: 0 },
        { type: '노출형', qty: 0 },
        { type: '핫라스', qty: 0 },
      ],
    },
    // ====== 절곡물 BOM (발주서 이미지와 동일) ======
    bomData: {
      guideRails: {
        description: '가이드레일 - EGI 1.55T + 마감재 EGI 1.15T + 별도마감재 SUS 1.15T',
        items: [
          {
            type: '백면형', spec: '120-70', code: 'KSS01', lengths: [
              { length: 4300, qty: 0 },
              { length: 3500, qty: 0 },
            ]
          },
          {
            type: '백면형', spec: '120-70', code: 'KSE01/KWE01', lengths: [
              { length: 3000, qty: 22 },
              { length: 2438, qty: 0 },
            ]
          },
          {
            type: '측면형', spec: '120-120', code: 'KSS01', lengths: [
              { length: 4300, qty: 0 },
              { length: 4000, qty: 0 },
              { length: 3500, qty: 0 },
              { length: 3000, qty: 0 },
              { length: 2438, qty: 0 },
            ]
          },
          {
            type: '하부BASE', spec: '130-80', code: '', lengths: [
              { length: 0, qty: 22 },
            ]
          },
        ],
        smokeBarrier: {
          spec: 'W80',
          material: '원 0.8T 화이바글라스크탑직물',
          lengths: [{ length: 2438, qty: 44 }],
          note: '* 전면부, 린텔부 양쪽에 설치',
        },
      },
      cases: {
        description: '케이스(셔터박스) - EGI 1.55T',
        mainSpec: '500-330 (150,300,400/K용)',
        items: [
          { length: 4150, qty: 1 },
          { length: 4000, qty: 7 },
          { length: 3500, qty: 5 },
          { length: 3000, qty: 3 },
          { length: 2438, qty: 3 },
          { length: 1219, qty: 0 },
        ],
        sideCover: { spec: '500-355', qty: 22 },
        topCover: { qty: 3 },
        extension: { spec: '1219+무게', qty: 59 },
        smokeBarrier: { spec: 'W80', length: 3000, qty: 47 },
      },
      bottomFinish: {
        description: '하단마감재 - 마단마감재(EGI 1.55T) + 하단보강별바(EGI 1.55T) + 하단 보강횡철(EGI 1.15T) + 하단 부재횡철(50-12T)',
        items: [
          {
            name: '하단마감재', spec: '50-40', lengths: [
              { length: 4000, qty: 11 },
              { length: 3000, qty: 8 },
            ]
          },
          {
            name: '하단보강빔바', spec: '80-17', lengths: [
              { length: 4000, qty: 28 },
              { length: 3000, qty: 12 },
            ]
          },
          {
            name: '하단보강철', spec: '', lengths: [
              { length: 4000, qty: 13 },
              { length: 3000, qty: 0 },
            ]
          },
          {
            name: '하단부재횡철', spec: '50-12T', lengths: [
              { length: 2000, qty: 67 },
            ]
          },
        ],
      },
    },
    splits: [
      {
        id: 1,
        splitNo: 'KD-TS-251210-01-01',
        lotNo: 'KD-TS-251210-01',
        splitOrder: 1,
        splitType: '일괄',
        itemIds: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
        dueDate: '2026-01-05',
        productionStatus: '작업대기',
        shipmentStatus: '미출고',
        productionOrderNo: 'KD-WO-251210-01',
        totalQty: 11,
        completedQty: 0,
        remainingQty: 11,
      },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-15 09:00', changeType: '수주등록', description: '용산고등학교 4층 방화셔터 11개소', changedBy: '판매팀 김판매' },
      { id: 2, changedAt: '2025-12-16 10:00', changeType: '생산지시', description: '전체 일괄 생산지시', changedBy: '생산팀 박생산' },
    ],
    createdAt: '2025-12-15',
    createdBy: '판매팀 김판매',
    note: '[시나리오8] 발주서 양식 테스트 - 용산고등학교 4층 방화셔터 11개소 (직접수주, 가장 최신)',
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // E2E 테스트용 수주 데이터 (견적 101-105 연결)
  // ═══════════════════════════════════════════════════════════════════════════

  // E2E-101: 삼성물산 - 강남 오피스 A동 스크린 (견적101 → 수주)
  {
    id: 101,
    orderNo: 'KD-TS-251216-01',
    lotNo: 'KD-TS-251216-01',
    quoteId: 101,
    quoteNo: 'KD-PR-251216-01',
    orderDate: '2025-12-16',
    customerId: 1,
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteId: 'PJ-E2E-001',
    siteName: '[E2E테스트] 강남 오피스 A동',
    siteAddress: '서울시 강남구 테헤란로 100',
    contact: '010-1234-5678',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    dueDate: '2025-12-30',
    totalAmount: 18500000,
    status: '생산지시완료',
    paymentStatus: '입금완료',
    accountingApproval: '승인완료',
    shipmentStatus: '미출고',
    productionProgress: 33,
    items: [
      { id: 1, floor: '1층', location: 'A-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, spec: '3000×2500', guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, unitPrice: 6166667, amount: 6166667, process: 'screen' },
      { id: 2, floor: '2층', location: 'A-02', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, spec: '3000×2500', guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, unitPrice: 6166667, amount: 6166667, process: 'screen' },
      { id: 3, floor: '3층', location: 'A-03', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, spec: '3000×2500', guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, unitPrice: 6166666, amount: 6166666, process: 'screen' },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251216-01-01', lotNo: 'KD-TS-251216-01', splitOrder: 1, splitType: '일괄', itemIds: [1, 2, 3], dueDate: '2025-12-30', productionStatus: '작업중', shipmentStatus: '미출고', productionOrderNo: 'KD-WO-251216-01', totalQty: 3, completedQty: 1, remainingQty: 2 },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-16 09:00', changeType: '수주등록', description: '견적 KD-PR-251216-01 기반 수주 전환', changedBy: '[E2E] 시스템' },
      { id: 2, changedAt: '2025-12-16 10:00', changeType: '생산지시', description: '전체 일괄 생산지시', changedBy: '생산팀' },
    ],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    note: '[E2E-101] 견적→수주 전환 테스트 - 스크린 3개소',
  },

  // E2E-102: 현대건설 - 판교 물류센터 슬랫 (견적102 → 수주)
  {
    id: 102,
    orderNo: 'KD-TS-251216-02',
    lotNo: 'KD-TS-251216-02',
    quoteId: 102,
    quoteNo: 'KD-PR-251216-02',
    orderDate: '2025-12-16',
    customerId: 2,
    customerName: '현대건설(주)',
    creditGrade: 'A',
    siteId: 'PJ-E2E-002',
    siteName: '[E2E테스트] 판교 물류센터',
    siteAddress: '경기도 성남시 분당구 판교로 200',
    contact: '010-2345-6789',
    deliveryAddress: '경기도 성남시 분당구 판교로 200',
    dueDate: '2025-12-28',
    totalAmount: 15000000,
    status: '작업완료',
    paymentStatus: '입금완료',
    accountingApproval: '승인완료',
    shipmentStatus: '출고대기',
    productionProgress: 100,
    items: [
      { id: 1, floor: 'B1', location: 'C-01', category: '슬랫', productName: '철재 슬랫 셔터', width: 4000, height: 3000, spec: '4000×3000', guideType: '코너형', motorPower: '220V', controller: '노출형', qty: 1, unitPrice: 7500000, amount: 7500000, process: 'slat' },
      { id: 2, floor: 'B2', location: 'C-02', category: '슬랫', productName: '철재 슬랫 셔터', width: 4000, height: 3000, spec: '4000×3000', guideType: '코너형', motorPower: '220V', controller: '노출형', qty: 1, unitPrice: 7500000, amount: 7500000, process: 'slat' },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251216-02-01', lotNo: 'KD-TS-251216-02', splitOrder: 1, splitType: '일괄', itemIds: [1, 2], dueDate: '2025-12-28', productionStatus: '작업완료', shipmentStatus: '출고대기', productionOrderNo: 'KD-WO-251216-02', totalQty: 2, completedQty: 2, remainingQty: 0 },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-16 09:30', changeType: '수주등록', description: '견적 KD-PR-251216-02 기반 수주 전환', changedBy: '[E2E] 시스템' },
      { id: 2, changedAt: '2025-12-16 14:00', changeType: '작업완료', description: '슬랫 2개소 작업완료', changedBy: '생산팀' },
    ],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    note: '[E2E-102] 슬랫 공정 테스트 - 작업완료 상태',
  },

  // E2E-103: 대우건설 - 송도 아파트 B동 혼합 (견적103 → 수주, 공정분리)
  {
    id: 103,
    orderNo: 'KD-TS-251216-03',
    lotNo: 'KD-TS-251216-03',
    quoteId: 103,
    quoteNo: 'KD-PR-251216-03',
    orderDate: '2025-12-16',
    customerId: 3,
    customerName: '대우건설(주)',
    creditGrade: 'A',
    siteId: 'PJ-E2E-003',
    siteName: '[E2E테스트] 송도 아파트 B동',
    siteAddress: '인천시 연수구 송도동 300',
    contact: '010-3456-7890',
    deliveryAddress: '인천시 연수구 송도동 300',
    dueDate: '2025-12-25',
    totalAmount: 28000000,
    status: '생산지시완료',
    paymentStatus: '입금완료',
    accountingApproval: '승인완료',
    shipmentStatus: '생산완료',
    productionProgress: 100,
    items: [
      { id: 1, floor: '1층', location: 'D-01', category: '스크린', productName: '스크린 셔터 (대형)', width: 6000, height: 4000, spec: '6000×4000', guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, unitPrice: 12000000, amount: 12000000, process: 'screen' },
      { id: 2, floor: '1층', location: 'D-02', category: '슬랫', productName: '철재 슬랫 셔터', width: 3500, height: 2500, spec: '3500×2500', guideType: '벽면형', motorPower: '220V', controller: '노출형', qty: 2, unitPrice: 5000000, amount: 10000000, process: 'slat' },
      { id: 3, floor: '2층', location: 'D-03', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, spec: '3000×2500', guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, unitPrice: 6000000, amount: 6000000, process: 'screen' },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251216-03-01', lotNo: 'KD-TS-251216-03', splitOrder: 1, splitType: '공정분리-스크린', itemIds: [1, 3], dueDate: '2025-12-23', productionStatus: '작업완료', shipmentStatus: '배송완료', productionOrderNo: 'KD-WO-251216-03', totalQty: 2, completedQty: 2, remainingQty: 0 },
      { id: 2, splitNo: 'KD-TS-251216-03-02', lotNo: 'KD-TS-251216-03', splitOrder: 2, splitType: '공정분리-슬랫', itemIds: [2], dueDate: '2025-12-25', productionStatus: '작업완료', shipmentStatus: '배송완료', productionOrderNo: 'KD-WO-251216-04', totalQty: 2, completedQty: 2, remainingQty: 0 },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-16 10:00', changeType: '수주등록', description: '견적 KD-PR-251216-03 기반 수주 전환 (공정분리)', changedBy: '[E2E] 시스템' },
      { id: 2, changedAt: '2025-12-23 16:00', changeType: '출하완료', description: '스크린+슬랫 전체 배송완료', changedBy: '물류팀' },
    ],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    note: '[E2E-103] 공정분리 테스트 - 스크린/슬랫 분리 작업지시 후 배송완료',
  },

  // E2E-104: 서울인테리어 - 용산 호텔 대형 스크린 (견적104 → 수주)
  {
    id: 104,
    orderNo: 'KD-TS-251216-04',
    lotNo: 'KD-TS-251216-04',
    quoteId: 104,
    quoteNo: 'KD-PR-251216-04',
    orderDate: '2025-12-16',
    customerId: 4,
    customerName: '(주)서울인테리어',
    creditGrade: 'B',
    siteId: 'PJ-E2E-004',
    siteName: '[E2E테스트] 용산 호텔',
    siteAddress: '서울시 용산구 한강로 400',
    contact: '010-4567-8901',
    deliveryAddress: '서울시 용산구 한강로 400',
    dueDate: '2025-12-31',
    totalAmount: 22000000,
    status: '작업대기',
    paymentStatus: '부분입금',
    accountingApproval: '승인대기',
    shipmentStatus: '미출고',
    productionProgress: 0,
    items: [
      { id: 1, floor: '로비', location: 'E-01', category: '스크린', productName: '스크린 셔터 (대형)', width: 6000, height: 4000, spec: '6000×4000', guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, unitPrice: 11000000, amount: 11000000, process: 'screen' },
      { id: 2, floor: '연회장', location: 'E-02', category: '스크린', productName: '스크린 셔터 (대형)', width: 6000, height: 4000, spec: '6000×4000', guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, unitPrice: 11000000, amount: 11000000, process: 'screen' },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251216-04-01', lotNo: 'KD-TS-251216-04', splitOrder: 1, splitType: '일괄', itemIds: [1, 2], dueDate: '2025-12-31', productionStatus: '작업대기', shipmentStatus: '미출고', productionOrderNo: 'KD-WO-251216-05', totalQty: 2, completedQty: 0, remainingQty: 2 },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-16 11:00', changeType: '수주등록', description: '견적 KD-PR-251216-04 기반 수주 전환', changedBy: '[E2E] 시스템' },
    ],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    note: '[E2E-104] B등급 거래처 테스트 - 부분입금/승인대기 상태',
  },

  // E2E-105: 삼성물산 - 삼성타운 종합 (견적105 → 수주, 전 공정 통합)
  {
    id: 105,
    orderNo: 'KD-TS-251216-05',
    lotNo: 'KD-TS-251216-05',
    quoteId: 105,
    quoteNo: 'KD-PR-251216-05',
    orderDate: '2025-12-16',
    customerId: 1,
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteId: 'PJ-E2E-005',
    siteName: '[E2E테스트] 삼성타운 종합',
    siteAddress: '서울시 서초구 서초대로 500',
    contact: '010-5678-9012',
    deliveryAddress: '서울시 서초구 서초대로 500',
    dueDate: '2026-01-15',
    totalAmount: 42750000,
    discountRate: 5,
    discountAmount: 2250000,
    status: '생산지시완료',
    paymentStatus: '입금완료',
    accountingApproval: '승인완료',
    shipmentStatus: '일부출고',
    productionProgress: 67,
    items: [
      { id: 1, floor: '1층', location: 'F-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3500, height: 2800, spec: '3500×2800', guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 2, unitPrice: 7000000, amount: 14000000, process: 'screen' },
      { id: 2, floor: '2층', location: 'F-02', category: '슬랫', productName: '철재 슬랫 셔터', width: 4500, height: 3200, spec: '4500×3200', guideType: '코너형', motorPower: '220V', controller: '노출형', qty: 2, unitPrice: 8000000, amount: 16000000, process: 'slat' },
      { id: 3, floor: '3층', location: 'F-03', category: '스크린', productName: '스크린 셔터 (대형)', width: 5000, height: 3500, spec: '5000×3500', guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 2, unitPrice: 7500000, amount: 15000000, process: 'screen' },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251216-05-01', lotNo: 'KD-TS-251216-05', splitOrder: 1, splitType: '1차출하-스크린', itemIds: [1], dueDate: '2025-12-28', productionStatus: '작업완료', shipmentStatus: '배송완료', productionOrderNo: 'KD-WO-251216-06', totalQty: 2, completedQty: 2, remainingQty: 0 },
      { id: 2, splitNo: 'KD-TS-251216-05-02', lotNo: 'KD-TS-251216-05', splitOrder: 2, splitType: '2차출하-슬랫', itemIds: [2], dueDate: '2026-01-05', productionStatus: '작업완료', shipmentStatus: '출고대기', productionOrderNo: 'KD-WO-251216-07', totalQty: 2, completedQty: 2, remainingQty: 0 },
      { id: 3, splitNo: 'KD-TS-251216-05-03', lotNo: 'KD-TS-251216-05', splitOrder: 3, splitType: '3차출하-대형스크린', itemIds: [3], dueDate: '2026-01-15', productionStatus: '작업중', shipmentStatus: '미출고', productionOrderNo: 'KD-WO-251216-08', totalQty: 2, completedQty: 1, remainingQty: 1 },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-16 14:00', changeType: '수주등록', description: '견적 KD-PR-251216-05 기반 수주 전환 (할인 5% 적용)', changedBy: '[E2E] 시스템' },
      { id: 2, changedAt: '2025-12-28 17:00', changeType: '1차출하완료', description: '1층 스크린 2개소 배송완료', changedBy: '물류팀' },
    ],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    note: '[E2E-105] 전 공정 통합 테스트 - 3차 분할출하 진행중 (1차완료, 2차대기, 3차생산중)',
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // 전체 워크플로우 통합 테스트 수주 데이터 10건 (ID: 201-210)
  // 견적(QT-251217-XX) → 수주(SO-251217-XX) → 생산 → 품질 → 출하 연동
  // ═══════════════════════════════════════════════════════════════════════════

  // [통합테스트 1] 삼성물산 - 래미안 강남 프레스티지 (A등급, 스크린 3대)
  {
    id: 201,
    orderNo: 'KD-TS-251217-01',
    lotNo: 'KD-TS-251217-01',
    quoteId: 201,
    quoteNo: 'KD-PR-251217-01',
    orderDate: '2025-12-17',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 1,
    customerCode: 'CUS-001',
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteId: 1,
    siteName: '래미안 강남 프레스티지',
    siteCode: 'S-001',
    manager: '김건설',
    contact: '010-1234-5678',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    receiverName: '김건설',
    receiverPhone: '010-1234-5678',
    dueDate: '2026-01-15',
    scheduledShipDate: '2026-01-13',
    status: '생산지시완료',
    paymentStatus: '전액입금',
    accountingStatus: '회계확인완료',
    accountingConfirmedBy: '회계팀 박회계',
    accountingConfirmedAt: '2025-12-18 10:00',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    invoiceIssuedAt: '2025-12-17 15:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-12-17 15:30',
    totalAmount: 24000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 24000000,
    paidAmount: 24000000,
    remainingAmount: 0,
    deliveryMethod: '상차',
    items: [
      { id: 1, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'A-01', spec: '3000×2500', qty: 1, unit: 'EA', unitPrice: 8000000, amount: 8000000, productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, prodWidth: 3140, prodHeight: 2850, guideRailType: '벽면형', guideRailSpec: '120-70', shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감' } },
      { id: 2, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '2층', location: 'A-02', spec: '3000×2500', qty: 1, unit: 'EA', unitPrice: 8000000, amount: 8000000, productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, prodWidth: 3140, prodHeight: 2850, guideRailType: '벽면형', guideRailSpec: '120-70', shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감' } },
      { id: 3, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '3층', location: 'A-03', spec: '3000×2500', qty: 1, unit: 'EA', unitPrice: 8000000, amount: 8000000, productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, prodWidth: 3140, prodHeight: 2850, guideRailType: '벽면형', guideRailSpec: '120-70', shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감' } },
    ],
    motorSpec: { motors220V: [{ model: 'KD-300K', qty: 3 }], brackets: [{ spec: '380-180', qty: 3 }], controllers: [{ type: '매립형', qty: 3 }] },
    splits: [
      { id: 1, splitNo: 'KD-TS-251217-01-01', lotNo: 'KD-TS-251217-01', splitOrder: 1, splitType: '일괄', itemIds: [1, 2, 3], dueDate: '2026-01-15', productionStatus: '작업완료', shipmentStatus: '출하준비', productionOrderNo: 'KD-WO-251217-01', totalQty: 3, completedQty: 3, remainingQty: 0 },
    ],
    documentHistory: [
      { id: 1, docType: '거래명세서', sentAt: '2025-12-17 15:00', sentBy: '판매팀', sentMethod: '이메일', status: '발송완료' },
      { id: 2, docType: '세금계산서', sentAt: '2025-12-17 15:30', sentBy: '회계팀', sentMethod: '전자발행', status: '발행완료' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-12-17 14:00', changeType: '수주등록', description: '[통합테스트1] A등급 정상 플로우 - 자동 진행', changedBy: '판매1팀 김영업' },
      { id: 2, changedAt: '2025-12-18 10:00', changeType: '회계확인', description: '전액 입금 확인', changedBy: '회계팀 박회계' },
    ],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 김영업',
    note: '[통합테스트1] A등급 정상 플로우 - 스크린 3대 생산완료',
  },

  // [통합테스트 2] 현대건설 - 힐스테이트 판교 (A등급, 스크린+슬랫 혼합)
  {
    id: 202,
    orderNo: 'KD-TS-251217-02',
    lotNo: 'KD-TS-251217-02',
    quoteId: 202,
    quoteNo: 'KD-PR-251217-02',
    orderDate: '2025-12-17',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 2,
    customerCode: 'CUS-002',
    customerName: '현대건설(주)',
    creditGrade: 'A',
    siteId: 11,
    siteName: '힐스테이트 판교 더 퍼스트',
    siteCode: 'S-011',
    manager: '박현장',
    contact: '010-2345-6789',
    deliveryAddress: '경기도 성남시 분당구 판교로 200',
    receiverName: '박현장',
    receiverPhone: '010-2345-6789',
    dueDate: '2026-01-20',
    scheduledShipDate: '2026-01-18',
    status: '생산중',
    paymentStatus: '계약금입금',
    accountingStatus: '입금확인',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    taxInvoiceIssued: true,
    totalAmount: 32000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 32000000,
    paidAmount: 16000000,
    remainingAmount: 16000000,
    deliveryMethod: '직접배차',
    items: [
      { id: 1, productCode: 'SH4030', productName: '스크린 셔터 (표준형)', floor: 'B1', location: 'B-01', spec: '4000×3000', qty: 2, unit: 'EA', unitPrice: 9000000, amount: 18000000, productionSpec: { type: '와이어', openWidth: 4000, openHeight: 3000, prodWidth: 4140, prodHeight: 3350, guideRailType: '벽면형', capacity: 300 } },
      { id: 2, productCode: 'ST3525', productName: '철재 슬랫 셔터', floor: '1층', location: 'B-02', spec: '3500×2500', qty: 2, unit: 'EA', unitPrice: 7000000, amount: 14000000, productionSpec: { type: '슬랫', openWidth: 3500, openHeight: 2500 } },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251217-02-01', lotNo: 'KD-TS-251217-02', splitOrder: 1, splitType: '공정분리-스크린', itemIds: [1], dueDate: '2026-01-15', productionStatus: '작업완료', shipmentStatus: '출하준비', productionOrderNo: 'KD-WO-251217-02', totalQty: 2, completedQty: 2, remainingQty: 0 },
      { id: 2, splitNo: 'KD-TS-251217-02-02', lotNo: 'KD-TS-251217-02', splitOrder: 2, splitType: '공정분리-슬랫', itemIds: [2], dueDate: '2026-01-20', productionStatus: '작업중', shipmentStatus: '미출고', productionOrderNo: 'KD-WO-251217-03', totalQty: 2, completedQty: 1, remainingQty: 1 },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-17 14:30', changeType: '수주등록', description: '[통합테스트2] 스크린+슬랫 혼합 공정분리', changedBy: '판매1팀 이영업' },
    ],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 이영업',
    note: '[통합테스트2] 스크린+슬랫 혼합 공정 분리 - 스크린 완료, 슬랫 진행중',
  },

  // [통합테스트 3] 대우건설 - 푸르지오 일산 (A등급, 대형 스크린)
  {
    id: 203,
    orderNo: 'KD-TS-251217-03',
    lotNo: 'KD-TS-251217-03',
    quoteId: 203,
    quoteNo: 'KD-PR-251217-03',
    orderDate: '2025-12-17',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 3,
    customerCode: 'CUS-003',
    customerName: '대우건설(주)',
    creditGrade: 'A',
    siteId: 21,
    siteName: '푸르지오 일산 센트럴파크',
    siteCode: 'S-021',
    manager: '최건설',
    contact: '010-3456-7890',
    deliveryAddress: '경기도 고양시 일산동구 마두동 500',
    receiverName: '최건설',
    receiverPhone: '010-3456-7890',
    dueDate: '2026-01-25',
    scheduledShipDate: '2026-01-23',
    status: '생산지시완료',
    paymentStatus: '전액입금',
    accountingStatus: '회계확인완료',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    taxInvoiceIssued: true,
    totalAmount: 28000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 28000000,
    paidAmount: 28000000,
    remainingAmount: 0,
    deliveryMethod: '화물',
    items: [
      { id: 1, productCode: 'SH6040', productName: '스크린 셔터 (대형)', floor: '로비', location: 'C-01', spec: '6000×4000', qty: 1, unit: 'EA', unitPrice: 14000000, amount: 14000000, productionSpec: { type: '와이어', openWidth: 6000, openHeight: 4000, prodWidth: 6140, prodHeight: 4350, guideRailType: '벽면형', capacity: 500 } },
      { id: 2, productCode: 'SH6040', productName: '스크린 셔터 (대형)', floor: '연회장', location: 'C-02', spec: '6000×4000', qty: 1, unit: 'EA', unitPrice: 14000000, amount: 14000000, productionSpec: { type: '와이어', openWidth: 6000, openHeight: 4000, prodWidth: 6140, prodHeight: 4350, guideRailType: '벽면형', capacity: 500 } },
    ],
    motorSpec: { motors380V: [{ model: 'KD-500K', qty: 2 }], brackets: [{ spec: '500-250', qty: 2 }], controllers: [{ type: '매립형', qty: 2 }] },
    splits: [
      { id: 1, splitNo: 'KD-TS-251217-03-01', lotNo: 'KD-TS-251217-03', splitOrder: 1, splitType: '일괄', itemIds: [1, 2], dueDate: '2026-01-25', productionStatus: '작업완료', shipmentStatus: '출하준비', productionOrderNo: 'KD-WO-251217-04', totalQty: 2, completedQty: 2, remainingQty: 0 },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-17 15:00', changeType: '수주등록', description: '[통합테스트3] 대형 스크린 500KG 모터', changedBy: '판매2팀 박영업' },
    ],
    createdAt: '2025-12-17',
    createdBy: '판매2팀 박영업',
    note: '[통합테스트3] 대형 스크린(6m×4m) 모터용량 500KG - 생산완료',
  },

  // [통합테스트 4] GS건설 - 자이 위례 (A등급, 슬랫 전용)
  {
    id: 204,
    orderNo: 'KD-TS-251217-04',
    lotNo: 'KD-TS-251217-04',
    quoteId: 204,
    quoteNo: 'KD-PR-251217-04',
    orderDate: '2025-12-17',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 4,
    customerCode: 'CUS-004',
    customerName: 'GS건설(주)',
    creditGrade: 'A',
    siteId: 31,
    siteName: '자이 위례 더 퍼스트',
    siteCode: 'S-031',
    manager: '정건설',
    contact: '010-4567-8901',
    deliveryAddress: '경기도 성남시 수정구 위례동 100',
    receiverName: '정건설',
    receiverPhone: '010-4567-8901',
    dueDate: '2026-01-30',
    scheduledShipDate: '2026-01-28',
    status: '생산중',
    paymentStatus: '계약금입금',
    accountingStatus: '입금확인',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    taxInvoiceIssued: false,
    totalAmount: 35000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 35000000,
    paidAmount: 17500000,
    remainingAmount: 17500000,
    deliveryMethod: '직접배차',
    items: [
      { id: 1, productCode: 'ST4030', productName: '철재 슬랫 셔터', floor: 'B1', location: 'D-01', spec: '4000×3000', qty: 3, unit: 'EA', unitPrice: 7000000, amount: 21000000, productionSpec: { type: '슬랫', openWidth: 4000, openHeight: 3000 } },
      { id: 2, productCode: 'ST4030-C', productName: '철재 슬랫 셔터 (코너형)', floor: '1층', location: 'D-02', spec: '4000×3000', qty: 2, unit: 'EA', unitPrice: 7000000, amount: 14000000, productionSpec: { type: '슬랫', openWidth: 4000, openHeight: 3000, guideRailType: '코너형' } },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251217-04-01', lotNo: 'KD-TS-251217-04', splitOrder: 1, splitType: '일괄-슬랫', itemIds: [1, 2], dueDate: '2026-01-30', productionStatus: '작업중', shipmentStatus: '미출고', productionOrderNo: 'KD-WO-251217-05', totalQty: 5, completedQty: 3, remainingQty: 2 },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-17 15:30', changeType: '수주등록', description: '[통합테스트4] 슬랫 전용 공정', changedBy: '판매2팀 최영업' },
    ],
    createdAt: '2025-12-17',
    createdBy: '판매2팀 최영업',
    note: '[통합테스트4] 슬랫 전용 공정 - 5대 중 3대 완료',
  },

  // [통합테스트 5] 포스코건설 - 더샵 송도 (A등급, 코너형 가이드)
  {
    id: 205,
    orderNo: 'KD-TS-251217-05',
    lotNo: 'KD-TS-251217-05',
    quoteId: 205,
    quoteNo: 'KD-PR-251217-05',
    orderDate: '2025-12-17',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 5,
    customerCode: 'CUS-005',
    customerName: '포스코건설(주)',
    creditGrade: 'A',
    siteId: 41,
    siteName: '더샵 송도 센트럴파크',
    siteCode: 'S-041',
    manager: '강건설',
    contact: '010-5678-9012',
    deliveryAddress: '인천시 연수구 송도동 200',
    receiverName: '강건설',
    receiverPhone: '010-5678-9012',
    dueDate: '2026-02-05',
    scheduledShipDate: '2026-02-03',
    status: '생산지시완료',
    paymentStatus: '전액입금',
    accountingStatus: '회계확인완료',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    taxInvoiceIssued: true,
    totalAmount: 27000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 27000000,
    paidAmount: 27000000,
    remainingAmount: 0,
    deliveryMethod: '상차',
    items: [
      { id: 1, productCode: 'SH3530-C', productName: '스크린 셔터 (코너형)', floor: '1층', location: 'E-01', spec: '3500×3000', qty: 1, unit: 'EA', unitPrice: 9000000, amount: 9000000, productionSpec: { type: '와이어', openWidth: 3500, openHeight: 3000, guideRailType: '코너형', capacity: 300 } },
      { id: 2, productCode: 'SH3530-C', productName: '스크린 셔터 (코너형)', floor: '2층', location: 'E-02', spec: '3500×3000', qty: 1, unit: 'EA', unitPrice: 9000000, amount: 9000000, productionSpec: { type: '와이어', openWidth: 3500, openHeight: 3000, guideRailType: '코너형', capacity: 300 } },
      { id: 3, productCode: 'SH3530-C', productName: '스크린 셔터 (코너형)', floor: '3층', location: 'E-03', spec: '3500×3000', qty: 1, unit: 'EA', unitPrice: 9000000, amount: 9000000, productionSpec: { type: '와이어', openWidth: 3500, openHeight: 3000, guideRailType: '코너형', capacity: 300 } },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251217-05-01', lotNo: 'KD-TS-251217-05', splitOrder: 1, splitType: '일괄', itemIds: [1, 2, 3], dueDate: '2026-02-05', productionStatus: '작업완료', shipmentStatus: '출하준비', productionOrderNo: 'KD-WO-251217-06', totalQty: 3, completedQty: 3, remainingQty: 0 },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-17 16:00', changeType: '수주등록', description: '[통합테스트5] 코너형 가이드레일 BOM', changedBy: '판매1팀 김영업' },
    ],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 김영업',
    note: '[통합테스트5] 코너형 가이드레일 BOM 산출 - 생산완료',
  },

  // [통합테스트 6] 롯데건설 - 캐슬 잠실 (B등급, 경리승인 필요)
  {
    id: 206,
    orderNo: 'KD-TS-251217-06',
    lotNo: 'KD-TS-251217-06',
    quoteId: 206,
    quoteNo: 'KD-PR-251217-06',
    orderDate: '2025-12-17',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 6,
    customerCode: 'CUS-006',
    customerName: '롯데건설(주)',
    creditGrade: 'B',
    siteId: 51,
    siteName: '캐슬 잠실 파인시티',
    siteCode: 'S-051',
    manager: '윤건설',
    contact: '010-6789-0123',
    deliveryAddress: '서울시 송파구 잠실동 300',
    receiverName: '윤건설',
    receiverPhone: '010-6789-0123',
    dueDate: '2026-02-10',
    scheduledShipDate: '미정',
    status: '수주확정',
    paymentStatus: '미입금',
    accountingStatus: '미확인',
    requireApproval: true,
    approvalStatus: '승인대기',
    approvalRequestedAt: '2025-12-17 17:00',
    requirePaymentBeforeShip: true,
    productionHold: true,
    productionHoldReason: '경리 승인 대기',
    invoiceIssued: false,
    taxInvoiceIssued: false,
    totalAmount: 36000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 36000000,
    paidAmount: 0,
    remainingAmount: 36000000,
    depositRequired: 18000000,
    deliveryMethod: '직접배차',
    items: [
      { id: 1, productCode: 'SH4028', productName: '스크린 셔터 (표준형)', floor: 'B1', location: 'F-01', spec: '4000×2800', qty: 2, unit: 'EA', unitPrice: 9000000, amount: 18000000, productionSpec: { type: '와이어', openWidth: 4000, openHeight: 2800, capacity: 300 } },
      { id: 2, productCode: 'SH4028', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'F-02', spec: '4000×2800', qty: 2, unit: 'EA', unitPrice: 9000000, amount: 18000000, productionSpec: { type: '와이어', openWidth: 4000, openHeight: 2800, capacity: 300 } },
    ],
    splits: [],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-17 17:00', changeType: '수주등록', description: '[통합테스트6] B등급 경리승인 필요', changedBy: '판매2팀 이영업' },
      { id: 2, changedAt: '2025-12-17 17:00', changeType: '승인요청', description: '경리팀에 생산 승인 요청', changedBy: '판매2팀 이영업' },
    ],
    createdAt: '2025-12-17',
    createdBy: '판매2팀 이영업',
    note: '[통합테스트6] B등급 경리승인 대기 - 생산보류',
  },

  // [통합테스트 7] 호반건설 - 써밋 광교 (A등급, 분할출하)
  {
    id: 207,
    orderNo: 'KD-TS-251217-07',
    lotNo: 'KD-TS-251217-07',
    quoteId: 207,
    quoteNo: 'KD-PR-251217-07',
    orderDate: '2025-12-17',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 7,
    customerCode: 'CUS-007',
    customerName: '호반건설(주)',
    creditGrade: 'A',
    siteId: 61,
    siteName: '써밋 광교 센트럴시티',
    siteCode: 'S-061',
    manager: '서건설',
    contact: '010-7890-1234',
    deliveryAddress: '경기도 수원시 영통구 광교동 400',
    receiverName: '서건설',
    receiverPhone: '010-7890-1234',
    dueDate: '2026-02-15',
    scheduledShipDate: '2026-02-10',
    status: '생산중',
    paymentStatus: '계약금입금',
    accountingStatus: '입금확인',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    taxInvoiceIssued: true,
    totalAmount: 48000000,
    discountRate: 5,
    discountAmount: 2400000,
    finalAmount: 45600000,
    paidAmount: 22800000,
    remainingAmount: 22800000,
    deliveryMethod: '화물',
    items: [
      { id: 1, productCode: 'SH3528', productName: '스크린 셔터 (표준형)', floor: 'B1', location: 'G-01', spec: '3500×2800', qty: 2, unit: 'EA', unitPrice: 8500000, amount: 17000000, productionSpec: { type: '와이어', openWidth: 3500, openHeight: 2800, capacity: 300 } },
      { id: 2, productCode: 'ST4030', productName: '철재 슬랫 셔터', floor: 'B2', location: 'G-02', spec: '4000×3000', qty: 2, unit: 'EA', unitPrice: 7500000, amount: 15000000, productionSpec: { type: '슬랫', openWidth: 4000, openHeight: 3000 } },
      { id: 3, productCode: 'SH5035', productName: '스크린 셔터 (대형)', floor: '1층', location: 'G-03', spec: '5000×3500', qty: 2, unit: 'EA', unitPrice: 8000000, amount: 16000000, productionSpec: { type: '와이어', openWidth: 5000, openHeight: 3500, capacity: 400 } },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251217-07-01', lotNo: 'KD-TS-251217-07', splitOrder: 1, splitType: '1차분할-스크린', itemIds: [1], dueDate: '2026-02-05', productionStatus: '작업완료', shipmentStatus: '배송완료', productionOrderNo: 'KD-WO-251217-07', totalQty: 2, completedQty: 2, remainingQty: 0 },
      { id: 2, splitNo: 'KD-TS-251217-07-02', lotNo: 'KD-TS-251217-07', splitOrder: 2, splitType: '2차분할-슬랫', itemIds: [2], dueDate: '2026-02-10', productionStatus: '작업완료', shipmentStatus: '출하준비', productionOrderNo: 'KD-WO-251217-08', totalQty: 2, completedQty: 2, remainingQty: 0 },
      { id: 3, splitNo: 'KD-TS-251217-07-03', lotNo: 'KD-TS-251217-07', splitOrder: 3, splitType: '3차분할-대형스크린', itemIds: [3], dueDate: '2026-02-15', productionStatus: '작업중', shipmentStatus: '미출고', productionOrderNo: 'KD-WO-251217-09', totalQty: 2, completedQty: 1, remainingQty: 1 },
    ],
    documentHistory: [
      { id: 1, docType: '거래명세서', sentAt: '2025-12-17 17:30', sentBy: '판매팀', sentMethod: '이메일', status: '발송완료' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-12-17 17:30', changeType: '수주등록', description: '[통합테스트7] 분할출하 3회 예정', changedBy: '판매1팀 박영업' },
      { id: 2, changedAt: '2026-02-05 16:00', changeType: '1차출하완료', description: 'B1 스크린 2대 배송완료', changedBy: '물류팀' },
    ],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 박영업',
    note: '[통합테스트7] 분할출하 - 1차완료, 2차준비, 3차생산중',
  },

  // [통합테스트 8] 한화건설 - 포레나 수지 (A등급, 추가분 수주)
  {
    id: 208,
    orderNo: 'KD-TS-251217-08',
    lotNo: 'KD-TS-251217-08',
    quoteId: 208,
    quoteNo: 'KD-PR-251217-08',
    orderDate: '2025-12-17',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 8,
    customerCode: 'CUS-008',
    customerName: '한화건설(주)',
    creditGrade: 'A',
    siteId: 71,
    siteName: '포레나 수지 더 센트럴',
    siteCode: 'S-071',
    manager: '한건설',
    contact: '010-8901-2345',
    deliveryAddress: '경기도 용인시 수지구 풍덕천동 500',
    receiverName: '한건설',
    receiverPhone: '010-8901-2345',
    dueDate: '2026-02-20',
    scheduledShipDate: '2026-02-18',
    status: '생산지시완료',
    paymentStatus: '전액입금',
    accountingStatus: '회계확인완료',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    taxInvoiceIssued: true,
    totalAmount: 16000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 16000000,
    paidAmount: 16000000,
    remainingAmount: 0,
    deliveryMethod: '상차',
    items: [
      { id: 1, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '4층', location: 'H-01', spec: '3000×2500', qty: 1, unit: 'EA', unitPrice: 8000000, amount: 8000000, productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, capacity: 300 } },
      { id: 2, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '5층', location: 'H-02', spec: '3000×2500', qty: 1, unit: 'EA', unitPrice: 8000000, amount: 8000000, productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, capacity: 300 } },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251217-08-01', lotNo: 'KD-TS-251217-08', splitOrder: 1, splitType: '일괄', itemIds: [1, 2], dueDate: '2026-02-20', productionStatus: '작업완료', shipmentStatus: '출하준비', productionOrderNo: 'KD-WO-251217-10', totalQty: 2, completedQty: 2, remainingQty: 0 },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-17 18:00', changeType: '수주등록', description: '[통합테스트8] 추가분 수주', changedBy: '판매2팀 최영업' },
    ],
    createdAt: '2025-12-17',
    createdBy: '판매2팀 최영업',
    note: '[통합테스트8] 추가분 수주 - 생산완료',
  },

  // [통합테스트 9] 태영건설 - 데시앙 동탄 (A등급, 품질불량→재작업)
  {
    id: 209,
    orderNo: 'KD-TS-251217-09',
    lotNo: 'KD-TS-251217-09',
    quoteId: 209,
    quoteNo: 'KD-PR-251217-09',
    orderDate: '2025-12-17',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 9,
    customerCode: 'CUS-009',
    customerName: '태영건설(주)',
    creditGrade: 'A',
    siteId: 81,
    siteName: '데시앙 동탄 파크뷰',
    siteCode: 'S-081',
    manager: '조건설',
    contact: '010-9012-3456',
    deliveryAddress: '경기도 화성시 동탄동 600',
    receiverName: '조건설',
    receiverPhone: '010-9012-3456',
    dueDate: '2026-02-25',
    scheduledShipDate: '2026-02-23',
    status: '재작업중',
    paymentStatus: '계약금입금',
    accountingStatus: '입금확인',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    taxInvoiceIssued: false,
    totalAmount: 33000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 33000000,
    paidAmount: 16500000,
    remainingAmount: 16500000,
    deliveryMethod: '직접배차',
    items: [
      { id: 1, productCode: 'SH4535', productName: '스크린 셔터 (프리미엄)', floor: '로비', location: 'I-01', spec: '4500×3500', qty: 1, unit: 'EA', unitPrice: 11000000, amount: 11000000, productionSpec: { type: '와이어', openWidth: 4500, openHeight: 3500, capacity: 400 } },
      { id: 2, productCode: 'SH4535', productName: '스크린 셔터 (프리미엄)', floor: '카페', location: 'I-02', spec: '4500×3500', qty: 1, unit: 'EA', unitPrice: 11000000, amount: 11000000, productionSpec: { type: '와이어', openWidth: 4500, openHeight: 3500, capacity: 400 } },
      { id: 3, productCode: 'SH4535', productName: '스크린 셔터 (프리미엄)', floor: '헬스장', location: 'I-03', spec: '4500×3500', qty: 1, unit: 'EA', unitPrice: 11000000, amount: 11000000, productionSpec: { type: '와이어', openWidth: 4500, openHeight: 3500, capacity: 400 } },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251217-09-01', lotNo: 'KD-TS-251217-09', splitOrder: 1, splitType: '일괄', itemIds: [1, 2, 3], dueDate: '2026-02-25', productionStatus: '재작업중', shipmentStatus: '미출고', productionOrderNo: 'KD-WO-251217-11', totalQty: 3, completedQty: 2, remainingQty: 1, hasQualityIssue: true, qualityIssueDescription: '1대 품질불량 발생 - 원단 불량으로 재작업' },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-12-17 18:30', changeType: '수주등록', description: '[통합테스트9] 프리미엄 스크린', changedBy: '판매1팀 김영업' },
      { id: 2, changedAt: '2026-02-15 14:00', changeType: '품질불량', description: '로비 1대 원단 불량 발생, 재작업 진행', changedBy: '품질팀 이품질' },
    ],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 김영업',
    note: '[통합테스트9] 품질불량 → 재작업 플로우 - 1대 재작업중',
  },

  // [통합테스트 10] 두산건설 - 위브 청라 (A등급, 전체 완료 시나리오)
  {
    id: 210,
    orderNo: 'KD-TS-251217-10',
    lotNo: 'KD-TS-251217-10',
    quoteId: 210,
    quoteNo: 'KD-PR-251217-10',
    orderDate: '2025-12-17',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 10,
    customerCode: 'CUS-010',
    customerName: '두산건설(주)',
    creditGrade: 'A',
    siteId: 91,
    siteName: '위브 청라 더 퍼스트',
    siteCode: 'S-091',
    manager: '임건설',
    contact: '010-0123-4567',
    deliveryAddress: '인천시 서구 청라동 700',
    receiverName: '임건설',
    receiverPhone: '010-0123-4567',
    dueDate: '2026-03-01',
    scheduledShipDate: '2026-02-27',
    status: '출하완료',
    paymentStatus: '전액입금',
    accountingStatus: '회계확인완료',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    invoiceIssuedAt: '2025-12-17 19:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-12-17 19:30',
    totalAmount: 40000000,
    discountRate: 3,
    discountAmount: 1200000,
    finalAmount: 38800000,
    paidAmount: 38800000,
    remainingAmount: 0,
    deliveryMethod: '상차',
    items: [
      { id: 1, productCode: 'SH3528', productName: '스크린 셔터 (표준형)', floor: 'B1', location: 'J-01', spec: '3500×2800', qty: 2, unit: 'EA', unitPrice: 8500000, amount: 17000000, productionSpec: { type: '와이어', openWidth: 3500, openHeight: 2800, capacity: 300 } },
      { id: 2, productCode: 'ST4030', productName: '철재 슬랫 셔터', floor: '1층', location: 'J-02', spec: '4000×3000', qty: 2, unit: 'EA', unitPrice: 7000000, amount: 14000000, productionSpec: { type: '슬랫', openWidth: 4000, openHeight: 3000 } },
      { id: 3, productCode: 'SH5035', productName: '스크린 셔터 (대형)', floor: '2층', location: 'J-03', spec: '5000×3500', qty: 1, unit: 'EA', unitPrice: 9000000, amount: 9000000, productionSpec: { type: '와이어', openWidth: 5000, openHeight: 3500, capacity: 400 } },
    ],
    splits: [
      { id: 1, splitNo: 'KD-TS-251217-10-01', lotNo: 'KD-TS-251217-10', splitOrder: 1, splitType: '일괄', itemIds: [1, 2, 3], dueDate: '2026-03-01', productionStatus: '작업완료', shipmentStatus: '배송완료', productionOrderNo: 'KD-WO-251217-12', totalQty: 5, completedQty: 5, remainingQty: 0 },
    ],
    documentHistory: [
      { id: 1, docType: '거래명세서', sentAt: '2025-12-17 19:00', sentBy: '판매팀', sentMethod: '이메일', status: '발송완료' },
      { id: 2, docType: '세금계산서', sentAt: '2025-12-17 19:30', sentBy: '회계팀', sentMethod: '전자발행', status: '발행완료' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-12-17 19:00', changeType: '수주등록', description: '[통합테스트10] 전체 완료 시나리오', changedBy: '판매2팀 이영업' },
      { id: 2, changedAt: '2025-12-18 09:00', changeType: '회계확인', description: '전액 입금 확인', changedBy: '회계팀 박회계' },
      { id: 3, changedAt: '2026-02-25 10:00', changeType: '생산완료', description: '전량 생산 완료', changedBy: '생산팀' },
      { id: 4, changedAt: '2026-02-27 16:00', changeType: '출하완료', description: '전량 배송 완료', changedBy: '물류팀' },
      { id: 5, changedAt: '2026-02-28 10:00', changeType: '수금완료', description: '잔금 수금 완료', changedBy: '회계팀' },
    ],
    createdAt: '2025-12-17',
    createdBy: '판매2팀 이영업',
    note: '[통합테스트10] 전체 완료 시나리오 - 견적→수주→생산→품질→출하→회계 완료',
  },
];

// 작업지시
const initialWorkOrders = [
  /*
   * ============================================================
   * 📋 생산 데이터 - 8개 테스트 시나리오 연동 (새 번호 체계)
   * ============================================================
   * [1] KD-WO-2502-001 ← KD-TS-2502-001-01 (시나리오1: 삼성물산 래미안 강남 1차) → 작업완료 ✅
   * [2] KD-WO-2502-002 ← KD-TS-2502-002-01 (시나리오2: 현대건설 힐스테이트 판교 스크린) → 작업완료
   * [3] KD-WO-2502-003 ← KD-TS-2502-002-02 (시나리오2: 현대건설 힐스테이트 판교 슬랫) → 작업완료
   * [4] KD-WO-2502-004 ← KD-TS-2502-001-A-01 (시나리오4: 삼성물산 래미안 강남 1차 추가분) → 작업중
   * [5] KD-WO-2502-005 ← KD-TS-2502-004-01 (시나리오5: 서울인테리어 오피스타워 1차) → 작업완료 ✅
   * [6] KD-WO-2502-006 ← KD-TS-2502-004-02 (시나리오5: 서울인테리어 오피스타워 2차) → 작업완료
   * [7] KD-WO-2502-007 ← KD-TS-2502-005-01 (시나리오6: 삼성물산 래미안 강남 2차 품질불량) → 재작업중 ⚠️
   * [8] KD-WO-2502-008 ← KD-TS-2502-006-01 (시나리오7: 현대건설 힐스테이트 용인 할인적용) → 작업중
   * [9] WO-2510-001 ← SO-2510-001-01 (시나리오8: 용산고등학교 직접수주) → 작업대기
   *
   * ※ 시나리오3 (대우건설 푸르지오 일산)은 경리승인 대기로 생산 미시작
   * ============================================================
   */

  // ========== 시나리오 1: A등급 정상 플로우 (삼성물산) - 작업완료 ==========
  {
    id: 1,
    workOrderNo: 'KD-PL-250207-01',
    orderNo: 'KD-SO-250205-01',
    splitNo: 'KD-SO-250205-01-01',
    lotNo: 'KD-TS-251201-01',  // 수주 로트번호
    shipRequestDate: '2025-12-18',  // 출고예정일
    orderDate: '2025-02-07',
    processType: '스크린',
    customerName: '삼성물산(주)',
    siteName: '강남 타워 신축현장',
    productName: '스크린 셔터 (표준형)',
    workPriority: 1,
    workSequence: 1, // 당일 작업 순서
    instruction: '1층 A구역 우선 작업, 절단 시 원단 방향 주의', // 작업 지시사항
    dueDate: '2025-03-01',
    status: '작업완료',
    priority: '긴급',
    assignee: '김스크린',
    assignedWorkers: ['김스크린', '이스크린'], // 스크린 공정 작업자 2명 배정
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '원단절단': { status: '완료', worker: '김스크린', completedAt: '2025-02-08 10:00' },
      '미싱': { status: '완료', worker: '이스크린', completedAt: '2025-02-09 14:00' },
      '앤드락작업': { status: '완료', worker: '김스크린', completedAt: '2025-02-10 11:00' },
      '중간검사': {
        status: '완료',
        inspector: '품질팀 이검사',
        result: '합격',
        completedAt: '2025-02-10 15:00',
        approvedBy: '품질팀장 최품질',
        inspectionLot: 'KD-SC-250210-01-(4)'
      },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-02-11 09:00', labelInfo: '1층 A-01,A-02' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-02-11 10:00',
    items: [
      { id: 1, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'A-01', spec: '7660×2550', qty: 1, lotNo: 'KD-TS-250211-01-01', materialLotNo: '250201-01' },
      { id: 2, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'A-02', spec: '6500×2400', qty: 1, lotNo: 'KD-TS-250211-01-02', materialLotNo: '250201-01' },
    ],
    issues: [],
    createdAt: '2025-02-07',
    createdBy: '판매팀 김판매',
    // 결재라인
    approval: {
      drafter: { name: '김판매', date: '2025-02-07', dept: '판매팀' },
      approver: { name: '박생산', date: '2025-02-07', dept: '생산관리' },
      cc: ['회계팀'],
    },
    approvalStatus: '승인완료', // 승인대기, 승인완료, 반려
  },

  // ========== 시나리오 2: B등급 입금 후 출고 (현대건설) - 스크린 작업완료 ==========
  {
    id: 2,
    workOrderNo: 'KD-PL-250210-01',
    orderNo: 'KD-SO-250208-01',
    splitNo: 'KD-SO-250208-01-01',
    lotNo: 'KD-TS-251208-01',  // 수주 로트번호
    shipRequestDate: '2026-01-03',  // 출고예정일
    orderDate: '2025-02-10',
    processType: '스크린',
    customerName: '현대건설(주)',
    siteName: '송도 오피스빌딩',
    productName: '스크린 셔터 (고급형)',
    workPriority: 2,
    workSequence: 2,
    instruction: '고급형 마감 처리, 미싱 라인 정밀 확인',
    dueDate: '2025-03-15',
    status: '작업완료',
    priority: '일반',
    assignee: '박스크린',
    assignedWorkers: ['박스크린'], // 스크린 공정 작업자 1명 배정
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '원단절단': { status: '완료', worker: '박스크린', completedAt: '2025-02-11 10:00' },
      '미싱': { status: '완료', worker: '박스크린', completedAt: '2025-02-12 14:00' },
      '앤드락작업': { status: '완료', worker: '박스크린', completedAt: '2025-02-13 11:00' },
      '중간검사': {
        status: '완료',
        inspector: '품질팀 이검사',
        result: '합격',
        completedAt: '2025-02-13 15:00',
        approvedBy: '품질팀장 최품질',
        inspectionLot: 'KD-SC-250213-01-(4)'
      },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-02-14 09:00', labelInfo: 'B1 C-01' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-02-14 10:00',
    items: [
      { id: 1, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: 'B1', location: 'C-01', spec: '6000×2400', qty: 2, lotNo: 'KD-TS-250214-01-01', materialLotNo: '250205-01' },
    ],
    issues: [],
    createdAt: '2025-02-10',
    createdBy: '판매팀 이판매',
    approval: {
      drafter: { name: '이판매', date: '2025-02-10', dept: '판매팀' },
      approver: { name: '박생산', date: '2025-02-10', dept: '생산관리' },
      cc: ['회계팀'],
    },
    approvalStatus: '승인완료',
  },

  // ========== 시나리오 2: B등급 입금 후 출고 (현대건설) - 슬랫 작업완료 ==========
  {
    id: 3,
    workOrderNo: 'KD-PL-250212-01',
    orderNo: 'KD-SO-250208-01',
    splitNo: 'KD-SO-250208-01-02',
    lotNo: 'KD-TS-251208-01',  // 수주 로트번호
    shipRequestDate: '2026-01-03',  // 출고예정일
    orderDate: '2025-02-12',
    processType: '슬랫',
    customerName: '현대건설(주)',
    siteName: '송도 오피스빌딩',
    productName: '슬랫 셔터',
    workPriority: 3,
    workSequence: 3,
    instruction: '코일 색상 확인 필수, B1층 설치용',
    dueDate: '2025-03-20',
    status: '작업완료',
    priority: '일반',
    assignee: '김슬랫',
    assignedWorkers: ['김슬랫', '이슬랫', '박슬랫'], // 슬랫 공정 팀 배정 (3명)
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '코일절단': { status: '완료', worker: '김슬랫', completedAt: '2025-02-13 10:00' },
      '중간검사': {
        status: '완료',
        inspector: '품질팀 이검사',
        result: '합격',
        completedAt: '2025-02-13 14:00',
        approvedBy: '품질팀장 최품질',
        inspectionLot: 'KD-SL-250213-01-(2)'
      },
      '미미작업': { status: '완료', worker: '이슬랫', completedAt: '2025-02-14 11:00' },
      '포장': { status: '완료', worker: '박슬랫', completedAt: '2025-02-14 15:00', labelInfo: '1층 D-01' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-02-14 16:00',
    items: [
      { id: 1, productCode: 'SLT-001', productName: '슬랫 셔터', floor: '1층', location: 'D-01', spec: '4500×2000', qty: 2, lotNo: 'KD-TS-250214-02-01', materialLotNo: '250203-01' },
    ],
    issues: [],
    createdAt: '2025-02-12',
    createdBy: '판매팀 이판매',
    approval: {
      drafter: { name: '이판매', date: '2025-02-12', dept: '판매팀' },
      approver: { name: '박생산', date: '2025-02-12', dept: '생산관리' },
      cc: ['회계팀'],
    },
    approvalStatus: '승인완료',
  },

  // ========== 시나리오 4: 추가분 수주 (삼성물산) - 작업중 ==========
  {
    id: 4,
    workOrderNo: 'KD-PL-250222-01',
    orderNo: 'KD-SO-250205-01-A',
    splitNo: 'KD-SO-250205-01-A-01',
    lotNo: 'KD-TS-251201-02',  // 수주 로트번호 (추가분)
    shipRequestDate: '2025-03-25',  // 출고예정일
    orderDate: '2025-02-22',
    processType: '스크린',
    customerName: '삼성물산(주)',
    siteName: '강남 타워 신축현장',
    productName: '스크린 셔터 (표준형) - 추가',
    workPriority: 4,
    workSequence: 1, // 오늘 첫번째 작업
    instruction: '추가분 주문, 기존 납품분과 동일 사양 유지',
    dueDate: '2025-03-25',
    status: '작업중',
    priority: '일반',
    assignee: '김스크린',
    assignedWorkers: ['김스크린', '이스크린', '박스크린'], // 스크린 공정 팀 배정 (3명)
    totalQty: 3,
    completedQty: 1,
    currentStep: '미싱',
    stepStatus: {
      '원단절단': { status: '완료', worker: '김스크린', completedAt: '2025-02-23 10:00' },
      '미싱': { status: '진행중', worker: '이스크린', startedAt: '2025-02-23 14:00' },
      '앤드락작업': { status: '대기' },
      '중간검사': { status: '대기' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'SCR-002', productName: '스크린 셔터 (프리미엄)', floor: '3층', location: 'C-01', spec: '8000×2800', qty: 3, lotNo: null, materialLotNo: '250220-01' },
    ],
    issues: [],
    createdAt: '2025-02-22',
    createdBy: '전진팀 최전진',
    approval: {
      drafter: { name: '최전진', date: '2025-02-22', dept: '전진팀' },
      approver: { name: '박생산', date: '2025-02-22', dept: '생산관리' },
      cc: ['회계팀'],
    },
    approvalStatus: '승인완료',
  },

  // ========== 시나리오 5: 분할 출하 (서울인테리어) - 1차분 작업완료 ==========
  {
    id: 5,
    workOrderNo: 'KD-PL-250215-01',
    orderNo: 'KD-SO-250212-01',
    splitNo: 'KD-SO-250212-01-01',
    lotNo: 'KD-TS-251212-01',  // 수주 로트번호
    shipRequestDate: '2025-03-15',  // 출고예정일
    orderDate: '2025-02-15',
    processType: '스크린',
    customerName: '(주)서울인테리어',
    siteName: '해운대 타워',
    productName: '스크린 셔터 (고급형)',
    workPriority: 5,
    workSequence: 4,
    instruction: '1차 분할 출하, 포장 시 출하 구분 라벨 부착',
    dueDate: '2025-03-15',
    status: '작업완료',
    priority: '긴급',
    assignee: '김스크린',
    assignedWorkers: ['김스크린', '이스크린'], // 스크린 공정 작업자 2명 배정
    totalQty: 3,
    completedQty: 3,
    currentStep: '포장',
    stepStatus: {
      '원단절단': { status: '완료', worker: '김스크린', completedAt: '2025-02-16 10:00' },
      '미싱': { status: '완료', worker: '이스크린', completedAt: '2025-02-17 14:00' },
      '앤드락작업': { status: '완료', worker: '김스크린', completedAt: '2025-02-18 11:00' },
      '중간검사': {
        status: '완료',
        inspector: '품질팀 이검사',
        result: '합격',
        completedAt: '2025-02-18 15:00',
        approvedBy: '품질팀장 최품질',
        inspectionLot: 'KD-SC-250218-01-(4)'
      },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-02-19 09:00', labelInfo: '1층 E-01' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-02-19 10:00',
    items: [
      { id: 1, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'E-01', spec: '7000×2500', qty: 3, lotNo: 'KD-TS-250219-01-01', materialLotNo: '250210-01' },
    ],
    issues: [],
    createdAt: '2025-02-15',
    createdBy: '판매팀 김판매',
    approval: {
      drafter: { name: '김판매', date: '2025-02-15', dept: '판매팀' },
      approver: { name: '박생산', date: '2025-02-15', dept: '생산관리' },
      cc: ['회계팀'],
    },
    approvalStatus: '승인완료',
  },

  // ========== 시나리오 5: 분할 출하 (서울인테리어) - 2차분 작업완료 ==========
  {
    id: 6,
    workOrderNo: 'KD-PL-250217-01',
    orderNo: 'KD-SO-250212-01',
    splitNo: 'KD-SO-250212-01-02',
    lotNo: 'KD-TS-251212-01',  // 수주 로트번호 (동일 수주)
    shipRequestDate: '2025-03-25',  // 출고예정일
    orderDate: '2025-02-17',
    processType: '슬랫',
    customerName: '(주)서울인테리어',
    siteName: '해운대 타워',
    productName: '슬랫 셔터 (고급형)',
    workPriority: 6,
    workSequence: 5,
    instruction: '2차 분할 출하, 1차와 동일 품질 기준 적용',
    dueDate: '2025-03-25',
    status: '작업완료',
    priority: '일반',
    assignee: '박슬랫',
    assignedWorkers: ['박슬랫', '이슬랫'], // 슬랫 공정 작업자 2명 배정
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '코일절단': { status: '완료', worker: '박슬랫', completedAt: '2025-02-18 10:00' },
      '중간검사': {
        status: '완료',
        inspector: '품질팀 이검사',
        result: '합격',
        completedAt: '2025-02-18 14:00',
        approvedBy: '품질팀장 최품질',
        inspectionLot: 'KD-SL-250218-02-(2)'
      },
      '미미작업': { status: '완료', worker: '이슬랫', completedAt: '2025-02-19 11:00' },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-02-19 15:00', labelInfo: '2층 F-01' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-02-19 16:00',
    items: [
      { id: 1, productCode: 'SLT-001', productName: '슬랫 셔터', floor: '2층', location: 'F-01', spec: '5000×2200', qty: 2, lotNo: 'KD-TS-250219-02-01', materialLotNo: '250210-02' },
    ],
    issues: [],
    createdAt: '2025-02-17',
    createdBy: '판매팀 김판매',
    approval: {
      drafter: { name: '김판매', date: '2025-02-17', dept: '판매팀' },
      approver: { name: '박생산', date: '2025-02-17', dept: '생산관리' },
      cc: ['회계팀'],
    },
    approvalStatus: '승인완료',
  },

  // ========== 시나리오 6: 품질 불량 (삼성물산) - 재작업중 ⚠️ ==========
  {
    id: 7,
    workOrderNo: 'KD-PL-250218-01',
    orderNo: 'KD-SO-250215-01',
    splitNo: 'KD-SO-250215-01-01',
    lotNo: 'KD-TS-251215-01',  // 수주 로트번호
    shipRequestDate: '2025-03-15',  // 출고예정일
    orderDate: '2025-02-18',
    processType: '슬랫',
    customerName: '삼성물산(주)',
    siteName: '강남 타워 신축현장 (B동)',
    productName: '슬랫 셔터 (특수)',
    workPriority: 1,
    workSequence: 2, // 긴급이라 우선순위 높음
    instruction: '⚠️ 재작업 건, 치수 ±5mm 준수 필수, 품질팀 입회 검사',
    dueDate: '2025-03-15',
    status: '재작업중',
    priority: '긴급',
    assignee: '김슬랫',
    assignedWorkers: ['김슬랫', '이슬랫'], // 슬랫 공정 작업자 2명 배정
    totalQty: 4,
    completedQty: 2,
    currentStep: '코일절단',
    stepStatus: {
      '코일절단': {
        status: '재작업',
        worker: '김슬랫',
        completedAt: '2025-02-19 10:00',
        reworkStartedAt: '2025-02-20 09:00',
        reworkReason: '치수불량 2EA 재작업'
      },
      '중간검사': {
        status: '불합격',
        inspector: '품질팀 이검사',
        result: '불합격',
        completedAt: '2025-02-19 14:00',
        failReason: '치수불량 - 4500mm 기준 ±5mm 초과 (2EA)',
        inspectionLot: 'KD-SL-250219-01-(2)',
        reworkRequired: true,
        reworkQty: 2
      },
      '미미작업': { status: '대기' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'SLT-001', productName: '슬랫 셔터', floor: '1층', location: 'H-01', spec: '4500×2000', qty: 4, lotNo: null, materialLotNo: '250215-01' },
    ],
    issues: [
      {
        id: 1,
        issueType: '불량품발생',
        description: '중간검사 불합격 - 치수불량 2EA (4500mm 기준 ±10mm 초과)',
        reportedBy: '품질팀 이검사',
        reportedAt: '2025-02-19 14:30',
        status: '처리중',
        resolvedBy: null,
        resolvedAt: null,
        resolution: null,
        actionTaken: '재작업 지시 - 코일 재절단 진행'
      },
    ],
    qualityIssue: {
      hasIssue: true,
      inspectionLot: 'KD-SL-250219-01-(2)',
      failedQty: 2,
      passedQty: 2,
      failReason: '치수불량',
      reworkStatus: '재작업중',
      reworkStartDate: '2025-02-20',
      expectedCompletionDate: '2025-02-22'
    },
    createdAt: '2025-02-18',
    createdBy: '판매팀 이판매',
    approval: {
      drafter: { name: '이판매', date: '2025-02-18', dept: '판매팀' },
      approver: { name: '박생산', date: '2025-02-18', dept: '생산관리' },
      cc: ['회계팀'],
    },
    approvalStatus: '승인완료',
  },

  // ========== 시나리오 7: 할인 적용 (현대건설) - 작업중 ==========
  {
    id: 8,
    workOrderNo: 'KD-PL-250220-01',
    orderNo: 'KD-SO-250218-01',
    splitNo: 'KD-SO-250218-01-01',
    lotNo: 'KD-TS-251218-01',  // 수주 로트번호
    shipRequestDate: '2025-04-05',  // 출고예정일
    orderDate: '2025-02-20',
    processType: '스크린',
    customerName: '현대건설(주)',
    siteName: '연수 오피스텔',
    productName: '스크린 셔터 (표준형)',
    workPriority: 2,
    workSequence: 3,
    instruction: '할인 적용 건, 표준 공정 준수',
    dueDate: '2025-04-05',
    status: '작업중',
    priority: '일반',
    assignee: '박스크린',
    assignedWorkers: ['박스크린', '이스크린'], // 스크린 공정 작업자 2명 배정
    totalQty: 6,
    completedQty: 2,
    currentStep: '앤드락작업',
    stepStatus: {
      '원단절단': { status: '완료', worker: '박스크린', completedAt: '2025-02-21 10:00' },
      '미싱': { status: '완료', worker: '이스크린', completedAt: '2025-02-22 14:00' },
      '앤드락작업': { status: '진행중', worker: '박스크린', startedAt: '2025-02-23 09:00' },
      '중간검사': { status: '대기' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'I-01', spec: '6000×2400', qty: 6, lotNo: null, materialLotNo: '250218-01' },
    ],
    issues: [],
    createdAt: '2025-02-20',
    createdBy: '판매팀 이판매',
    approval: {
      drafter: { name: '이판매', date: '2025-02-20', dept: '판매팀' },
      approver: { name: '박생산', date: '2025-02-20', dept: '생산관리' },
      cc: ['회계팀'],
    },
    approvalStatus: '승인완료',
  },

  // ========== 시나리오 8: 발주서 양식 테스트 (용산고등학교) - 작업대기 ==========
  {
    id: 9,
    workOrderNo: 'KD-PL-251016-01',
    orderNo: 'KD-WE-251015-01',
    splitNo: 'KD-WE-251015-01-01',
    lotNo: 'KD-TS-251015-01',  // 수주 로트번호
    shipRequestDate: '2025-10-30',  // 출고예정일
    orderDate: '2025-10-16',
    processType: '스크린',
    customerName: '주말건설',
    siteName: '용산고등학교(4층)',
    productName: '스크린 셔터 (학교용)',
    workPriority: 3,
    workSequence: 6,
    instruction: '학교 시설용, 안전 기준 강화, 대량 작업 - 팀 전원 투입',
    dueDate: '2025-10-30',
    status: '작업대기',
    priority: '일반',
    assignee: '김스크린',
    assignedWorkers: ['김스크린', '이스크린', '박스크린'], // 스크린 공정 팀 배정 (3명) - 대량 작업
    totalQty: 11,
    completedQty: 0,
    currentStep: null,
    stepStatus: {
      '원단절단': { status: '대기' },
      '미싱': { status: '대기' },
      '앤드락작업': { status: '대기' },
      '중간검사': { status: '대기' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터', floor: '4층', location: 'FSS1', spec: '7260×2600', qty: 1 },
      { id: 2, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터', floor: '4층', location: 'FSS5', spec: '4560×2600', qty: 1 },
      { id: 3, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터', floor: '4층', location: 'FSS17A', spec: '6650×2600', qty: 1 },
      { id: 4, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터', floor: '4층', location: 'FSS3', spec: '3560×2600', qty: 1 },
      { id: 5, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터', floor: '4층', location: 'FSS7', spec: '5860×2600', qty: 1 },
      { id: 6, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터', floor: '4층', location: 'FSS16', spec: '7160×2600', qty: 1 },
      { id: 7, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터', floor: '4층', location: 'FSS3-2', spec: '3560×2600', qty: 1 },
      { id: 8, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터', floor: '4층', location: 'FSS6', spec: '5760×2600', qty: 1 },
      { id: 9, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터', floor: '4층', location: 'FSS3-3', spec: '3770×2600', qty: 1 },
      { id: 10, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터', floor: '4층', location: 'FSS17', spec: '7260×2600', qty: 1 },
      { id: 11, productCode: 'SCR-WE-001', productName: '국민방화스크린셔터', floor: '4층', location: 'FSS15', spec: '6860×2600', qty: 1 },
    ],
    issues: [],
    createdAt: '2025-10-16',
    createdBy: '전진팀 최전진',
    approval: {
      drafter: { name: '최전진', date: '2025-10-16', dept: '전진팀' },
      approver: null, // 승인 대기
      cc: ['회계팀'],
    },
    approvalStatus: '승인대기', // 이 건은 아직 승인 대기 상태
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // E2E 테스트용 작업지시 데이터 (수주 101-105 연결)
  // ═══════════════════════════════════════════════════════════════════════════

  // WO-E2E-01: 강남 오피스 A동 스크린 (수주101 → 작업지시) - 작업중
  {
    id: 101,
    workOrderNo: 'KD-WO-251216-01',
    orderNo: 'KD-TS-251216-01',
    splitNo: 'KD-TS-251216-01-01',
    lotNo: 'KD-TS-251216-01',  // 수주 로트번호
    shipRequestDate: '2025-12-30',  // 출고예정일
    orderDate: '2025-12-16',
    processType: '스크린',
    customerName: '삼성물산(주)',
    siteName: '[E2E테스트] 강남 오피스 A동',
    productName: '스크린 셔터 (표준형)',
    workPriority: 1,
    workSequence: 1,
    instruction: 'E2E 테스트 - A동 스크린, 표준 사양',
    dueDate: '2025-12-30',
    status: '작업중',
    priority: '긴급',
    assignee: '김스크린',
    assignedWorkers: ['김스크린', '이스크린'], // 스크린 공정 작업자 2명 배정
    totalQty: 3,
    completedQty: 1,
    currentStep: '미싱',
    stepStatus: {
      '원단절단': { status: '완료', worker: '김스크린', completedAt: '2025-12-17 10:00' },
      '미싱': { status: '진행중', worker: '이스크린', startedAt: '2025-12-17 14:00' },
      '앤드락작업': { status: '대기' },
      '중간검사': { status: '대기' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'SCR-E2E-001', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'A-01', spec: '3000×2500', qty: 1, lotNo: 'KD-TS-E2E-01-01' },
      { id: 2, productCode: 'SCR-E2E-001', productName: '스크린 셔터 (표준형)', floor: '2층', location: 'A-02', spec: '3000×2500', qty: 1, lotNo: null },
      { id: 3, productCode: 'SCR-E2E-001', productName: '스크린 셔터 (표준형)', floor: '3층', location: 'A-03', spec: '3000×2500', qty: 1, lotNo: null },
    ],
    issues: [],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    approval: { drafter: { name: '시스템', date: '2025-12-16', dept: 'E2E' }, approver: { name: '생산팀', date: '2025-12-16', dept: '생산' }, cc: [] },
    approvalStatus: '승인완료',
  },

  // WO-E2E-02: 판교 물류센터 슬랫 (수주102 → 작업지시) - 작업완료
  {
    id: 102,
    workOrderNo: 'KD-WO-251216-02',
    orderNo: 'KD-TS-251216-02',
    splitNo: 'KD-TS-251216-02-01',
    lotNo: 'KD-TS-251216-02',  // 수주 로트번호
    shipRequestDate: '2025-12-28',  // 출고예정일
    orderDate: '2025-12-16',
    processType: '슬랫',
    customerName: '현대건설(주)',
    siteName: '[E2E테스트] 판교 물류센터',
    productName: '철재 슬랫 셔터',
    workPriority: 2,
    dueDate: '2025-12-28',
    status: '작업완료',
    priority: '일반',
    assignee: '김슬랫',
    assignedWorkers: ['김슬랫', '박슬랫'], // 슬랫 공정 작업자 2명 배정
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '코일절단': { status: '완료', worker: '김슬랫', completedAt: '2025-12-17 09:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-17 14:00', inspectionLot: 'KD-SL-E2E-01-(2)' },
      '미미작업': { status: '완료', worker: '박슬랫', completedAt: '2025-12-18 10:00' },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-12-18 14:00', labelInfo: 'B1 C-01, B2 C-02' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-18 15:00',
    items: [
      { id: 1, productCode: 'STL-E2E-001', productName: '철재 슬랫 셔터', floor: 'B1', location: 'C-01', spec: '4000×3000', qty: 1, lotNo: 'KD-TS-E2E-02-01' },
      { id: 2, productCode: 'STL-E2E-001', productName: '철재 슬랫 셔터', floor: 'B2', location: 'C-02', spec: '4000×3000', qty: 1, lotNo: 'KD-TS-E2E-02-02' },
    ],
    issues: [],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    approval: { drafter: { name: '시스템', date: '2025-12-16', dept: 'E2E' }, approver: { name: '생산팀', date: '2025-12-16', dept: '생산' }, cc: [] },
    approvalStatus: '승인완료',
  },

  // WO-E2E-03: 송도 아파트 스크린 (수주103-01 → 작업지시) - 작업완료
  {
    id: 103,
    workOrderNo: 'KD-WO-251216-03',
    orderNo: 'KD-TS-251216-03',
    splitNo: 'KD-TS-251216-03-01',
    lotNo: 'KD-TS-251216-03',  // 수주 로트번호
    shipRequestDate: '2025-12-23',  // 출고예정일
    orderDate: '2025-12-16',
    processType: '스크린',
    customerName: '대우건설(주)',
    siteName: '[E2E테스트] 송도 아파트 B동',
    productName: '스크린 셔터 혼합',
    workPriority: 3,
    dueDate: '2025-12-23',
    status: '작업완료',
    priority: '일반',
    assignee: '이스크린',
    assignedWorkers: ['이스크린'], // 스크린 공정 작업자 1명 배정
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '원단절단': { status: '완료', worker: '이스크린', completedAt: '2025-12-18 10:00' },
      '미싱': { status: '완료', worker: '이스크린', completedAt: '2025-12-19 10:00' },
      '앤드락작업': { status: '완료', worker: '이스크린', completedAt: '2025-12-20 10:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-20 14:00', inspectionLot: 'KD-SC-E2E-02-(2)' },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-12-21 10:00', labelInfo: '1층 D-01, 2층 D-03' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-21 11:00',
    items: [
      { id: 1, productCode: 'SCR-E2E-002', productName: '스크린 셔터 (대형)', floor: '1층', location: 'D-01', spec: '6000×4000', qty: 1, lotNo: 'KD-TS-E2E-03-01' },
      { id: 2, productCode: 'SCR-E2E-002', productName: '스크린 셔터 (표준형)', floor: '2층', location: 'D-03', spec: '3000×2500', qty: 1, lotNo: 'KD-TS-E2E-03-02' },
    ],
    issues: [],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    approval: { drafter: { name: '시스템', date: '2025-12-16', dept: 'E2E' }, approver: { name: '생산팀', date: '2025-12-16', dept: '생산' }, cc: [] },
    approvalStatus: '승인완료',
  },

  // WO-E2E-04: 송도 아파트 슬랫 (수주103-02 → 작업지시) - 작업완료
  {
    id: 104,
    workOrderNo: 'KD-WO-251216-04',
    orderNo: 'KD-TS-251216-03',
    splitNo: 'KD-TS-251216-03-02',
    lotNo: 'KD-TS-251216-03',  // 수주 로트번호 (동일 수주)
    shipRequestDate: '2025-12-25',  // 출고예정일
    orderDate: '2025-12-16',
    processType: '슬랫',
    customerName: '대우건설(주)',
    siteName: '[E2E테스트] 송도 아파트 B동',
    productName: '철재 슬랫 셔터',
    workPriority: 4,
    dueDate: '2025-12-25',
    status: '작업완료',
    priority: '일반',
    assignee: '이슬랫',
    assignedWorkers: ['이슬랫', '박슬랫'], // 슬랫 공정 작업자 2명 배정
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '코일절단': { status: '완료', worker: '이슬랫', completedAt: '2025-12-19 09:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-19 14:00', inspectionLot: 'KD-SL-E2E-02-(2)' },
      '미미작업': { status: '완료', worker: '박슬랫', completedAt: '2025-12-20 10:00' },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-12-20 14:00', labelInfo: '1층 D-02' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-20 15:00',
    items: [
      { id: 1, productCode: 'STL-E2E-002', productName: '철재 슬랫 셔터', floor: '1층', location: 'D-02', spec: '3500×2500', qty: 2, lotNo: 'KD-TS-E2E-04-01' },
    ],
    issues: [],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    approval: { drafter: { name: '시스템', date: '2025-12-16', dept: 'E2E' }, approver: { name: '생산팀', date: '2025-12-16', dept: '생산' }, cc: [] },
    approvalStatus: '승인완료',
  },

  // WO-E2E-05: 용산 호텔 대형 스크린 (수주104 → 작업지시) - 작업대기 (승인대기)
  {
    id: 105,
    workOrderNo: 'KD-WO-251216-05',
    orderNo: 'KD-TS-251216-04',
    splitNo: 'KD-TS-251216-04-01',
    lotNo: 'KD-TS-251216-04',  // 수주 로트번호
    shipRequestDate: '2025-12-31',  // 출고예정일
    orderDate: '2025-12-16',
    processType: '스크린',
    customerName: '(주)서울인테리어',
    siteName: '[E2E테스트] 용산 호텔',
    productName: '스크린 셔터 (대형)',
    workPriority: 5,
    dueDate: '2025-12-31',
    status: '작업대기',
    priority: '일반',
    assignee: null,
    assignedWorkers: [], // 승인대기로 작업자 미배정
    totalQty: 2,
    completedQty: 0,
    currentStep: null,
    stepStatus: {
      '원단절단': { status: '대기' },
      '미싱': { status: '대기' },
      '앤드락작업': { status: '대기' },
      '중간검사': { status: '대기' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'SCR-E2E-003', productName: '스크린 셔터 (대형)', floor: '로비', location: 'E-01', spec: '6000×4000', qty: 1 },
      { id: 2, productCode: 'SCR-E2E-003', productName: '스크린 셔터 (대형)', floor: '연회장', location: 'E-02', spec: '6000×4000', qty: 1 },
    ],
    issues: [{ id: 1, type: '일정지연', description: 'B등급 거래처 - 경리승인 대기중', reportedBy: '시스템', reportedAt: '2025-12-16', resolved: false }],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    approval: { drafter: { name: '시스템', date: '2025-12-16', dept: 'E2E' }, approver: null, cc: ['회계팀'] },
    approvalStatus: '승인대기',
  },

  // WO-E2E-06: 삼성타운 1차 스크린 (수주105-01 → 작업지시) - 작업완료
  {
    id: 106,
    workOrderNo: 'KD-WO-251216-06',
    orderNo: 'KD-TS-251216-05',
    splitNo: 'KD-TS-251216-05-01',
    lotNo: 'KD-TS-251216-05',  // 수주 로트번호
    shipRequestDate: '2025-12-28',  // 출고예정일
    orderDate: '2025-12-16',
    processType: '스크린',
    customerName: '삼성물산(주)',
    siteName: '[E2E테스트] 삼성타운 종합',
    productName: '스크린 셔터 (표준형)',
    workPriority: 6,
    dueDate: '2025-12-28',
    status: '작업완료',
    priority: '일반',
    assignee: '박스크린',
    assignedWorkers: ['박스크린'], // 스크린 공정 작업자 1명 배정
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '원단절단': { status: '완료', worker: '박스크린', completedAt: '2025-12-19 10:00' },
      '미싱': { status: '완료', worker: '박스크린', completedAt: '2025-12-20 10:00' },
      '앤드락작업': { status: '완료', worker: '박스크린', completedAt: '2025-12-21 10:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-21 14:00', inspectionLot: 'KD-SC-E2E-03-(2)' },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-12-22 10:00', labelInfo: '1층 F-01' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-22 11:00',
    items: [
      { id: 1, productCode: 'SCR-E2E-004', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'F-01', spec: '3500×2800', qty: 2, lotNo: 'KD-TS-E2E-06-01' },
    ],
    issues: [],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    approval: { drafter: { name: '시스템', date: '2025-12-16', dept: 'E2E' }, approver: { name: '생산팀', date: '2025-12-16', dept: '생산' }, cc: [] },
    approvalStatus: '승인완료',
  },

  // WO-E2E-07: 삼성타운 2차 슬랫 (수주105-02 → 작업지시) - 작업완료
  {
    id: 107,
    workOrderNo: 'KD-WO-251216-07',
    orderNo: 'KD-TS-251216-05',
    splitNo: 'KD-TS-251216-05-02',
    lotNo: 'KD-TS-251216-05',  // 수주 로트번호 (동일 수주)
    shipRequestDate: '2026-01-05',  // 출고예정일
    orderDate: '2025-12-16',
    processType: '슬랫',
    customerName: '삼성물산(주)',
    siteName: '[E2E테스트] 삼성타운 종합',
    productName: '철재 슬랫 셔터',
    workPriority: 7,
    dueDate: '2026-01-05',
    status: '작업완료',
    priority: '일반',
    assignee: '김슬랫',
    assignedWorkers: ['김슬랫', '이슬랫', '박슬랫'], // 슬랫 공정 팀 배정 (3명)
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '코일절단': { status: '완료', worker: '김슬랫', completedAt: '2025-12-23 09:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-23 14:00', inspectionLot: 'KD-SL-E2E-03-(2)' },
      '미미작업': { status: '완료', worker: '이슬랫', completedAt: '2025-12-24 10:00' },
      '포장': { status: '완료', worker: '박슬랫', completedAt: '2025-12-24 14:00', labelInfo: '2층 F-02' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-24 15:00',
    items: [
      { id: 1, productCode: 'STL-E2E-003', productName: '철재 슬랫 셔터', floor: '2층', location: 'F-02', spec: '4500×3200', qty: 2, lotNo: 'KD-TS-E2E-07-01' },
    ],
    issues: [],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    approval: { drafter: { name: '시스템', date: '2025-12-16', dept: 'E2E' }, approver: { name: '생산팀', date: '2025-12-16', dept: '생산' }, cc: [] },
    approvalStatus: '승인완료',
  },

  // WO-E2E-08: 삼성타운 3차 대형스크린 (수주105-03 → 작업지시) - 작업중
  {
    id: 108,
    workOrderNo: 'KD-WO-251216-08',
    orderNo: 'KD-TS-251216-05',
    splitNo: 'KD-TS-251216-05-03',
    lotNo: 'KD-TS-251216-05',  // 수주 로트번호 (동일 수주)
    shipRequestDate: '2026-01-15',  // 출고예정일
    orderDate: '2025-12-16',
    processType: '스크린',
    customerName: '삼성물산(주)',
    siteName: '[E2E테스트] 삼성타운 종합',
    productName: '스크린 셔터 (대형)',
    workPriority: 8,
    dueDate: '2026-01-15',
    status: '작업중',
    priority: '일반',
    assignee: '김스크린',
    assignedWorkers: ['김스크린', '박스크린'], // 스크린 공정 작업자 2명 배정
    totalQty: 2,
    completedQty: 1,
    currentStep: '앤드락작업',
    stepStatus: {
      '원단절단': { status: '완료', worker: '김스크린', completedAt: '2025-12-26 10:00' },
      '미싱': { status: '완료', worker: '박스크린', completedAt: '2025-12-27 10:00' },
      '앤드락작업': { status: '진행중', worker: '김스크린', startedAt: '2025-12-28 09:00' },
      '중간검사': { status: '대기' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'SCR-E2E-005', productName: '스크린 셔터 (대형)', floor: '3층', location: 'F-03', spec: '5000×3500', qty: 2, lotNo: 'KD-TS-E2E-08-01' },
    ],
    issues: [],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    approval: { drafter: { name: '시스템', date: '2025-12-16', dept: 'E2E' }, approver: { name: '생산팀', date: '2025-12-16', dept: '생산' }, cc: [] },
    approvalStatus: '승인완료',
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // 절곡 공정 작업지시 데이터 (전개도 포함)
  // ═══════════════════════════════════════════════════════════════════════════

  // WO-FLD-01: 강남 타워 절곡 (작업완료)
  {
    id: 201,
    workOrderNo: 'KD-WO-FLD-251210-01',
    orderNo: 'KD-TS-251210-01',
    splitNo: 'KD-TS-251210-01-01',
    lotNo: 'KD-TS-251210-01',
    shipRequestDate: '2025-12-25',
    orderDate: '2025-12-10',
    processType: '절곡',
    customerName: '삼성물산(주)',
    siteName: '강남 타워 신축현장',
    productName: '방화셔터 절곡 부품',
    workPriority: 1,
    dueDate: '2025-12-25',
    status: '작업완료',
    priority: '긴급',
    assignee: '최절곡',
    assignedWorkers: ['최절곡', '김절곡'], // 절곡 공정 작업자 2명 배정
    totalQty: 1,
    completedQty: 1,
    currentStep: '포장',
    stepStatus: {
      '절단': { status: '완료', worker: '최절곡', completedAt: '2025-12-11 10:00' },
      '절곡': { status: '완료', worker: '김절곡', completedAt: '2025-12-12 14:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-12 16:00', inspectionLot: 'KD-FLD-251212-01-(1)' },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-12-13 10:00', labelInfo: '1층 G-01' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-13 11:00',
    items: [
      { id: 1, productCode: 'FLD-001', productName: '방화셔터 절곡 부품 SET', floor: '1층', location: 'G-01', spec: '3000×4000', qty: 1, lotNo: 'KD-TS-FLD-01-01' },
    ],
    // 전개도 상세정보 (절곡 공정 전용)
    developedParts: [
      { itemCode: 'SD30', itemName: '엘바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 4, weight: 0.9, dimensions: '75', note: '' },
      { itemCode: 'SD31', itemName: '하장바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 1.158, dimensions: '67→126→165→178→193', note: '' },
      { itemCode: 'SD32', itemName: '짜부가스켓', material: 'E.G.I 0.8T', totalWidth: 500, length: 3000, qty: 4, weight: 0.576, dimensions: '48', note: '80*4,50*8' },
      { itemCode: 'SD33', itemName: '가이드레일', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 2.304, dimensions: '40→80→42.5→25', note: '' },
      { itemCode: 'SD34', itemName: '바텀바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.44, dimensions: '30→95→30', note: '' },
      { itemCode: 'SD35', itemName: '바텀커버', material: 'E.G.I 1.2T', totalWidth: 500, length: 3000, qty: 1, weight: 0.864, dimensions: '65→50→16.5→25', note: '' },
      { itemCode: 'SD36', itemName: '전면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.92, dimensions: '25→210→140→30→50→28', note: '' },
      { itemCode: 'SD37', itemName: '후면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.728, dimensions: '25→165→90→155', note: '' },
      { itemCode: 'SD38', itemName: '측면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 0.96, dimensions: '35→50→35', note: '' },
      { itemCode: 'SD39', itemName: '상부덮개', material: 'E.G.I 1.2T', totalWidth: 500, length: 3000, qty: 1, weight: 0.648, dimensions: '25→140→330→25', note: '' },
    ],
    issues: [],
    createdAt: '2025-12-10',
    createdBy: '전진팀 최전진',
    approval: { drafter: { name: '최전진', date: '2025-12-10', dept: '전진팀' }, approver: { name: '박생산', date: '2025-12-10', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // WO-FLD-02: 판교 물류센터 절곡 (작업중)
  {
    id: 202,
    workOrderNo: 'KD-WO-FLD-251212-01',
    orderNo: 'KD-TS-251212-01',
    splitNo: 'KD-TS-251212-01-01',
    lotNo: 'KD-TS-251212-01',
    shipRequestDate: '2025-12-28',
    orderDate: '2025-12-12',
    processType: '절곡',
    customerName: '현대건설(주)',
    siteName: '판교 물류센터',
    productName: '방연셔터 절곡 부품',
    workPriority: 2,
    dueDate: '2025-12-28',
    status: '작업중',
    priority: '일반',
    assignee: '이절곡',
    assignedWorkers: ['이절곡', '박절곡', '최절곡'], // 절곡 공정 팀 배정 (3명)
    totalQty: 2,
    completedQty: 1,
    currentStep: '절곡',
    stepStatus: {
      '절단': { status: '완료', worker: '이절곡', completedAt: '2025-12-13 10:00' },
      '절곡': { status: '진행중', worker: '박절곡', startedAt: '2025-12-14 09:00' },
      '중간검사': { status: '대기' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'FLD-002', productName: '방연셔터 절곡 부품 SET', floor: 'B1', location: 'H-01', spec: '4000×3500', qty: 2, lotNo: null },
    ],
    // 전개도 상세정보 (절곡 공정 전용)
    developedParts: [
      { itemCode: 'SD40', itemName: '벽면형 마감재', material: 'E.G.I 1.15T', totalWidth: 450, length: 4000, qty: 4, weight: 1.2, dimensions: '30→60→30', note: '' },
      { itemCode: 'SD41', itemName: '가이드레일(벽면형)', material: 'E.G.I 1.6T', totalWidth: 500, length: 4000, qty: 2, weight: 3.072, dimensions: '40→80→42.5→25', note: '' },
      { itemCode: 'SD42', itemName: 'C형 레일', material: 'E.G.I 1.55T', totalWidth: 400, length: 4000, qty: 2, weight: 2.4, dimensions: '35→50→35', note: '' },
      { itemCode: 'SD43', itemName: 'D형 레일', material: 'E.G.I 1.55T', totalWidth: 380, length: 4000, qty: 2, weight: 2.28, dimensions: '40→45→40', note: '' },
      { itemCode: 'SD44', itemName: '하부BASE', material: 'E.G.I 1.55T', totalWidth: 280, length: 4000, qty: 2, weight: 1.68, dimensions: '130→80', note: '벽면형 하부' },
      { itemCode: 'SD45', itemName: '하단마감재', material: 'E.G.I 1.55T', totalWidth: 250, length: 3500, qty: 1, weight: 1.05, dimensions: '60→40', note: '' },
      { itemCode: 'SD46', itemName: '하단보강엘바', material: 'E.G.I 1.55T', totalWidth: 150, length: 3500, qty: 2, weight: 0.63, dimensions: '50→30', note: '' },
      { itemCode: 'SD47', itemName: '케이스 전면부', material: 'E.G.I 1.55T', totalWidth: 600, length: 4000, qty: 1, weight: 3.6, dimensions: '25→210→140→30→50→28', note: '500*330 케이스' },
      { itemCode: 'SD48', itemName: '케이스 린텔부', material: 'E.G.I 1.55T', totalWidth: 450, length: 4000, qty: 1, weight: 2.7, dimensions: '150→100→150', note: '' },
      { itemCode: 'SD49', itemName: '케이스 측면부', material: 'E.G.I 1.55T', totalWidth: 350, length: 500, qty: 2, weight: 0.42, dimensions: '120→100→80', note: '마구리' },
    ],
    issues: [],
    createdAt: '2025-12-12',
    createdBy: '판매팀 이판매',
    approval: { drafter: { name: '이판매', date: '2025-12-12', dept: '판매팀' }, approver: { name: '박생산', date: '2025-12-12', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // WO-FLD-03: 송도 아파트 절곡 (작업대기)
  {
    id: 203,
    workOrderNo: 'KD-WO-FLD-251215-01',
    orderNo: 'KD-TS-251215-01',
    splitNo: 'KD-TS-251215-01-01',
    lotNo: 'KD-TS-251215-01',
    shipRequestDate: '2025-12-30',
    orderDate: '2025-12-15',
    processType: '절곡',
    customerName: '대우건설(주)',
    siteName: '송도 아파트 B동',
    productName: '방화문 절곡 부품',
    workPriority: 3,
    dueDate: '2025-12-30',
    status: '작업대기',
    priority: '일반',
    assignee: null,
    assignedWorkers: ['김절곡', '이절곡', '박절곡', '최절곡'], // 절곡 공정 전체 팀 배정 (4명) - 대량 작업
    totalQty: 3,
    completedQty: 0,
    currentStep: null,
    stepStatus: {
      '절단': { status: '대기' },
      '절곡': { status: '대기' },
      '중간검사': { status: '대기' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'FLD-003', productName: '방화문 절곡 부품 SET', floor: '1층', location: 'I-01', spec: '3500×2800', qty: 3, lotNo: null },
    ],
    // 전개도 상세정보 (절곡 공정 전용)
    developedParts: [
      { itemCode: 'SD50', itemName: '문틀 상부', material: 'E.G.I 1.6T', totalWidth: 300, length: 3500, qty: 3, weight: 1.26, dimensions: '50→100→50', note: '' },
      { itemCode: 'SD51', itemName: '문틀 좌측', material: 'E.G.I 1.6T', totalWidth: 300, length: 2800, qty: 3, weight: 1.008, dimensions: '50→100→50', note: '' },
      { itemCode: 'SD52', itemName: '문틀 우측', material: 'E.G.I 1.6T', totalWidth: 300, length: 2800, qty: 3, weight: 1.008, dimensions: '50→100→50', note: '' },
      { itemCode: 'SD53', itemName: '문짝 외판', material: 'E.G.I 1.2T', totalWidth: 850, length: 2700, qty: 3, weight: 2.187, dimensions: 'FLAT', note: '' },
      { itemCode: 'SD54', itemName: '문짝 내판', material: 'E.G.I 1.2T', totalWidth: 850, length: 2700, qty: 3, weight: 2.187, dimensions: 'FLAT', note: '' },
      { itemCode: 'SD55', itemName: '문짝 보강재', material: 'E.G.I 1.6T', totalWidth: 200, length: 2700, qty: 6, weight: 2.592, dimensions: '40→60→40', note: '' },
      { itemCode: 'SD56', itemName: '경첩 보강판', material: 'E.G.I 2.0T', totalWidth: 150, length: 300, qty: 9, weight: 0.648, dimensions: 'FLAT', note: '3개/문짝' },
      { itemCode: 'SD57', itemName: '잠금장치 보강판', material: 'E.G.I 2.0T', totalWidth: 200, length: 400, qty: 3, weight: 0.384, dimensions: 'FLAT', note: '' },
    ],
    issues: [],
    createdAt: '2025-12-15',
    createdBy: '판매팀 김판매',
    approval: { drafter: { name: '김판매', date: '2025-12-15', dept: '판매팀' }, approver: null, cc: ['회계팀'] },
    approvalStatus: '승인대기',
  },

  // WO-FLD-04: 해운대 타워 절곡 (재작업중)
  {
    id: 204,
    workOrderNo: 'KD-WO-FLD-251208-01',
    orderNo: 'KD-TS-251208-01',
    splitNo: 'KD-TS-251208-01-01',
    lotNo: 'KD-TS-251208-01',
    shipRequestDate: '2025-12-22',
    orderDate: '2025-12-08',
    processType: '절곡',
    customerName: '(주)서울인테리어',
    siteName: '해운대 타워',
    productName: '스틸셔터 절곡 부품',
    workPriority: 1,
    dueDate: '2025-12-22',
    status: '재작업중',
    priority: '긴급',
    assignee: '최절곡',
    totalQty: 2,
    completedQty: 1,
    currentStep: '절곡',
    stepStatus: {
      '절단': { status: '완료', worker: '최절곡', completedAt: '2025-12-09 10:00' },
      '절곡': {
        status: '재작업',
        worker: '최절곡',
        completedAt: '2025-12-10 14:00',
        reworkStartedAt: '2025-12-11 09:00',
        reworkReason: '절곡 각도 불량 1EA 재작업'
      },
      '중간검사': {
        status: '불합격',
        inspector: '품질팀 이검사',
        result: '불합격',
        completedAt: '2025-12-10 16:00',
        failReason: '절곡 각도 불량 - 90° 기준 ±2° 초과 (1EA)',
        inspectionLot: 'KD-FLD-251210-01-(1)',
        reworkRequired: true,
        reworkQty: 1
      },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'FLD-004', productName: '스틸셔터 절곡 부품 SET', floor: '1층', location: 'J-01', spec: '3200×3000', qty: 2, lotNo: null },
    ],
    // 전개도 상세정보 (절곡 공정 전용)
    developedParts: [
      { itemCode: 'SD60', itemName: '스틸 가이드레일', material: 'SPCC 1.6T', totalWidth: 500, length: 3200, qty: 4, weight: 2.048, dimensions: '40→80→42.5→25', note: '' },
      { itemCode: 'SD61', itemName: '스틸 바텀바', material: 'SPCC 1.6T', totalWidth: 300, length: 3000, qty: 2, weight: 1.152, dimensions: '30→95→30', note: '' },
      { itemCode: 'SD62', itemName: '스틸 전면판', material: 'SPCC 1.6T', totalWidth: 600, length: 3200, qty: 2, weight: 2.4576, dimensions: '25→210→140→30→50→28', note: '' },
      { itemCode: 'SD63', itemName: '스틸 후면판', material: 'SPCC 1.6T', totalWidth: 500, length: 3200, qty: 2, weight: 2.048, dimensions: '25→165→90→155', note: '' },
      { itemCode: 'SD64', itemName: '스틸 측면판', material: 'SPCC 1.6T', totalWidth: 350, length: 400, qty: 4, weight: 0.3584, dimensions: '120→100→80', note: '' },
      { itemCode: 'SD65', itemName: '스틸 상부덮개', material: 'SPCC 1.2T', totalWidth: 600, length: 3200, qty: 2, weight: 1.8432, dimensions: '25→140→330→25', note: '' },
    ],
    issues: [
      {
        id: 1,
        issueType: '불량품발생',
        description: '중간검사 불합격 - 절곡 각도 불량 1EA (90° 기준 ±2° 초과)',
        reportedBy: '품질팀 이검사',
        reportedAt: '2025-12-10 16:30',
        status: '처리중',
        resolvedBy: null,
        resolvedAt: null,
        resolution: null,
        actionTaken: '재작업 지시 - 절곡 재가공 진행'
      },
    ],
    qualityIssue: {
      hasIssue: true,
      inspectionLot: 'KD-FLD-251210-01-(1)',
      failedQty: 1,
      passedQty: 1,
      failReason: '절곡 각도 불량',
      reworkStatus: '재작업중',
      reworkStartDate: '2025-12-11',
      expectedCompletionDate: '2025-12-13'
    },
    createdAt: '2025-12-08',
    createdBy: '전진팀 최전진',
    approval: { drafter: { name: '최전진', date: '2025-12-08', dept: '전진팀' }, approver: { name: '박생산', date: '2025-12-08', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // WO-FLD-05: E2E 테스트 절곡 (작업완료)
  {
    id: 205,
    workOrderNo: 'KD-WO-FLD-251216-01',
    orderNo: 'KD-TS-251216-06',
    splitNo: 'KD-TS-251216-06-01',
    lotNo: 'KD-TS-251216-06',
    shipRequestDate: '2025-12-28',
    orderDate: '2025-12-16',
    processType: '절곡',
    customerName: '삼성물산(주)',
    siteName: '[E2E테스트] 절곡 전용 현장',
    productName: '방화셔터 절곡 부품 (E2E)',
    workPriority: 1,
    dueDate: '2025-12-28',
    status: '작업완료',
    priority: '긴급',
    assignee: '최절곡',
    totalQty: 1,
    completedQty: 1,
    currentStep: '포장',
    stepStatus: {
      '절단': { status: '완료', worker: '최절곡', completedAt: '2025-12-17 10:00' },
      '절곡': { status: '완료', worker: '최절곡', completedAt: '2025-12-18 14:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-18 16:00', inspectionLot: 'KD-FLD-E2E-01-(1)' },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-12-19 10:00', labelInfo: 'E2E-G-01' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-19 11:00',
    items: [
      { id: 1, productCode: 'FLD-E2E-001', productName: '방화셔터 절곡 부품 SET (E2E)', floor: '테스트층', location: 'E2E-G-01', spec: '3000×4000', qty: 1, lotNo: 'KD-TS-FLD-E2E-01' },
    ],
    // 전개도 상세정보 (절곡 공정 전용) - E2E 테스트용
    developedParts: [
      { itemCode: 'E2E-01', itemName: '테스트 엘바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 4, weight: 0.9, dimensions: '75', note: 'E2E 테스트' },
      { itemCode: 'E2E-02', itemName: '테스트 하장바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 1.158, dimensions: '67→126→165→178→193', note: 'E2E 테스트' },
      { itemCode: 'E2E-03', itemName: '테스트 가이드레일', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 2.304, dimensions: '40→80→42.5→25', note: 'E2E 테스트' },
      { itemCode: 'E2E-04', itemName: '테스트 바텀바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.44, dimensions: '30→95→30', note: 'E2E 테스트' },
      { itemCode: 'E2E-05', itemName: '테스트 전면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.92, dimensions: '25→210→140→30→50→28', note: 'E2E 테스트' },
      { itemCode: 'E2E-06', itemName: '테스트 후면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.728, dimensions: '25→165→90→155', note: 'E2E 테스트' },
    ],
    issues: [],
    createdAt: '2025-12-16',
    createdBy: '[E2E] 시스템',
    approval: { drafter: { name: '시스템', date: '2025-12-16', dept: 'E2E' }, approver: { name: '생산팀', date: '2025-12-16', dept: '생산' }, cc: [] },
    approvalStatus: '승인완료',
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // 전체 워크플로우 통합 테스트 작업지시 데이터 12건 (ID: 301-312)
  // 수주(SO-251217-XX) → 작업지시(WO-251217-XX) → 품질검사 → 출하 연동
  // ═══════════════════════════════════════════════════════════════════════════

  // [통합테스트 1] WO-251217-01: 삼성물산 - 래미안 강남 프레스티지 (스크린 3대) - 작업완료
  {
    id: 301,
    workOrderNo: 'KD-WO-251217-01',
    orderNo: 'KD-TS-251217-01',
    splitNo: 'KD-TS-251217-01-01',
    lotNo: 'KD-TS-251217-01',
    shipRequestDate: '2026-01-13',
    orderDate: '2025-12-17',
    processType: '스크린',
    customerName: '삼성물산(주)',
    siteName: '래미안 강남 프레스티지',
    productName: '스크린 셔터 (표준형)',
    workPriority: 1,
    dueDate: '2026-01-15',
    status: '작업완료',
    priority: '긴급',
    assignee: '김스크린',
    assignedWorkers: ['김스크린', '이스크린'],
    totalQty: 3,
    completedQty: 3,
    currentStep: '포장',
    stepStatus: {
      '원단절단': { status: '완료', worker: '김스크린', completedAt: '2025-12-18 10:00' },
      '미싱': { status: '완료', worker: '이스크린', completedAt: '2025-12-19 14:00' },
      '앤드락작업': { status: '완료', worker: '김스크린', completedAt: '2025-12-20 11:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-20 15:00', approvedBy: '품질팀장 최품질', inspectionLot: 'IQC-251220-01' },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-12-21 09:00', labelInfo: '1층 A-01, 2층 A-02, 3층 A-03' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-21 10:00',
    items: [
      { id: 1, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'A-01', spec: '3000×2500', qty: 1, lotNo: 'LOT-20251218-001', materialLotNo: 'MAT-251217-01', productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, prodWidth: 3140, prodHeight: 2850, guideRailType: '벽면형', guideRailSpec: '120-70', shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감' } },
      { id: 2, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '2층', location: 'A-02', spec: '3000×2500', qty: 1, lotNo: 'LOT-20251218-002', materialLotNo: 'MAT-251217-01', productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, prodWidth: 3140, prodHeight: 2850, guideRailType: '벽면형', guideRailSpec: '120-70', shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감' } },
      { id: 3, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '3층', location: 'A-03', spec: '3000×2500', qty: 1, lotNo: 'LOT-20251218-003', materialLotNo: 'MAT-251217-01', productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, prodWidth: 3140, prodHeight: 2850, guideRailType: '벽면형', guideRailSpec: '120-70', shaft: 5, caseSpec: '500-330', motorBracket: '380-180', capacity: 300, finish: 'SUS마감' } },
    ],
    bomCalculated: {
      guideRail: { itemCode: 'GR12070', spec: '120-70', length: 2850, qty: 6, unitPrice: 45000 },
      case: { itemCode: 'RC500330', spec: '500-330', length: 3140, qty: 3, unitPrice: 120000 },
      smokeBarrier: { itemCode: 'G-I-4C17-53', spec: 'W50×3000', length: 3140, qty: 3, unitPrice: 35000 },
      shaft: { itemCode: 'SHAFT-5', spec: '5각', length: 3140, qty: 3, unitPrice: 28000 },
      motor: { itemCode: 'E-220V-300KG', spec: '220V-300KG', qty: 3, unitPrice: 450000 },
      motorBracket: { itemCode: 'HB380180', spec: '380-180', qty: 3, unitPrice: 25000 },
    },
    issues: [],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 김영업',
    approval: { drafter: { name: '김영업', date: '2025-12-17', dept: '판매1팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // [통합테스트 2-1] WO-251217-02: 현대건설 - 힐스테이트 판교 (스크린 2대) - 작업완료
  {
    id: 302,
    workOrderNo: 'KD-WO-251217-02',
    orderNo: 'KD-TS-251217-02',
    splitNo: 'KD-TS-251217-02-01',
    lotNo: 'KD-TS-251217-02',
    shipRequestDate: '2026-01-18',
    orderDate: '2025-12-17',
    processType: '스크린',
    customerName: '현대건설(주)',
    siteName: '힐스테이트 판교 더 퍼스트',
    productName: '스크린 셔터 (표준형)',
    workPriority: 2,
    dueDate: '2026-01-15',
    status: '작업완료',
    priority: '일반',
    assignee: '박스크린',
    assignedWorkers: ['박스크린', '최스크린'],
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '원단절단': { status: '완료', worker: '박스크린', completedAt: '2025-12-18 14:00' },
      '미싱': { status: '완료', worker: '최스크린', completedAt: '2025-12-19 16:00' },
      '앤드락작업': { status: '완료', worker: '박스크린', completedAt: '2025-12-20 14:00' },
      '중간검사': { status: '완료', inspector: '품질팀 박검사', result: '합격', completedAt: '2025-12-20 17:00', approvedBy: '품질팀장 최품질', inspectionLot: 'IQC-251220-02' },
      '포장': { status: '완료', worker: '김포장', completedAt: '2025-12-21 11:00', labelInfo: 'B1 B-01, B1 B-02' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-21 12:00',
    items: [
      { id: 1, productCode: 'SH4030', productName: '스크린 셔터 (표준형)', floor: 'B1', location: 'B-01', spec: '4000×3000', qty: 1, lotNo: 'LOT-20251218-004', materialLotNo: 'MAT-251217-02', productionSpec: { type: '와이어', openWidth: 4000, openHeight: 3000, prodWidth: 4140, prodHeight: 3350, guideRailType: '벽면형', capacity: 300 } },
      { id: 2, productCode: 'SH4030', productName: '스크린 셔터 (표준형)', floor: 'B1', location: 'B-02', spec: '4000×3000', qty: 1, lotNo: 'LOT-20251218-005', materialLotNo: 'MAT-251217-02', productionSpec: { type: '와이어', openWidth: 4000, openHeight: 3000, prodWidth: 4140, prodHeight: 3350, guideRailType: '벽면형', capacity: 300 } },
    ],
    bomCalculated: {
      guideRail: { itemCode: 'GR12070', spec: '120-70', length: 3350, qty: 4, unitPrice: 45000 },
      case: { itemCode: 'RC500330', spec: '500-330', length: 4140, qty: 2, unitPrice: 120000 },
      smokeBarrier: { itemCode: 'G-I-4C17-53', spec: 'W50×4000', length: 4140, qty: 2, unitPrice: 45000 },
      shaft: { itemCode: 'SHAFT-5', spec: '5각', length: 4140, qty: 2, unitPrice: 35000 },
      motor: { itemCode: 'E-220V-300KG', spec: '220V-300KG', qty: 2, unitPrice: 450000 },
    },
    issues: [],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 이영업',
    approval: { drafter: { name: '이영업', date: '2025-12-17', dept: '판매1팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // [통합테스트 2-2] WO-251217-03: 현대건설 - 힐스테이트 판교 (슬랫 2대) - 작업중
  {
    id: 303,
    workOrderNo: 'KD-WO-251217-03',
    orderNo: 'KD-TS-251217-02',
    splitNo: 'KD-TS-251217-02-02',
    lotNo: 'KD-TS-251217-02',
    shipRequestDate: '2026-01-18',
    orderDate: '2025-12-17',
    processType: '슬랫',
    customerName: '현대건설(주)',
    siteName: '힐스테이트 판교 더 퍼스트',
    productName: '철재 슬랫 셔터',
    workPriority: 3,
    dueDate: '2026-01-20',
    status: '작업중',
    priority: '일반',
    assignee: '김슬랫',
    assignedWorkers: ['김슬랫', '이슬랫'],
    totalQty: 2,
    completedQty: 1,
    currentStep: '미미작업',
    stepStatus: {
      '코일절단': { status: '완료', worker: '김슬랫', completedAt: '2025-12-19 10:00' },
      '중간검사': { status: '완료', inspector: '품질팀 박검사', result: '합격', completedAt: '2025-12-19 14:00', inspectionLot: 'PQC-251219-01' },
      '미미작업': { status: '진행중', worker: '이슬랫', startedAt: '2025-12-20 09:00' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'ST3525', productName: '철재 슬랫 셔터', floor: '1층', location: 'B-03', spec: '3500×2500', qty: 1, lotNo: 'LOT-20251219-001', materialLotNo: 'MAT-251218-01', productionSpec: { type: '슬랫', openWidth: 3500, openHeight: 2500 } },
      { id: 2, productCode: 'ST3525', productName: '철재 슬랫 셔터', floor: '1층', location: 'B-04', spec: '3500×2500', qty: 1, lotNo: null, materialLotNo: 'MAT-251218-01', productionSpec: { type: '슬랫', openWidth: 3500, openHeight: 2500 } },
    ],
    issues: [],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 이영업',
    approval: { drafter: { name: '이영업', date: '2025-12-17', dept: '판매1팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // [통합테스트 3] WO-251217-04: 대우건설 - 푸르지오 일산 (대형 스크린 2대, 500KG모터) - 작업완료
  {
    id: 304,
    workOrderNo: 'KD-WO-251217-04',
    orderNo: 'KD-TS-251217-03',
    splitNo: 'KD-TS-251217-03-01',
    lotNo: 'KD-TS-251217-03',
    shipRequestDate: '2026-01-23',
    orderDate: '2025-12-17',
    processType: '스크린',
    customerName: '대우건설(주)',
    siteName: '푸르지오 일산 센트럴파크',
    productName: '스크린 셔터 (대형)',
    workPriority: 4,
    dueDate: '2026-01-25',
    status: '작업완료',
    priority: '긴급',
    assignee: '김스크린',
    assignedWorkers: ['김스크린', '이스크린', '박스크린'],
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '원단절단': { status: '완료', worker: '김스크린', completedAt: '2025-12-19 10:00' },
      '미싱': { status: '완료', worker: '이스크린', completedAt: '2025-12-20 16:00' },
      '앤드락작업': { status: '완료', worker: '박스크린', completedAt: '2025-12-21 14:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-21 17:00', approvedBy: '품질팀장 최품질', inspectionLot: 'IQC-251221-01' },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-12-22 10:00', labelInfo: '로비 C-01, 연회장 C-02' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-22 11:00',
    items: [
      { id: 1, productCode: 'SH6040', productName: '스크린 셔터 (대형)', floor: '로비', location: 'C-01', spec: '6000×4000', qty: 1, lotNo: 'LOT-20251219-002', materialLotNo: 'MAT-251218-02', productionSpec: { type: '와이어', openWidth: 6000, openHeight: 4000, prodWidth: 6140, prodHeight: 4350, guideRailType: '벽면형', capacity: 500 } },
      { id: 2, productCode: 'SH6040', productName: '스크린 셔터 (대형)', floor: '연회장', location: 'C-02', spec: '6000×4000', qty: 1, lotNo: 'LOT-20251219-003', materialLotNo: 'MAT-251218-02', productionSpec: { type: '와이어', openWidth: 6000, openHeight: 4000, prodWidth: 6140, prodHeight: 4350, guideRailType: '벽면형', capacity: 500 } },
    ],
    bomCalculated: {
      guideRail: { itemCode: 'GR15080', spec: '150-80', length: 4350, qty: 4, unitPrice: 65000 },
      case: { itemCode: 'RC600400', spec: '600-400', length: 6140, qty: 2, unitPrice: 180000 },
      smokeBarrier: { itemCode: 'G-I-4C17-53', spec: 'W50×6000', length: 6140, qty: 2, unitPrice: 65000 },
      shaft: { itemCode: 'SHAFT-6', spec: '6각', length: 6140, qty: 2, unitPrice: 55000 },
      motor: { itemCode: 'E-380V-500KG', spec: '380V-500KG', qty: 2, unitPrice: 850000 },
      motorBracket: { itemCode: 'HB500250', spec: '500-250', qty: 2, unitPrice: 45000 },
    },
    issues: [],
    createdAt: '2025-12-17',
    createdBy: '판매2팀 박영업',
    approval: { drafter: { name: '박영업', date: '2025-12-17', dept: '판매2팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // [통합테스트 4] WO-251217-05: GS건설 - 자이 위례 (슬랫 전용 4대) - 작업완료
  {
    id: 305,
    workOrderNo: 'KD-WO-251217-05',
    orderNo: 'KD-TS-251217-04',
    splitNo: 'KD-TS-251217-04-01',
    lotNo: 'KD-TS-251217-04',
    shipRequestDate: '2026-01-28',
    orderDate: '2025-12-17',
    processType: '슬랫',
    customerName: 'GS건설(주)',
    siteName: '자이 위례 더 퍼스트',
    productName: '철재 슬랫 셔터',
    workPriority: 5,
    dueDate: '2026-01-30',
    status: '작업완료',
    priority: '일반',
    assignee: '박슬랫',
    assignedWorkers: ['박슬랫', '김슬랫', '이슬랫'],
    totalQty: 4,
    completedQty: 4,
    currentStep: '포장',
    stepStatus: {
      '코일절단': { status: '완료', worker: '박슬랫', completedAt: '2025-12-19 16:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-20 10:00', inspectionLot: 'PQC-251220-01' },
      '미미작업': { status: '완료', worker: '김슬랫', completedAt: '2025-12-21 14:00' },
      '포장': { status: '완료', worker: '이슬랫', completedAt: '2025-12-22 10:00', labelInfo: 'B2 D-01~D-04' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-22 11:00',
    items: [
      { id: 1, productCode: 'ST3020', productName: '철재 슬랫 셔터', floor: 'B2', location: 'D-01', spec: '3000×2000', qty: 1, lotNo: 'LOT-20251219-004', materialLotNo: 'MAT-251218-03', productionSpec: { type: '슬랫', openWidth: 3000, openHeight: 2000 } },
      { id: 2, productCode: 'ST3020', productName: '철재 슬랫 셔터', floor: 'B2', location: 'D-02', spec: '3000×2000', qty: 1, lotNo: 'LOT-20251219-005', materialLotNo: 'MAT-251218-03', productionSpec: { type: '슬랫', openWidth: 3000, openHeight: 2000 } },
      { id: 3, productCode: 'ST3020', productName: '철재 슬랫 셔터', floor: 'B2', location: 'D-03', spec: '3000×2000', qty: 1, lotNo: 'LOT-20251219-006', materialLotNo: 'MAT-251218-03', productionSpec: { type: '슬랫', openWidth: 3000, openHeight: 2000 } },
      { id: 4, productCode: 'ST3020', productName: '철재 슬랫 셔터', floor: 'B2', location: 'D-04', spec: '3000×2000', qty: 1, lotNo: 'LOT-20251219-007', materialLotNo: 'MAT-251218-03', productionSpec: { type: '슬랫', openWidth: 3000, openHeight: 2000 } },
    ],
    issues: [],
    createdAt: '2025-12-17',
    createdBy: '판매2팀 최영업',
    approval: { drafter: { name: '최영업', date: '2025-12-17', dept: '판매2팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // [통합테스트 5] WO-251217-06: 포스코건설 - 더샵 송도 (코너형 가이드레일 2대) - 작업완료
  {
    id: 306,
    workOrderNo: 'KD-WO-251217-06',
    orderNo: 'KD-TS-251217-05',
    splitNo: 'KD-TS-251217-05-01',
    lotNo: 'KD-TS-251217-05',
    shipRequestDate: '2026-01-28',
    orderDate: '2025-12-17',
    processType: '스크린',
    customerName: '포스코건설(주)',
    siteName: '더샵 송도 마린베이',
    productName: '스크린 셔터 (코너형)',
    workPriority: 6,
    dueDate: '2026-01-30',
    status: '작업완료',
    priority: '일반',
    assignee: '최스크린',
    assignedWorkers: ['최스크린', '김스크린'],
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '원단절단': { status: '완료', worker: '최스크린', completedAt: '2025-12-20 10:00' },
      '미싱': { status: '완료', worker: '김스크린', completedAt: '2025-12-21 14:00' },
      '앤드락작업': { status: '완료', worker: '최스크린', completedAt: '2025-12-22 11:00' },
      '중간검사': { status: '완료', inspector: '품질팀 박검사', result: '합격', completedAt: '2025-12-22 15:00', approvedBy: '품질팀장 최품질', inspectionLot: 'IQC-251222-01' },
      '포장': { status: '완료', worker: '김포장', completedAt: '2025-12-23 09:00', labelInfo: '1층 E-01, E-02 (코너형)' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-23 10:00',
    items: [
      { id: 1, productCode: 'SH3525C', productName: '스크린 셔터 (코너형)', floor: '1층', location: 'E-01', spec: '3500×2500', qty: 1, lotNo: 'LOT-20251220-001', materialLotNo: 'MAT-251219-01', productionSpec: { type: '와이어', openWidth: 3500, openHeight: 2500, prodWidth: 3640, prodHeight: 2850, guideRailType: '코너형', guideRailSpec: '130-80', capacity: 300 } },
      { id: 2, productCode: 'SH3525C', productName: '스크린 셔터 (코너형)', floor: '1층', location: 'E-02', spec: '3500×2500', qty: 1, lotNo: 'LOT-20251220-002', materialLotNo: 'MAT-251219-01', productionSpec: { type: '와이어', openWidth: 3500, openHeight: 2500, prodWidth: 3640, prodHeight: 2850, guideRailType: '코너형', guideRailSpec: '130-80', capacity: 300 } },
    ],
    bomCalculated: {
      guideRail: { itemCode: 'GR13080-C', spec: '130-80 코너형', length: 2850, qty: 4, unitPrice: 75000 },
      case: { itemCode: 'RC500330', spec: '500-330', length: 3640, qty: 2, unitPrice: 130000 },
      smokeBarrier: { itemCode: 'G-I-4C17-53', spec: 'W50×3500', length: 3640, qty: 2, unitPrice: 40000 },
      cornerBracket: { itemCode: 'CB-90', spec: '90도 코너 브라켓', qty: 4, unitPrice: 35000 },
      motor: { itemCode: 'E-220V-300KG', spec: '220V-300KG', qty: 2, unitPrice: 450000 },
    },
    issues: [],
    createdAt: '2025-12-17',
    createdBy: '판매3팀 정영업',
    approval: { drafter: { name: '정영업', date: '2025-12-17', dept: '판매3팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // [통합테스트 7-1] WO-251217-07: 호반건설 - 써밋 광교 1차분할 (스크린 2대) - 작업완료
  {
    id: 307,
    workOrderNo: 'KD-WO-251217-07',
    orderNo: 'KD-TS-251217-07',
    splitNo: 'KD-TS-251217-07-01',
    lotNo: 'KD-TS-251217-07',
    shipRequestDate: '2026-01-08',
    orderDate: '2025-12-17',
    processType: '스크린',
    customerName: '호반건설(주)',
    siteName: '써밋 광교 리버파크',
    productName: '스크린 셔터 (표준형)',
    workPriority: 7,
    dueDate: '2026-01-10',
    status: '작업완료',
    priority: '긴급',
    assignee: '이스크린',
    assignedWorkers: ['이스크린'],
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '원단절단': { status: '완료', worker: '이스크린', completedAt: '2025-12-18 10:00' },
      '미싱': { status: '완료', worker: '이스크린', completedAt: '2025-12-19 10:00' },
      '앤드락작업': { status: '완료', worker: '이스크린', completedAt: '2025-12-19 16:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-20 10:00', inspectionLot: 'IQC-251220-03' },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-12-20 14:00', labelInfo: '1층 F-01, F-02' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-20 15:00',
    items: [
      { id: 1, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'F-01', spec: '3000×2500', qty: 1, lotNo: 'LOT-20251218-006', materialLotNo: 'MAT-251217-03', productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, prodWidth: 3140, prodHeight: 2850, guideRailType: '벽면형', capacity: 300 } },
      { id: 2, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'F-02', spec: '3000×2500', qty: 1, lotNo: 'LOT-20251218-007', materialLotNo: 'MAT-251217-03', productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, prodWidth: 3140, prodHeight: 2850, guideRailType: '벽면형', capacity: 300 } },
    ],
    issues: [],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 윤영업',
    approval: { drafter: { name: '윤영업', date: '2025-12-17', dept: '판매1팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // [통합테스트 7-2] WO-251217-08: 호반건설 - 써밋 광교 2차분할 (스크린 2대) - 작업완료
  {
    id: 308,
    workOrderNo: 'KD-WO-251217-08',
    orderNo: 'KD-TS-251217-07',
    splitNo: 'KD-TS-251217-07-02',
    lotNo: 'KD-TS-251217-07',
    shipRequestDate: '2026-01-18',
    orderDate: '2025-12-17',
    processType: '스크린',
    customerName: '호반건설(주)',
    siteName: '써밋 광교 리버파크',
    productName: '스크린 셔터 (표준형)',
    workPriority: 8,
    dueDate: '2026-01-20',
    status: '작업완료',
    priority: '일반',
    assignee: '박스크린',
    assignedWorkers: ['박스크린'],
    totalQty: 2,
    completedQty: 2,
    currentStep: '포장',
    stepStatus: {
      '원단절단': { status: '완료', worker: '박스크린', completedAt: '2025-12-21 10:00' },
      '미싱': { status: '완료', worker: '박스크린', completedAt: '2025-12-22 10:00' },
      '앤드락작업': { status: '완료', worker: '박스크린', completedAt: '2025-12-22 16:00' },
      '중간검사': { status: '완료', inspector: '품질팀 박검사', result: '합격', completedAt: '2025-12-23 10:00', inspectionLot: 'IQC-251223-01' },
      '포장': { status: '완료', worker: '김포장', completedAt: '2025-12-23 14:00', labelInfo: '2층 F-03, F-04' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-23 15:00',
    items: [
      { id: 1, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '2층', location: 'F-03', spec: '3000×2500', qty: 1, lotNo: 'LOT-20251221-001', materialLotNo: 'MAT-251220-01', productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, prodWidth: 3140, prodHeight: 2850, guideRailType: '벽면형', capacity: 300 } },
      { id: 2, productCode: 'SH3025', productName: '스크린 셔터 (표준형)', floor: '2층', location: 'F-04', spec: '3000×2500', qty: 1, lotNo: 'LOT-20251221-002', materialLotNo: 'MAT-251220-01', productionSpec: { type: '와이어', openWidth: 3000, openHeight: 2500, prodWidth: 3140, prodHeight: 2850, guideRailType: '벽면형', capacity: 300 } },
    ],
    issues: [],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 윤영업',
    approval: { drafter: { name: '윤영업', date: '2025-12-17', dept: '판매1팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // [통합테스트 7-3] WO-251217-09: 호반건설 - 써밋 광교 3차분할 (슬랫 1대) - 작업중
  {
    id: 309,
    workOrderNo: 'KD-WO-251217-09',
    orderNo: 'KD-TS-251217-07',
    splitNo: 'KD-TS-251217-07-03',
    lotNo: 'KD-TS-251217-07',
    shipRequestDate: '2026-01-28',
    orderDate: '2025-12-17',
    processType: '슬랫',
    customerName: '호반건설(주)',
    siteName: '써밋 광교 리버파크',
    productName: '철재 슬랫 셔터',
    workPriority: 9,
    dueDate: '2026-01-30',
    status: '작업중',
    priority: '일반',
    assignee: '이슬랫',
    assignedWorkers: ['이슬랫'],
    totalQty: 1,
    completedQty: 0,
    currentStep: '코일절단',
    stepStatus: {
      '코일절단': { status: '진행중', worker: '이슬랫', startedAt: '2025-12-23 10:00' },
      '중간검사': { status: '대기' },
      '미미작업': { status: '대기' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'ST3525', productName: '철재 슬랫 셔터', floor: '3층', location: 'F-05', spec: '3500×2500', qty: 1, lotNo: null, materialLotNo: 'MAT-251222-01', productionSpec: { type: '슬랫', openWidth: 3500, openHeight: 2500 } },
    ],
    issues: [],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 윤영업',
    approval: { drafter: { name: '윤영업', date: '2025-12-17', dept: '판매1팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // [통합테스트 8] WO-251217-10: 한화건설 - 포레나 수지 추가분 (스크린 2대) - 작업대기
  {
    id: 310,
    workOrderNo: 'KD-WO-251217-10',
    orderNo: 'KD-TS-251217-08',
    splitNo: 'KD-TS-251217-08-01',
    lotNo: 'KD-TS-251217-08',
    shipRequestDate: '2026-02-13',
    orderDate: '2025-12-17',
    processType: '스크린',
    customerName: '한화건설(주)',
    siteName: '포레나 수지 더 퍼스트',
    productName: '스크린 셔터 (표준형) - 추가',
    workPriority: 7,
    dueDate: '2026-02-15',
    status: '작업대기',
    priority: '일반',
    assignee: null,
    assignedWorkers: [],
    totalQty: 2,
    completedQty: 0,
    currentStep: null,
    stepStatus: {
      '원단절단': { status: '대기' },
      '미싱': { status: '대기' },
      '앤드락작업': { status: '대기' },
      '중간검사': { status: '대기' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'SH3525', productName: '스크린 셔터 (표준형) 추가', floor: '4층', location: 'G-01', spec: '3500×2500', qty: 1, lotNo: null, materialLotNo: null, productionSpec: { type: '와이어', openWidth: 3500, openHeight: 2500, prodWidth: 3640, prodHeight: 2850, guideRailType: '벽면형', capacity: 300 } },
      { id: 2, productCode: 'SH3525', productName: '스크린 셔터 (표준형) 추가', floor: '5층', location: 'G-02', spec: '3500×2500', qty: 1, lotNo: null, materialLotNo: null, productionSpec: { type: '와이어', openWidth: 3500, openHeight: 2500, prodWidth: 3640, prodHeight: 2850, guideRailType: '벽면형', capacity: 300 } },
    ],
    issues: [],
    createdAt: '2025-12-17',
    createdBy: '판매2팀 강영업',
    approval: { drafter: { name: '강영업', date: '2025-12-17', dept: '판매2팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },

  // [통합테스트 9] WO-251217-11: 태영건설 - 데시앙 동탄 (품질불량 → 재작업) - 재작업중
  {
    id: 311,
    workOrderNo: 'KD-WO-251217-11',
    orderNo: 'KD-TS-251217-09',
    splitNo: 'KD-TS-251217-09-01',
    lotNo: 'KD-TS-251217-09',
    shipRequestDate: '2026-02-08',
    orderDate: '2025-12-17',
    processType: '스크린',
    customerName: '태영건설(주)',
    siteName: '데시앙 동탄 레이크파크',
    productName: '스크린 셔터 (표준형)',
    workPriority: 8,
    dueDate: '2026-02-10',
    status: '재작업중',
    priority: '긴급',
    assignee: '김스크린',
    assignedWorkers: ['김스크린', '이스크린'],
    totalQty: 2,
    completedQty: 0,
    currentStep: '앤드락작업',
    stepStatus: {
      '원단절단': { status: '완료', worker: '김스크린', completedAt: '2025-12-19 10:00' },
      '미싱': { status: '완료', worker: '이스크린', completedAt: '2025-12-20 14:00' },
      '앤드락작업': { status: '재작업', worker: '김스크린', startedAt: '2025-12-22 09:00', reworkReason: '앤드락 접착불량으로 재작업' },
      '중간검사': { status: '불합격', inspector: '품질팀 이검사', result: '불합격', completedAt: '2025-12-21 15:00', defectType: '앤드락 접착불량', inspectionLot: 'IQC-251221-02', ncrNo: 'NCR-251221-01' },
      '포장': { status: '대기' },
    },
    movedToShippingArea: false,
    movedToShippingAreaAt: null,
    items: [
      { id: 1, productCode: 'SH4030', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'H-01', spec: '4000×3000', qty: 1, lotNo: 'LOT-20251219-008', materialLotNo: 'MAT-251218-04', productionSpec: { type: '와이어', openWidth: 4000, openHeight: 3000, prodWidth: 4140, prodHeight: 3350, guideRailType: '벽면형', capacity: 300 }, reworkStatus: '재작업중' },
      { id: 2, productCode: 'SH4030', productName: '스크린 셔터 (표준형)', floor: '2층', location: 'H-02', spec: '4000×3000', qty: 1, lotNo: 'LOT-20251219-009', materialLotNo: 'MAT-251218-04', productionSpec: { type: '와이어', openWidth: 4000, openHeight: 3000, prodWidth: 4140, prodHeight: 3350, guideRailType: '벽면형', capacity: 300 }, reworkStatus: '재작업중' },
    ],
    issues: [
      { id: 1, issueType: '불량품발생', description: '앤드락 접착불량 - 전체 재작업 필요', reportedAt: '2025-12-21 15:30', reportedBy: '품질팀 이검사', status: '처리중', ncrNo: 'NCR-251221-01' },
    ],
    ncrInfo: {
      ncrNo: 'NCR-251221-01',
      defectType: '앤드락 접착불량',
      defectQty: 2,
      rootCause: '접착제 경화시간 미준수',
      correctiveAction: '접착제 경화시간 표준 재교육, 작업표준서 개정',
      preventiveAction: '공정 체크리스트에 경화시간 확인 항목 추가',
      reworkStartDate: '2025-12-22',
      expectedCompletionDate: '2025-12-25',
    },
    createdAt: '2025-12-17',
    createdBy: '판매3팀 임영업',
    approval: { drafter: { name: '임영업', date: '2025-12-17', dept: '판매3팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀', '품질팀'] },
    approvalStatus: '승인완료',
  },

  // [통합테스트 10] WO-251217-12: 두산건설 - 위브 청라 (전체 완료) - 출하완료
  {
    id: 312,
    workOrderNo: 'KD-WO-251217-12',
    orderNo: 'KD-TS-251217-10',
    splitNo: 'KD-TS-251217-10-01',
    lotNo: 'KD-TS-251217-10',
    shipRequestDate: '2025-12-28',
    orderDate: '2025-12-17',
    processType: '스크린',
    customerName: '두산건설(주)',
    siteName: '위브 청라 센트럴파크',
    productName: '스크린 셔터 (표준형)',
    workPriority: 9,
    dueDate: '2025-12-30',
    status: '출하완료',
    priority: '긴급',
    assignee: '최스크린',
    assignedWorkers: ['최스크린', '김스크린'],
    totalQty: 2,
    completedQty: 2,
    currentStep: '출하완료',
    stepStatus: {
      '원단절단': { status: '완료', worker: '최스크린', completedAt: '2025-12-18 09:00' },
      '미싱': { status: '완료', worker: '김스크린', completedAt: '2025-12-18 16:00' },
      '앤드락작업': { status: '완료', worker: '최스크린', completedAt: '2025-12-19 11:00' },
      '중간검사': { status: '완료', inspector: '품질팀 이검사', result: '합격', completedAt: '2025-12-19 14:00', approvedBy: '품질팀장 최품질', inspectionLot: 'IQC-251219-01' },
      '포장': { status: '완료', worker: '박포장', completedAt: '2025-12-19 17:00', labelInfo: '1층 I-01, I-02' },
    },
    movedToShippingArea: true,
    movedToShippingAreaAt: '2025-12-20 09:00',
    shippedAt: '2025-12-20 14:00',
    shipmentNo: 'SL-251220-01',
    items: [
      { id: 1, productCode: 'SH3525', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'I-01', spec: '3500×2500', qty: 1, lotNo: 'LOT-20251218-008', materialLotNo: 'MAT-251217-04', productionSpec: { type: '와이어', openWidth: 3500, openHeight: 2500, prodWidth: 3640, prodHeight: 2850, guideRailType: '벽면형', capacity: 300 }, shipmentStatus: '출하완료' },
      { id: 2, productCode: 'SH3525', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'I-02', spec: '3500×2500', qty: 1, lotNo: 'LOT-20251218-009', materialLotNo: 'MAT-251217-04', productionSpec: { type: '와이어', openWidth: 3500, openHeight: 2500, prodWidth: 3640, prodHeight: 2850, guideRailType: '벽면형', capacity: 300 }, shipmentStatus: '출하완료' },
    ],
    bomCalculated: {
      guideRail: { itemCode: 'GR12070', spec: '120-70', length: 2850, qty: 4, unitPrice: 45000 },
      case: { itemCode: 'RC500330', spec: '500-330', length: 3640, qty: 2, unitPrice: 125000 },
      smokeBarrier: { itemCode: 'G-I-4C17-53', spec: 'W50×3500', length: 3640, qty: 2, unitPrice: 38000 },
      shaft: { itemCode: 'SHAFT-5', spec: '5각', length: 3640, qty: 2, unitPrice: 30000 },
      motor: { itemCode: 'E-220V-300KG', spec: '220V-300KG', qty: 2, unitPrice: 450000 },
    },
    issues: [],
    createdAt: '2025-12-17',
    createdBy: '판매1팀 조영업',
    approval: { drafter: { name: '조영업', date: '2025-12-17', dept: '판매1팀' }, approver: { name: '박생산', date: '2025-12-17', dept: '생산관리' }, cc: ['회계팀'] },
    approvalStatus: '승인완료',
  },
];

// 이슈 유형
const issueTypes = ['불량품발생', '재고없음', '일정지연', '설비고장', '기타'];

// 작업실적 (LOT별)
const initialWorkResults = [
  {
    id: 1,
    lotNo: 'KD-TS-250210-01-01', // 완제품LOT: KD-공장코드-YYMMDD-순번-분할순번
    workOrderNo: 'KD-PL-250120-01',
    workDate: '2025-02-10',
    processType: '스크린',
    productCode: 'SCR-001',
    productName: '스크린 셔터 (표준형)',
    spec: '7660×2550',
    productionQty: 1,
    goodQty: 1,
    defectQty: 0,
    defectType: null,
    inspectionCompleted: true,
    inspectionLot: 'KD-SC-250209-01-(3)', // 중간검사LOT
    packingCompleted: true,
    worker: '김생산',
    note: '',
    createdAt: '2025-02-10 09:30',
  },
  {
    id: 2,
    lotNo: 'KD-TS-250210-01-02',
    workOrderNo: 'KD-PL-250120-01',
    workDate: '2025-02-10',
    processType: '스크린',
    productCode: 'SCR-001',
    productName: '스크린 셔터 (표준형)',
    spec: '6500×2400',
    productionQty: 1,
    goodQty: 1,
    defectQty: 0,
    defectType: null,
    inspectionCompleted: true,
    inspectionLot: 'KD-SC-250209-01-(3)',
    packingCompleted: true,
    worker: '김생산',
    note: '',
    createdAt: '2025-02-10 14:20',
  },
  {
    id: 3,
    lotNo: 'KD-TS-250212-01-01',
    workOrderNo: 'KD-PL-250122-01',
    workDate: '2025-02-12',
    processType: '스크린',
    productCode: 'SCR-002',
    productName: '스크린 셔터 (프리미엄)',
    spec: '8000×2800',
    productionQty: 1,
    goodQty: 0,
    defectQty: 1,
    defectType: '치수불량',
    inspectionCompleted: true,
    inspectionLot: 'KD-SC-250212-01-(3)',
    packingCompleted: false,
    worker: '이생산',
    note: '재작업 필요',
    createdAt: '2025-02-12 11:00',
  },
];

// 출하 데이터 (출고번호 채번규칙: 날짜-P-순번, 예: 251217-P-01)
const initialShipments = [
  /*
   * ============================================================
   * 📋 출하 데이터 (수주 분할과 연동)
   * ============================================================
   * [1] KD-TS-250115-01-01 (서울 1차분) → 배송완료 ✓
   * [2] KD-TS-250115-01-02 (서울 2차분) → 출고지시 (생산중)
   *     → 서울건축 출하진행률: 50% (1/2 완료)
   * 
   * [3] KD-TS-250118-01-01 (인천 1차분) → 배송완료 ✓
   * [4] KD-TS-250118-01-02 (인천 2차분) → 배송완료 ✓
   *     → 인천건설 출하진행률: 100% (2/2 완료)
   * 
   * [5] KD-TS-250115-01-A-01 (서울 추가분) → 출하준비
   *     → 서울건축 추가분 출하진행률: 0% (0/1 완료)
   * ============================================================
   */
  {
    id: 1,
    releaseNo: '250215-P-01',         // 출고번호 (채번규칙: 날짜-P-순번)
    shipmentDate: '2025-02-15',
    lotNo: 'KD-TS-250115-01',         // 로트번호 (추적 기준)
    splitNo: 'KD-TS-250115-01-01',    // 분할번호 (수주 연동)
    customerName: '서울건축',
    siteName: '강남 오피스텔 A동',
    deliveryAddress: '서울시 강남구 테헤란로 123',
    receiverName: '김현장',
    receiverPhone: '010-9999-8888',
    status: '배송완료',  // 테스트: 배송완료로 변경 → 50% 표시
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    // 출고순위
    shipmentPriority: 1,
    isSplitShipment: true,
    splitOrder: 1,                    // 분할 순서 (1차, 2차...)
    // 배차 정보
    dispatchType: '상차',
    logisticsCompany: '한진물류',
    vehicleType: '5톤',
    vehicleNo: '12가 3456',
    driverName: '홍운전',
    driverPhone: '010-1111-2222',
    scheduledArrival: '2025-02-15 09:00',
    confirmedArrival: '2025-02-15 09:30',
    shippingCost: 150000,
    // 상차 정보
    loadingCompleted: false,
    loadingCompletedAt: null,
    loadingWorker: null,
    // 품목 - 완제품LOT: KD-공장코드-YYMMDD-순번-분할순번
    items: [
      { id: 1, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'A-01', spec: '7660×2550', qty: 1, lotNo: 'KD-TS-250210-01-01', arrivedAtLoadingArea: true, loadingChecked: false, accessoryLotNo: '' },
      { id: 2, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'A-02', spec: '6500×2400', qty: 1, lotNo: 'KD-TS-250210-01-02', arrivedAtLoadingArea: true, loadingChecked: false, accessoryLotNo: '' },
    ],
    // 변경이력
    changeHistory: [
      { id: 1, changedAt: '2025-02-14 10:30', changeType: '출하일 변경', beforeValue: '2025-02-14', afterValue: '2025-02-15', reason: '고객사 현장 일정 변경', changedBy: '판매1팀 김판매' },
    ],
    // 미출고사유
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-02-10',
    createdBy: '판매1팀 김판매',
    note: '',
  },
  {
    id: 2,
    releaseNo: '250218-P-01',         // 출고번호 (채번규칙: 날짜-P-순번)
    shipmentDate: '2025-02-18',
    lotNo: 'KD-TS-250115-01',
    splitNo: 'KD-TS-250115-01-02',
    customerName: '서울건축',
    siteName: '강남 오피스텔 A동',
    deliveryAddress: '서울시 강남구 테헤란로 123',
    receiverName: '김현장',
    receiverPhone: '010-9999-8888',
    status: '출고지시',
    paymentConfirmed: false,
    taxInvoiceIssued: false,
    shipmentPriority: 2,
    isSplitShipment: true,
    splitOrder: 2,
    dispatchType: '직접배차',
    logisticsCompany: null,
    vehicleType: null,
    vehicleNo: null,
    driverName: null,
    driverPhone: null,
    scheduledArrival: '2025-02-18 10:00',
    confirmedArrival: null,
    shippingCost: 0,
    loadingCompleted: false,
    loadingCompletedAt: null,
    loadingWorker: null,
    items: [
      { id: 1, productCode: 'SCR-002', productName: '스크린 셔터 (프리미엄)', floor: '2층', location: 'B-01', spec: '8000×2800', qty: 1, lotNo: null, arrivedAtLoadingArea: false, loadingChecked: false, accessoryLotNo: '' },
      { id: 2, productCode: 'SLT-001', productName: '슬랫 셔터', floor: '2층', location: 'B-02', spec: '5000×2200', qty: 2, lotNo: null, arrivedAtLoadingArea: false, loadingChecked: false, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-02-12',
    createdBy: '판매1팀 김판매',
    note: '2차 분할 출고 예정 - 생산 진행중',
  },
  // KD-TS-250118-01 출하 (100% 완료)
  {
    id: 3,
    releaseNo: '250220-P-01',         // 출고번호 (채번규칙: 날짜-P-순번)
    shipmentDate: '2025-02-20',
    lotNo: 'KD-TS-250118-01',
    splitNo: 'KD-TS-250118-01-01',
    customerName: '인천건설',
    siteName: '송도 오피스텔 B동',
    deliveryAddress: '인천시 연수구 송도동 45',
    receiverName: '박현장',
    receiverPhone: '010-8888-7777',
    status: '배송완료',
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    shipmentPriority: 1,
    isSplitShipment: true,
    splitOrder: 1,
    dispatchType: '직접배차',
    logisticsCompany: null,
    vehicleType: '5톤',
    vehicleNo: '34나 5678',
    driverName: '이운전',
    driverPhone: '010-3333-4444',
    scheduledArrival: '2025-02-20 10:00',
    confirmedArrival: '2025-02-20 10:15',
    shippingCost: 0,
    loadingCompleted: true,
    loadingCompletedAt: '2025-02-20 08:30',
    loadingWorker: '김상차',
    items: [
      { id: 1, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: 'B1', location: 'C-01', spec: '6000×2400', qty: 2, lotNo: 'KD-TS-250215-01-01', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-02-18',
    createdBy: '판매1팀 이판매',
    completedAt: '2025-02-20 14:00',
    note: '1차 분할 배송완료',
  },
  {
    id: 4,
    releaseNo: '250301-P-01',         // 출고번호 (채번규칙: 날짜-P-순번)
    shipmentDate: '2025-03-01',
    lotNo: 'KD-TS-250118-01',
    splitNo: 'KD-TS-250118-01-02',
    customerName: '인천건설',
    siteName: '송도 오피스텔 B동',
    deliveryAddress: '인천시 연수구 송도동 45',
    receiverName: '박현장',
    receiverPhone: '010-8888-7777',
    status: '배송완료',
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    shipmentPriority: 1,
    isSplitShipment: true,
    splitOrder: 2,
    dispatchType: '직접배차',
    logisticsCompany: null,
    vehicleType: '5톤',
    vehicleNo: '34나 5678',
    driverName: '이운전',
    driverPhone: '010-3333-4444',
    scheduledArrival: '2025-03-01 10:00',
    confirmedArrival: '2025-03-01 10:30',
    shippingCost: 0,
    loadingCompleted: true,
    loadingCompletedAt: '2025-03-01 08:00',
    loadingWorker: '김상차',
    items: [
      { id: 1, productCode: 'SLT-001', productName: '슬랫 셔터', floor: '1층', location: 'D-01', spec: '4500×2000', qty: 2, lotNo: 'KD-TS-250225-01-01', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-02-25',
    createdBy: '판매1팀 이판매',
    completedAt: '2025-03-01 15:00',
    note: '2차 분할 배송완료 - 최종 출하',
  },
  // KD-TS-250115-01-A 출하 (0% - 출하준비)
  {
    id: 5,
    releaseNo: '250320-P-01',         // 출고번호 (채번규칙: 날짜-P-순번)
    shipmentDate: '2025-03-20',
    lotNo: 'KD-TS-250115-01-A',
    splitNo: 'KD-TS-250115-01-A-01',
    customerName: '서울건축',
    siteName: '강남 오피스텔 A동',
    deliveryAddress: '서울시 강남구 테헤란로 123',
    receiverName: '김현장',
    receiverPhone: '010-9999-8888',
    status: '출하준비',  // 아직 배송완료 아님 → 0%
    paymentConfirmed: false,
    taxInvoiceIssued: false,
    shipmentPriority: 1,
    isSplitShipment: true,
    splitOrder: 1,
    dispatchType: '상차',
    logisticsCompany: null,
    vehicleType: null,
    vehicleNo: null,
    driverName: null,
    driverPhone: null,
    scheduledArrival: '2025-03-20 09:00',
    confirmedArrival: null,
    shippingCost: 0,
    loadingCompleted: false,
    loadingCompletedAt: null,
    loadingWorker: null,
    items: [
      { id: 1, productCode: 'SCR-002', productName: '스크린 셔터 (프리미엄)', floor: '3층', location: 'C-01', spec: '8000×2800', qty: 3, lotNo: null, arrivedAtLoadingArea: false, loadingChecked: false, accessoryLotNo: '' },
      { id: 2, productCode: 'MTR-001', productName: '모터 세트', floor: '-', location: '-', spec: '-', qty: 2, lotNo: null, arrivedAtLoadingArea: false, loadingChecked: false, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-03-10',
    createdBy: '판매1팀 박판매',
    note: '추가분 출하 예정',
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // E2E 테스트용 출하 데이터 (수주 101-105 연결)
  // ═══════════════════════════════════════════════════════════════════════════

  // SHP-E2E-01: 판교 물류센터 슬랫 (수주102 → 출하대기)
  {
    id: 101,
    releaseNo: '251228-P-01',         // 출고번호 (채번규칙: 날짜-P-순번)
    shipmentDate: '2025-12-28',
    lotNo: 'KD-TS-251216-02',
    splitNo: 'KD-TS-251216-02-01',
    customerName: '현대건설(주)',
    siteName: '[E2E테스트] 판교 물류센터',
    deliveryAddress: '경기도 성남시 분당구 판교로 200',
    receiverName: '이현장',
    receiverPhone: '010-2345-6789',
    status: '출고대기',
    paymentConfirmed: true,
    taxInvoiceIssued: false,
    shipmentPriority: 1,
    isSplitShipment: false,
    splitOrder: 1,
    dispatchType: '상차',
    logisticsCompany: '경동로지스',
    vehicleType: '5톤',
    vehicleNo: null,
    driverName: null,
    driverPhone: null,
    scheduledArrival: '2025-12-28 14:00',
    confirmedArrival: null,
    shippingCost: 150000,
    loadingCompleted: false,
    loadingCompletedAt: null,
    loadingWorker: null,
    items: [
      { id: 1, productCode: 'STL-E2E-001', productName: '철재 슬랫 셔터', floor: 'B1', location: 'C-01', spec: '4000×3000', qty: 1, lotNo: 'KD-TS-E2E-02-01', arrivedAtLoadingArea: true, loadingChecked: false, accessoryLotNo: '' },
      { id: 2, productCode: 'STL-E2E-001', productName: '철재 슬랫 셔터', floor: 'B2', location: 'C-02', spec: '4000×3000', qty: 1, lotNo: 'KD-TS-E2E-02-02', arrivedAtLoadingArea: true, loadingChecked: false, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-18',
    createdBy: '[E2E] 시스템',
    note: '[E2E-102] 슬랫 공정 완료 → 출고대기 상태',
  },

  // SHP-E2E-02: 송도 아파트 스크린 (수주103-01 → 배송완료)
  {
    id: 102,
    releaseNo: '251223-P-01',         // 출고번호 (채번규칙: 날짜-P-순번)
    shipmentDate: '2025-12-23',
    lotNo: 'KD-TS-251216-03',
    splitNo: 'KD-TS-251216-03-01',
    customerName: '대우건설(주)',
    siteName: '[E2E테스트] 송도 아파트 B동',
    deliveryAddress: '인천시 연수구 송도동 300',
    receiverName: '박현장',
    receiverPhone: '010-3456-7890',
    status: '배송완료',
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    shipmentPriority: 1,
    isSplitShipment: true,
    splitOrder: 1,
    dispatchType: '납품',
    logisticsCompany: '경동로지스',
    vehicleType: '5톤',
    vehicleNo: '서울 12가 3456',
    driverName: '김운송',
    driverPhone: '010-7777-8888',
    scheduledArrival: '2025-12-23 10:00',
    confirmedArrival: '2025-12-23 10:15',
    shippingCost: 200000,
    loadingCompleted: true,
    loadingCompletedAt: '2025-12-23 08:30',
    loadingWorker: '물류팀 이적재',
    items: [
      { id: 1, productCode: 'SCR-E2E-002', productName: '스크린 셔터 (대형)', floor: '1층', location: 'D-01', spec: '6000×4000', qty: 1, lotNo: 'KD-TS-E2E-03-01', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: 'ACC-E2E-01' },
      { id: 2, productCode: 'SCR-E2E-002', productName: '스크린 셔터 (표준형)', floor: '2층', location: 'D-03', spec: '3000×2500', qty: 1, lotNo: 'KD-TS-E2E-03-02', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: 'ACC-E2E-02' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-12-23 10:15', changeType: '배송완료', description: '정상 배송완료', changedBy: '김운송' },
    ],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-21',
    createdBy: '[E2E] 시스템',
    note: '[E2E-103] 공정분리 스크린 1차 → 배송완료',
  },

  // SHP-E2E-03: 송도 아파트 슬랫 (수주103-02 → 배송완료)
  {
    id: 103,
    releaseNo: '251225-P-01',         // 출고번호 (채번규칙: 날짜-P-순번)
    shipmentDate: '2025-12-25',
    lotNo: 'KD-TS-251216-03',
    splitNo: 'KD-TS-251216-03-02',
    customerName: '대우건설(주)',
    siteName: '[E2E테스트] 송도 아파트 B동',
    deliveryAddress: '인천시 연수구 송도동 300',
    receiverName: '박현장',
    receiverPhone: '010-3456-7890',
    status: '배송완료',
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    shipmentPriority: 2,
    isSplitShipment: true,
    splitOrder: 2,
    dispatchType: '납품',
    logisticsCompany: '경동로지스',
    vehicleType: '2.5톤',
    vehicleNo: '서울 34나 5678',
    driverName: '박운송',
    driverPhone: '010-6666-7777',
    scheduledArrival: '2025-12-25 14:00',
    confirmedArrival: '2025-12-25 14:30',
    shippingCost: 120000,
    loadingCompleted: true,
    loadingCompletedAt: '2025-12-25 12:00',
    loadingWorker: '물류팀 이적재',
    items: [
      { id: 1, productCode: 'STL-E2E-002', productName: '철재 슬랫 셔터', floor: '1층', location: 'D-02', spec: '3500×2500', qty: 2, lotNo: 'KD-TS-E2E-04-01', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: 'ACC-E2E-03' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-12-25 14:30', changeType: '배송완료', description: '슬랫 2차분 배송완료', changedBy: '박운송' },
    ],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-20',
    createdBy: '[E2E] 시스템',
    note: '[E2E-103] 공정분리 슬랫 2차 → 배송완료',
  },

  // SHP-E2E-04: 삼성타운 1차 스크린 (수주105-01 → 배송완료)
  {
    id: 104,
    releaseNo: '251228-P-02',         // 출고번호 (채번규칙: 날짜-P-순번)
    shipmentDate: '2025-12-28',
    lotNo: 'KD-TS-251216-05',
    splitNo: 'KD-TS-251216-05-01',
    customerName: '삼성물산(주)',
    siteName: '[E2E테스트] 삼성타운 종합',
    deliveryAddress: '서울시 서초구 서초대로 500',
    receiverName: '정현장',
    receiverPhone: '010-5678-9012',
    status: '배송완료',
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    shipmentPriority: 1,
    isSplitShipment: true,
    splitOrder: 1,
    dispatchType: '납품',
    logisticsCompany: '삼성물류',
    vehicleType: '5톤',
    vehicleNo: '서울 56다 7890',
    driverName: '최운송',
    driverPhone: '010-5555-6666',
    scheduledArrival: '2025-12-28 09:00',
    confirmedArrival: '2025-12-28 09:10',
    shippingCost: 180000,
    loadingCompleted: true,
    loadingCompletedAt: '2025-12-28 07:30',
    loadingWorker: '물류팀 박적재',
    items: [
      { id: 1, productCode: 'SCR-E2E-004', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'F-01', spec: '3500×2800', qty: 2, lotNo: 'KD-TS-E2E-06-01', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: 'ACC-E2E-04' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-12-28 09:10', changeType: '배송완료', description: '1차 스크린 배송완료', changedBy: '최운송' },
    ],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-22',
    createdBy: '[E2E] 시스템',
    note: '[E2E-105] 삼성타운 3차분할 中 1차 스크린 → 배송완료',
  },

  // SHP-E2E-05: 삼성타운 2차 슬랫 (수주105-02 → 출고대기)
  {
    id: 105,
    releaseNo: '260105-P-01',         // 출고번호 (채번규칙: 날짜-P-순번)
    shipmentDate: '2026-01-05',
    lotNo: 'KD-TS-251216-05',
    splitNo: 'KD-TS-251216-05-02',
    customerName: '삼성물산(주)',
    siteName: '[E2E테스트] 삼성타운 종합',
    deliveryAddress: '서울시 서초구 서초대로 500',
    receiverName: '정현장',
    receiverPhone: '010-5678-9012',
    status: '출고대기',
    paymentConfirmed: true,
    taxInvoiceIssued: false,
    shipmentPriority: 2,
    isSplitShipment: true,
    splitOrder: 2,
    dispatchType: '상차',
    logisticsCompany: '삼성물류',
    vehicleType: '5톤',
    vehicleNo: null,
    driverName: null,
    driverPhone: null,
    scheduledArrival: '2026-01-05 10:00',
    confirmedArrival: null,
    shippingCost: 180000,
    loadingCompleted: false,
    loadingCompletedAt: null,
    loadingWorker: null,
    items: [
      { id: 1, productCode: 'STL-E2E-003', productName: '철재 슬랫 셔터', floor: '2층', location: 'F-02', spec: '4500×3200', qty: 2, lotNo: 'KD-TS-E2E-07-01', arrivedAtLoadingArea: true, loadingChecked: false, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-24',
    createdBy: '[E2E] 시스템',
    note: '[E2E-105] 삼성타운 3차분할 中 2차 슬랫 → 출고대기 (작업완료, 배차대기)',
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // 전체 워크플로우 통합 테스트 출하 데이터 10건 (ID: 301-310)
  // 품질검사(IQC/PQC/FQC-YYMMDD-XX) → 출하(SL-YYMMDD-XX) → 회계 연동
  // ═══════════════════════════════════════════════════════════════════════════

  // [통합테스트 1] SL-251221-01: 삼성물산 - 래미안 강남 프레스티지 (스크린 3대) - 배송완료
  {
    id: 301,
    releaseNo: 'SL-251221-01',
    shipmentDate: '2025-12-21',
    lotNo: 'KD-TS-251217-01',
    splitNo: 'KD-TS-251217-01-01',
    orderNo: 'KD-TS-251217-01',
    workOrderNo: 'KD-WO-251217-01',
    inspectionNo: 'IQC-251220-01',
    customerName: '삼성물산(주)',
    siteName: '래미안 강남 프레스티지',
    deliveryAddress: '서울시 강남구 테헤란로 123',
    receiverName: '박현장',
    receiverPhone: '010-1234-5678',
    status: '배송완료',
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    shipmentPriority: 1,
    isSplitShipment: false,
    splitOrder: 1,
    dispatchType: '상차',
    logisticsCompany: '한진물류',
    vehicleType: '5톤',
    vehicleNo: '12가 3456',
    driverName: '홍운전',
    driverPhone: '010-1111-2222',
    scheduledArrival: '2025-12-21 09:00',
    confirmedArrival: '2025-12-21 09:15',
    shippingCost: 180000,
    loadingCompleted: true,
    loadingCompletedAt: '2025-12-21 07:30',
    loadingWorker: '김상차',
    items: [
      { id: 1, productCode: 'SH3025', productName: '스크린 셔터 (와이어)', floor: '1층', location: 'A-01', spec: '3000×2500', qty: 1, lotNo: 'LOT-20251218-001', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
      { id: 2, productCode: 'SH3025', productName: '스크린 셔터 (와이어)', floor: '1층', location: 'A-02', spec: '3000×2500', qty: 1, lotNo: 'LOT-20251218-002', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
      { id: 3, productCode: 'SH2820', productName: '스크린 셔터 (와이어)', floor: '2층', location: 'B-01', spec: '2800×2000', qty: 1, lotNo: 'LOT-20251218-003', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-20',
    createdBy: '판매1팀 김판매',
    completedAt: '2025-12-21 14:00',
    note: '[통합테스트1] 삼성물산 - 스크린 3대 배송완료',
  },

  // [통합테스트 2] SL-251221-02: 현대건설 - 힐스테이트 판교 (스크린 2대) - 배송완료
  {
    id: 302,
    releaseNo: 'SL-251221-02',
    shipmentDate: '2025-12-21',
    lotNo: 'KD-TS-251217-02',
    splitNo: 'KD-TS-251217-02-01',
    orderNo: 'KD-TS-251217-02',
    workOrderNo: 'KD-WO-251217-02',
    inspectionNo: 'IQC-251220-02',
    customerName: '현대건설(주)',
    siteName: '힐스테이트 판교',
    deliveryAddress: '경기도 성남시 분당구 판교로 200',
    receiverName: '이현장',
    receiverPhone: '010-2345-6789',
    status: '배송완료',
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    shipmentPriority: 1,
    isSplitShipment: true,
    splitOrder: 1,
    dispatchType: '직접배차',
    logisticsCompany: null,
    vehicleType: '5톤',
    vehicleNo: '34나 5678',
    driverName: '이운전',
    driverPhone: '010-3333-4444',
    scheduledArrival: '2025-12-21 14:00',
    confirmedArrival: '2025-12-21 14:20',
    shippingCost: 0,
    loadingCompleted: true,
    loadingCompletedAt: '2025-12-21 12:00',
    loadingWorker: '박상차',
    items: [
      { id: 1, productCode: 'SH4030', productName: '스크린 셔터 (튜블러)', floor: 'B1', location: 'C-01', spec: '4000×3000', qty: 1, lotNo: 'LOT-20251219-001', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
      { id: 2, productCode: 'SH4030', productName: '스크린 셔터 (튜블러)', floor: 'B1', location: 'C-02', spec: '4000×3000', qty: 1, lotNo: 'LOT-20251219-002', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-20',
    createdBy: '판매1팀 이판매',
    completedAt: '2025-12-21 18:00',
    note: '[통합테스트2] 현대건설 - 스크린 1차분 2대 배송완료',
  },

  // [통합테스트 3] SL-251223-01: 현대건설 - 힐스테이트 판교 (슬랫 2대) - 출고대기
  {
    id: 303,
    releaseNo: 'SL-251223-01',
    shipmentDate: '2025-12-23',
    lotNo: 'KD-TS-251217-02',
    splitNo: 'KD-TS-251217-02-02',
    orderNo: 'KD-TS-251217-02',
    workOrderNo: 'KD-WO-251217-03',
    inspectionNo: 'PQC-251219-01',
    customerName: '현대건설(주)',
    siteName: '힐스테이트 판교',
    deliveryAddress: '경기도 성남시 분당구 판교로 200',
    receiverName: '이현장',
    receiverPhone: '010-2345-6789',
    status: '출고대기',
    paymentConfirmed: false,
    taxInvoiceIssued: false,
    shipmentPriority: 2,
    isSplitShipment: true,
    splitOrder: 2,
    dispatchType: '상차',
    logisticsCompany: '경동로지스',
    vehicleType: '5톤',
    vehicleNo: null,
    driverName: null,
    driverPhone: null,
    scheduledArrival: '2025-12-23 10:00',
    confirmedArrival: null,
    shippingCost: 150000,
    loadingCompleted: false,
    loadingCompletedAt: null,
    loadingWorker: null,
    items: [
      { id: 1, productCode: 'SL3525', productName: '슬랫 셔터', floor: '1층', location: 'D-01', spec: '3500×2500', qty: 1, lotNo: 'LOT-20251219-003', arrivedAtLoadingArea: true, loadingChecked: false, accessoryLotNo: '' },
      { id: 2, productCode: 'SL3525', productName: '슬랫 셔터', floor: '1층', location: 'D-02', spec: '3500×2500', qty: 1, lotNo: 'LOT-20251219-004', arrivedAtLoadingArea: true, loadingChecked: false, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-22',
    createdBy: '판매1팀 이판매',
    note: '[통합테스트3] 현대건설 - 슬랫 2차분 2대 출고대기 (검사 진행중)',
  },

  // [통합테스트 4] SL-251222-01: 대우건설 - 푸르지오 일산 (대형 스크린 2대) - 배송완료
  {
    id: 304,
    releaseNo: 'SL-251222-01',
    shipmentDate: '2025-12-22',
    lotNo: 'KD-TS-251217-03',
    splitNo: 'KD-TS-251217-03-01',
    orderNo: 'KD-TS-251217-03',
    workOrderNo: 'KD-WO-251217-04',
    inspectionNo: 'IQC-251221-01',
    customerName: '대우건설(주)',
    siteName: '푸르지오 일산',
    deliveryAddress: '경기도 고양시 일산동구 중앙로 1000',
    receiverName: '최현장',
    receiverPhone: '010-3456-7890',
    status: '배송완료',
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    shipmentPriority: 1,
    isSplitShipment: false,
    splitOrder: 1,
    dispatchType: '상차',
    logisticsCompany: '대한통운',
    vehicleType: '11톤',
    vehicleNo: '56다 7890',
    driverName: '박운전',
    driverPhone: '010-5555-6666',
    scheduledArrival: '2025-12-22 09:00',
    confirmedArrival: '2025-12-22 09:30',
    shippingCost: 250000,
    loadingCompleted: true,
    loadingCompletedAt: '2025-12-22 07:00',
    loadingWorker: '김상차',
    items: [
      { id: 1, productCode: 'SH6035', productName: '스크린 셔터 (대형)', floor: 'B2', location: 'E-01', spec: '6000×3500', qty: 1, lotNo: 'LOT-20251220-001', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
      { id: 2, productCode: 'SH6035', productName: '스크린 셔터 (대형)', floor: 'B2', location: 'E-02', spec: '6000×3500', qty: 1, lotNo: 'LOT-20251220-002', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-21',
    createdBy: '판매1팀 박판매',
    completedAt: '2025-12-22 15:00',
    note: '[통합테스트4] 대우건설 - 대형 스크린 2대 배송완료 (11톤 차량)',
  },

  // [통합테스트 5] SL-251222-02: GS건설 - 자이 위례 (슬랫 4대) - 배송완료
  {
    id: 305,
    releaseNo: 'SL-251222-02',
    shipmentDate: '2025-12-22',
    lotNo: 'KD-TS-251217-04',
    splitNo: 'KD-TS-251217-04-01',
    orderNo: 'KD-TS-251217-04',
    workOrderNo: 'KD-WO-251217-05',
    inspectionNo: 'PQC-251220-01',
    customerName: 'GS건설(주)',
    siteName: '자이 위례',
    deliveryAddress: '경기도 성남시 수정구 위례중앙로 50',
    receiverName: '정현장',
    receiverPhone: '010-4567-8901',
    status: '배송완료',
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    shipmentPriority: 1,
    isSplitShipment: false,
    splitOrder: 1,
    dispatchType: '직접배차',
    logisticsCompany: null,
    vehicleType: '5톤',
    vehicleNo: '78라 9012',
    driverName: '최운전',
    driverPhone: '010-7777-8888',
    scheduledArrival: '2025-12-22 14:00',
    confirmedArrival: '2025-12-22 14:10',
    shippingCost: 0,
    loadingCompleted: true,
    loadingCompletedAt: '2025-12-22 12:00',
    loadingWorker: '이상차',
    items: [
      { id: 1, productCode: 'SL2520', productName: '슬랫 셔터', floor: '1층', location: 'F-01', spec: '2500×2000', qty: 1, lotNo: 'LOT-20251219-005', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
      { id: 2, productCode: 'SL2520', productName: '슬랫 셔터', floor: '1층', location: 'F-02', spec: '2500×2000', qty: 1, lotNo: 'LOT-20251219-006', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
      { id: 3, productCode: 'SL3020', productName: '슬랫 셔터', floor: '2층', location: 'G-01', spec: '3000×2000', qty: 1, lotNo: 'LOT-20251219-007', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
      { id: 4, productCode: 'SL3020', productName: '슬랫 셔터', floor: '2층', location: 'G-02', spec: '3000×2000', qty: 1, lotNo: 'LOT-20251219-008', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-21',
    createdBy: '판매1팀 최판매',
    completedAt: '2025-12-22 18:00',
    note: '[통합테스트5] GS건설 - 슬랫 4대 배송완료',
  },

  // [통합테스트 6] SL-251223-02: 포스코건설 - 더샵 송도 (코너형 스크린 2대) - 배송중
  {
    id: 306,
    releaseNo: 'SL-251223-02',
    shipmentDate: '2025-12-23',
    lotNo: 'KD-TS-251217-05',
    splitNo: 'KD-TS-251217-05-01',
    orderNo: 'KD-TS-251217-05',
    workOrderNo: 'KD-WO-251217-06',
    inspectionNo: 'IQC-251222-01',
    customerName: '포스코건설(주)',
    siteName: '더샵 송도',
    deliveryAddress: '인천시 연수구 송도동 123',
    receiverName: '한현장',
    receiverPhone: '010-5678-9012',
    status: '배송중',
    paymentConfirmed: false,
    taxInvoiceIssued: false,
    shipmentPriority: 1,
    isSplitShipment: false,
    splitOrder: 1,
    dispatchType: '상차',
    logisticsCompany: '한진물류',
    vehicleType: '5톤',
    vehicleNo: '90마 1234',
    driverName: '김운전',
    driverPhone: '010-9999-0000',
    scheduledArrival: '2025-12-23 11:00',
    confirmedArrival: null,
    shippingCost: 200000,
    loadingCompleted: true,
    loadingCompletedAt: '2025-12-23 08:00',
    loadingWorker: '박상차',
    items: [
      { id: 1, productCode: 'SH3530C', productName: '스크린 셔터 (코너형)', floor: '1층', location: 'H-01', spec: '3500×3000', qty: 1, lotNo: 'LOT-20251221-001', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
      { id: 2, productCode: 'SH3530C', productName: '스크린 셔터 (코너형)', floor: '1층', location: 'H-02', spec: '3500×3000', qty: 1, lotNo: 'LOT-20251221-002', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-22',
    createdBy: '판매1팀 한판매',
    note: '[통합테스트6] 포스코건설 - 코너형 스크린 2대 배송중',
  },

  // [통합테스트 7] SL-251221-03: 호반건설 - 써밋 광교 1차분 (스크린 2대) - 배송완료
  {
    id: 307,
    releaseNo: 'SL-251221-03',
    shipmentDate: '2025-12-21',
    lotNo: 'KD-TS-251217-06',
    splitNo: 'KD-TS-251217-06-01',
    orderNo: 'KD-TS-251217-06',
    workOrderNo: 'KD-WO-251217-07',
    inspectionNo: 'IQC-251220-03',
    customerName: '호반건설(주)',
    siteName: '써밋 광교',
    deliveryAddress: '경기도 수원시 영통구 광교로 100',
    receiverName: '오현장',
    receiverPhone: '010-6789-0123',
    status: '배송완료',
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    shipmentPriority: 1,
    isSplitShipment: true,
    splitOrder: 1,
    dispatchType: '직접배차',
    logisticsCompany: null,
    vehicleType: '3.5톤',
    vehicleNo: '12바 3456',
    driverName: '이운전',
    driverPhone: '010-1212-3434',
    scheduledArrival: '2025-12-21 10:00',
    confirmedArrival: '2025-12-21 10:30',
    shippingCost: 0,
    loadingCompleted: true,
    loadingCompletedAt: '2025-12-21 08:00',
    loadingWorker: '최상차',
    items: [
      { id: 1, productCode: 'SH3228', productName: '스크린 셔터 (와이어)', floor: 'B1', location: 'I-01', spec: '3200×2800', qty: 1, lotNo: 'LOT-20251218-004', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
      { id: 2, productCode: 'SH3228', productName: '스크린 셔터 (와이어)', floor: 'B1', location: 'I-02', spec: '3200×2800', qty: 1, lotNo: 'LOT-20251218-005', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-20',
    createdBy: '판매1팀 오판매',
    completedAt: '2025-12-21 15:00',
    note: '[통합테스트7] 호반건설 - 1차 분할 출하 완료 (3차 분할 중 1차)',
  },

  // [통합테스트 8] SL-251224-01: 호반건설 - 써밋 광교 2차분 (스크린 2대) - 출고지시
  {
    id: 308,
    releaseNo: 'SL-251224-01',
    shipmentDate: '2025-12-24',
    lotNo: 'KD-TS-251217-06',
    splitNo: 'KD-TS-251217-06-02',
    orderNo: 'KD-TS-251217-06',
    workOrderNo: 'KD-WO-251217-08',
    inspectionNo: 'IQC-251223-01',
    customerName: '호반건설(주)',
    siteName: '써밋 광교',
    deliveryAddress: '경기도 수원시 영통구 광교로 100',
    receiverName: '오현장',
    receiverPhone: '010-6789-0123',
    status: '출고지시',
    paymentConfirmed: false,
    taxInvoiceIssued: false,
    shipmentPriority: 2,
    isSplitShipment: true,
    splitOrder: 2,
    dispatchType: '상차',
    logisticsCompany: '경동로지스',
    vehicleType: '3.5톤',
    vehicleNo: null,
    driverName: null,
    driverPhone: null,
    scheduledArrival: '2025-12-24 10:00',
    confirmedArrival: null,
    shippingCost: 120000,
    loadingCompleted: false,
    loadingCompletedAt: null,
    loadingWorker: null,
    items: [
      { id: 1, productCode: 'SH3228', productName: '스크린 셔터 (와이어)', floor: 'B1', location: 'I-03', spec: '3200×2800', qty: 1, lotNo: 'LOT-20251222-001', arrivedAtLoadingArea: true, loadingChecked: false, accessoryLotNo: '' },
      { id: 2, productCode: 'SH3228', productName: '스크린 셔터 (와이어)', floor: '1층', location: 'J-01', spec: '3200×2800', qty: 1, lotNo: 'LOT-20251222-002', arrivedAtLoadingArea: true, loadingChecked: false, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-23',
    createdBy: '판매1팀 오판매',
    note: '[통합테스트8] 호반건설 - 2차 분할 출고지시 (3차 분할 중 2차)',
  },

  // [통합테스트 9] 태영건설 - 데시앙 동탄 - 품질불량으로 출하 보류
  {
    id: 309,
    releaseNo: 'SL-251222-03',
    shipmentDate: '2025-12-22',
    lotNo: 'KD-TS-251217-09',
    splitNo: 'KD-TS-251217-09-01',
    orderNo: 'KD-TS-251217-09',
    workOrderNo: 'KD-WO-251217-11',
    inspectionNo: 'IQC-251221-02',
    customerName: '태영건설(주)',
    siteName: '데시앙 동탄',
    deliveryAddress: '경기도 화성시 동탄순환대로 100',
    receiverName: '강현장',
    receiverPhone: '010-7890-1234',
    status: '출하보류',
    paymentConfirmed: false,
    taxInvoiceIssued: false,
    shipmentPriority: 1,
    isSplitShipment: false,
    splitOrder: 1,
    dispatchType: '상차',
    logisticsCompany: '한진물류',
    vehicleType: '5톤',
    vehicleNo: null,
    driverName: null,
    driverPhone: null,
    scheduledArrival: '2025-12-22 14:00',
    confirmedArrival: null,
    shippingCost: 0,
    loadingCompleted: false,
    loadingCompletedAt: null,
    loadingWorker: null,
    items: [
      { id: 1, productCode: 'SH2822', productName: '스크린 셔터 (와이어)', floor: 'B1', location: 'K-01', spec: '2800×2200', qty: 1, lotNo: 'LOT-20251220-003', arrivedAtLoadingArea: false, loadingChecked: false, accessoryLotNo: '' },
      { id: 2, productCode: 'SH2822', productName: '스크린 셔터 (와이어)', floor: 'B1', location: 'K-02', spec: '2800×2200', qty: 1, lotNo: 'LOT-20251220-004', arrivedAtLoadingArea: false, loadingChecked: false, accessoryLotNo: '' },
      { id: 3, productCode: 'SH2822', productName: '스크린 셔터 (와이어)', floor: '1층', location: 'L-01', spec: '2800×2200', qty: 1, lotNo: 'LOT-20251220-005', arrivedAtLoadingArea: false, loadingChecked: false, accessoryLotNo: '' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-12-21 17:30', changeType: '상태 변경', beforeValue: '출고지시', afterValue: '출하보류', reason: '품질검사 불합격 (NCR-251221-01)', changedBy: '품질팀 이검사' },
    ],
    cancelReason: '품질검사 불합격 - NCR-251221-01 발행, 재작업 후 재검사 필요',
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-20',
    createdBy: '판매1팀 강판매',
    note: '[통합테스트9] 태영건설 - 품질불량으로 출하 보류 (NCR 발행, 재작업 진행중)',
  },

  // [통합테스트 10] SL-251220-01: 두산건설 - 위브 청라 (스크린 1대) - 배송완료 (전체 플로우 완료)
  {
    id: 310,
    releaseNo: 'SL-251220-01',
    shipmentDate: '2025-12-20',
    lotNo: 'KD-TS-251217-10',
    splitNo: 'KD-TS-251217-10-01',
    orderNo: 'KD-TS-251217-10',
    workOrderNo: 'KD-WO-251217-12',
    inspectionNo: 'FQC-251219-01',
    customerName: '두산건설(주)',
    siteName: '위브 청라',
    deliveryAddress: '인천시 서구 청라동 456',
    receiverName: '임현장',
    receiverPhone: '010-8901-2345',
    status: '배송완료',
    paymentConfirmed: true,
    taxInvoiceIssued: true,
    shipmentPriority: 1,
    isSplitShipment: false,
    splitOrder: 1,
    dispatchType: '직접배차',
    logisticsCompany: null,
    vehicleType: '3.5톤',
    vehicleNo: '34사 5678',
    driverName: '정운전',
    driverPhone: '010-5656-7878',
    scheduledArrival: '2025-12-20 10:00',
    confirmedArrival: '2025-12-20 10:15',
    shippingCost: 0,
    loadingCompleted: true,
    loadingCompletedAt: '2025-12-20 08:30',
    loadingWorker: '김상차',
    items: [
      { id: 1, productCode: 'SH3225', productName: '스크린 셔터 (와이어)', floor: '1층', location: 'M-01', spec: '3200×2500', qty: 1, lotNo: 'LOT-20251217-001', arrivedAtLoadingArea: true, loadingChecked: true, accessoryLotNo: '' },
    ],
    changeHistory: [],
    cancelReason: null,
    canceledAt: null,
    canceledBy: null,
    createdAt: '2025-12-19',
    createdBy: '판매1팀 임판매',
    completedAt: '2025-12-20 14:00',
    note: '[통합테스트10] 두산건설 - 전체 플로우 완료 (견적→수주→생산→품질→출하→회계)',
  },
];

// 품질검사 (제품검사)
// 제품검사LOT: KD-SA-YYMMDD-순번 (설치LOT와 동일)
const initialProductInspections = [
  {
    id: 1,
    inspectionNo: 'KD-SA-250216-01', // 제품검사LOT: KD-SA-YYMMDD-순번
    requestDate: '2025-02-16',
    requestedBy: '서울건축 김대리',
    status: '검사예정', // 검사신청 → 검사예정 → 검사중 → 합격/불합격 → 결재완료
    // 연결 정보 (로트번호 기준)
    lotNo: 'KD-TS-250115-01',         // 로트번호 (추적 기준)
    splitNo: 'KD-TS-250115-01-01',    // 분할번호
    customerName: '서울건축',
    siteName: '강남 오피스텔 A동',
    // 세트로트 (여러 출하 로트 묶음) - 설치LOT = 제품검사LOT
    setLotNo: 'KD-SA-250216-01', // 설치LOT는 제품검사LOT와 동일
    lotNos: ['KD-TS-250210-01-01', 'KD-TS-250210-01-02'], // 완제품LOT 목록
    // 검사 정보
    inspector: '품질팀 이검사',
    scheduledDate: '2025-02-20',
    scheduledTime: '10:00',
    // 개소별 검사 (50개 설치 → 50장 검사서)
    totalItems: 2,
    completedItems: 0,
    passedItems: 0,
    failedItems: 0,
    items: [
      { id: 1, floor: '1층', location: 'A-01', productName: '스크린 셔터 (표준형)', orderSpec: '7660×2550', productLot: 'KD-TS-250210-01-01', installedSpec: null, specMatch: null, result: null, inspectedAt: null, note: '' },
      { id: 2, floor: '1층', location: 'A-02', productName: '스크린 셔터 (표준형)', orderSpec: '6500×2400', productLot: 'KD-TS-250210-01-02', installedSpec: null, specMatch: null, result: null, inspectedAt: null, note: '' },
    ],
    // 승인 정보
    approvalStatus: '대기', // 대기 → 결재대기 → 결재완료
    approvedBy: null,
    approvedAt: null,
    // 변경 이력
    scheduleHistory: [],
    createdAt: '2025-02-16',
    createdBy: '품질팀 이검사',
  },
  {
    id: 2,
    inspectionNo: 'KD-SA-250218-01',
    requestDate: '2025-02-18',
    requestedBy: '인천건설 박과장',
    status: '검사신청',
    lotNo: 'KD-TS-250118-01',         // 로트번호
    splitNo: null,
    customerName: '인천건설',
    siteName: '송도 오피스텔 B동',
    setLotNo: null,
    lotNos: [],
    inspector: null,
    scheduledDate: null,
    scheduledTime: null,
    totalItems: 4,
    completedItems: 0,
    passedItems: 0,
    failedItems: 0,
    items: [
      { id: 1, floor: 'B1', location: 'C-01', productName: '스크린 셔터 (표준형)', orderSpec: '6000×2400', productLot: null, installedSpec: null, specMatch: null, result: null, inspectedAt: null, note: '' },
      { id: 2, floor: 'B1', location: 'C-01', productName: '스크린 셔터 (표준형)', orderSpec: '6000×2400', productLot: null, installedSpec: null, specMatch: null, result: null, inspectedAt: null, note: '' },
      { id: 3, floor: '1층', location: 'D-01', productName: '슬랫 셔터', orderSpec: '4500×2000', productLot: null, installedSpec: null, specMatch: null, result: null, inspectedAt: null, note: '' },
      { id: 4, floor: '1층', location: 'D-01', productName: '슬랫 셔터', orderSpec: '4500×2000', productLot: null, installedSpec: null, specMatch: null, result: null, inspectedAt: null, note: '' },
    ],
    approvalStatus: '대기',
    approvedBy: null,
    approvedAt: null,
    scheduleHistory: [],
    createdAt: '2025-02-18',
    createdBy: '품질팀 최품질',
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // 전체 워크플로우 통합 테스트 품질검사 데이터 10건 (ID: 301-310)
  // 작업지시(WO-251217-XX) → 품질검사(IQC/PQC-YYMMDD-XX) → 출하 연동
  // ═══════════════════════════════════════════════════════════════════════════

  // [통합테스트 1] IQC-251220-01: 삼성물산 - 래미안 강남 프레스티지 (스크린 3대) - 합격
  {
    id: 301,
    inspectionNo: 'IQC-251220-01',
    requestDate: '2025-12-20',
    requestedBy: '생산팀 김스크린',
    status: '검사완료',
    inspectionType: '중간검사',
    workOrderNo: 'KD-WO-251217-01',
    orderNo: 'KD-TS-251217-01',
    lotNo: 'KD-TS-251217-01',
    splitNo: 'KD-TS-251217-01-01',
    customerName: '삼성물산(주)',
    siteName: '래미안 강남 프레스티지',
    setLotNo: 'IQC-251220-01',
    lotNos: ['LOT-20251218-001', 'LOT-20251218-002', 'LOT-20251218-003'],
    inspector: '품질팀 이검사',
    scheduledDate: '2025-12-20',
    scheduledTime: '14:00',
    totalItems: 3,
    completedItems: 3,
    passedItems: 3,
    failedItems: 0,
    items: [
      { id: 1, floor: '1층', location: 'A-01', productName: '스크린 셔터 (와이어)', productCode: 'SH3025', orderSpec: '3000×2500', productLot: 'LOT-20251218-001', installedSpec: '3000×2500', specMatch: true, result: '합격', inspectedAt: '2025-12-20 14:30', note: '' },
      { id: 2, floor: '1층', location: 'A-02', productName: '스크린 셔터 (와이어)', productCode: 'SH3025', orderSpec: '3000×2500', productLot: 'LOT-20251218-002', installedSpec: '3000×2500', specMatch: true, result: '합격', inspectedAt: '2025-12-20 15:00', note: '' },
      { id: 3, floor: '2층', location: 'B-01', productName: '스크린 셔터 (와이어)', productCode: 'SH2820', orderSpec: '2800×2000', productLot: 'LOT-20251218-003', installedSpec: '2800×2000', specMatch: true, result: '합격', inspectedAt: '2025-12-20 15:30', note: '' },
    ],
    inspectionItems: [
      { id: 1, itemName: '외관검사', standard: '찍힘, 스크래치 없음', result: '합격', note: '' },
      { id: 2, itemName: '치수검사', standard: '±5mm 이내', result: '합격', note: '모든 규격 공차 이내' },
      { id: 3, itemName: '작동검사', standard: '원활한 개폐 동작', result: '합격', note: '' },
      { id: 4, itemName: '안전장치', standard: '급정지 기능 정상', result: '합격', note: '' },
    ],
    approvalStatus: '결재완료',
    approvedBy: '품질팀장 박품질',
    approvedAt: '2025-12-20 16:00',
    scheduleHistory: [],
    createdAt: '2025-12-20',
    createdBy: '품질팀 이검사',
  },

  // [통합테스트 2] IQC-251220-02: 현대건설 - 힐스테이트 판교 (스크린 2대) - 합격
  {
    id: 302,
    inspectionNo: 'IQC-251220-02',
    requestDate: '2025-12-20',
    requestedBy: '생산팀 이스크린',
    status: '검사완료',
    inspectionType: '중간검사',
    workOrderNo: 'KD-WO-251217-02',
    orderNo: 'KD-TS-251217-02',
    lotNo: 'KD-TS-251217-02',
    splitNo: 'KD-TS-251217-02-01',
    customerName: '현대건설(주)',
    siteName: '힐스테이트 판교',
    setLotNo: 'IQC-251220-02',
    lotNos: ['LOT-20251219-001', 'LOT-20251219-002'],
    inspector: '품질팀 이검사',
    scheduledDate: '2025-12-20',
    scheduledTime: '16:00',
    totalItems: 2,
    completedItems: 2,
    passedItems: 2,
    failedItems: 0,
    items: [
      { id: 1, floor: 'B1', location: 'C-01', productName: '스크린 셔터 (튜블러)', productCode: 'SH4030', orderSpec: '4000×3000', productLot: 'LOT-20251219-001', installedSpec: '4000×3000', specMatch: true, result: '합격', inspectedAt: '2025-12-20 16:30', note: '' },
      { id: 2, floor: 'B1', location: 'C-02', productName: '스크린 셔터 (튜블러)', productCode: 'SH4030', orderSpec: '4000×3000', productLot: 'LOT-20251219-002', installedSpec: '4000×3000', specMatch: true, result: '합격', inspectedAt: '2025-12-20 17:00', note: '' },
    ],
    inspectionItems: [
      { id: 1, itemName: '외관검사', standard: '찍힘, 스크래치 없음', result: '합격', note: '' },
      { id: 2, itemName: '치수검사', standard: '±5mm 이내', result: '합격', note: '' },
      { id: 3, itemName: '작동검사', standard: '원활한 개폐 동작', result: '합격', note: '' },
    ],
    approvalStatus: '결재완료',
    approvedBy: '품질팀장 박품질',
    approvedAt: '2025-12-20 17:30',
    scheduleHistory: [],
    createdAt: '2025-12-20',
    createdBy: '품질팀 이검사',
  },

  // [통합테스트 3] PQC-251219-01: 현대건설 - 힐스테이트 판교 (슬랫 2대) - 공정검사 진행중
  {
    id: 303,
    inspectionNo: 'PQC-251219-01',
    requestDate: '2025-12-19',
    requestedBy: '생산팀 박슬랫',
    status: '검사중',
    inspectionType: '공정검사',
    workOrderNo: 'KD-WO-251217-03',
    orderNo: 'KD-TS-251217-02',
    lotNo: 'KD-TS-251217-02',
    splitNo: 'KD-TS-251217-02-02',
    customerName: '현대건설(주)',
    siteName: '힐스테이트 판교',
    setLotNo: 'PQC-251219-01',
    lotNos: ['LOT-20251219-003', 'LOT-20251219-004'],
    inspector: '품질팀 최품질',
    scheduledDate: '2025-12-22',
    scheduledTime: '10:00',
    totalItems: 2,
    completedItems: 1,
    passedItems: 1,
    failedItems: 0,
    items: [
      { id: 1, floor: '1층', location: 'D-01', productName: '슬랫 셔터', productCode: 'SL3525', orderSpec: '3500×2500', productLot: 'LOT-20251219-003', installedSpec: '3500×2500', specMatch: true, result: '합격', inspectedAt: '2025-12-22 10:30', note: '' },
      { id: 2, floor: '1층', location: 'D-02', productName: '슬랫 셔터', productCode: 'SL3525', orderSpec: '3500×2500', productLot: 'LOT-20251219-004', installedSpec: null, specMatch: null, result: null, inspectedAt: null, note: '' },
    ],
    inspectionItems: [
      { id: 1, itemName: '외관검사', standard: '도장 상태 양호', result: '합격', note: '' },
      { id: 2, itemName: '치수검사', standard: '±5mm 이내', result: '합격', note: '' },
      { id: 3, itemName: '작동검사', standard: '원활한 개폐 동작', result: null, note: '' },
    ],
    approvalStatus: '대기',
    approvedBy: null,
    approvedAt: null,
    scheduleHistory: [],
    createdAt: '2025-12-19',
    createdBy: '품질팀 최품질',
  },

  // [통합테스트 4] IQC-251221-01: 대우건설 - 푸르지오 일산 (스크린 2대) - 합격
  {
    id: 304,
    inspectionNo: 'IQC-251221-01',
    requestDate: '2025-12-21',
    requestedBy: '생산팀 김스크린',
    status: '검사완료',
    inspectionType: '중간검사',
    workOrderNo: 'KD-WO-251217-04',
    orderNo: 'KD-TS-251217-03',
    lotNo: 'KD-TS-251217-03',
    splitNo: 'KD-TS-251217-03-01',
    customerName: '대우건설(주)',
    siteName: '푸르지오 일산',
    setLotNo: 'IQC-251221-01',
    lotNos: ['LOT-20251220-001', 'LOT-20251220-002'],
    inspector: '품질팀 이검사',
    scheduledDate: '2025-12-21',
    scheduledTime: '09:00',
    totalItems: 2,
    completedItems: 2,
    passedItems: 2,
    failedItems: 0,
    items: [
      { id: 1, floor: 'B2', location: 'E-01', productName: '스크린 셔터 (대형)', productCode: 'SH6035', orderSpec: '6000×3500', productLot: 'LOT-20251220-001', installedSpec: '6000×3500', specMatch: true, result: '합격', inspectedAt: '2025-12-21 09:30', note: '대형 규격 특별검사 완료' },
      { id: 2, floor: 'B2', location: 'E-02', productName: '스크린 셔터 (대형)', productCode: 'SH6035', orderSpec: '6000×3500', productLot: 'LOT-20251220-002', installedSpec: '6000×3500', specMatch: true, result: '합격', inspectedAt: '2025-12-21 10:00', note: '' },
    ],
    inspectionItems: [
      { id: 1, itemName: '외관검사', standard: '찍힘, 스크래치 없음', result: '합격', note: '' },
      { id: 2, itemName: '치수검사', standard: '±5mm 이내', result: '합격', note: '대형 규격 공차 확인' },
      { id: 3, itemName: '작동검사', standard: '원활한 개폐 동작', result: '합격', note: '' },
      { id: 4, itemName: '하중검사', standard: '정격하중 견딤', result: '합격', note: '500kg 모터 성능 확인' },
    ],
    approvalStatus: '결재완료',
    approvedBy: '품질팀장 박품질',
    approvedAt: '2025-12-21 11:00',
    scheduleHistory: [],
    createdAt: '2025-12-21',
    createdBy: '품질팀 이검사',
  },

  // [통합테스트 5] PQC-251220-01: GS건설 - 자이 위례 (슬랫 4대) - 합격
  {
    id: 305,
    inspectionNo: 'PQC-251220-01',
    requestDate: '2025-12-20',
    requestedBy: '생산팀 박슬랫',
    status: '검사완료',
    inspectionType: '공정검사',
    workOrderNo: 'KD-WO-251217-05',
    orderNo: 'KD-TS-251217-04',
    lotNo: 'KD-TS-251217-04',
    splitNo: 'KD-TS-251217-04-01',
    customerName: 'GS건설(주)',
    siteName: '자이 위례',
    setLotNo: 'PQC-251220-01',
    lotNos: ['LOT-20251219-005', 'LOT-20251219-006', 'LOT-20251219-007', 'LOT-20251219-008'],
    inspector: '품질팀 최품질',
    scheduledDate: '2025-12-21',
    scheduledTime: '14:00',
    totalItems: 4,
    completedItems: 4,
    passedItems: 4,
    failedItems: 0,
    items: [
      { id: 1, floor: '1층', location: 'F-01', productName: '슬랫 셔터', productCode: 'SL2520', orderSpec: '2500×2000', productLot: 'LOT-20251219-005', installedSpec: '2500×2000', specMatch: true, result: '합격', inspectedAt: '2025-12-21 14:30', note: '' },
      { id: 2, floor: '1층', location: 'F-02', productName: '슬랫 셔터', productCode: 'SL2520', orderSpec: '2500×2000', productLot: 'LOT-20251219-006', installedSpec: '2500×2000', specMatch: true, result: '합격', inspectedAt: '2025-12-21 15:00', note: '' },
      { id: 3, floor: '2층', location: 'G-01', productName: '슬랫 셔터', productCode: 'SL3020', orderSpec: '3000×2000', productLot: 'LOT-20251219-007', installedSpec: '3000×2000', specMatch: true, result: '합격', inspectedAt: '2025-12-21 15:30', note: '' },
      { id: 4, floor: '2층', location: 'G-02', productName: '슬랫 셔터', productCode: 'SL3020', orderSpec: '3000×2000', productLot: 'LOT-20251219-008', installedSpec: '3000×2000', specMatch: true, result: '합격', inspectedAt: '2025-12-21 16:00', note: '' },
    ],
    inspectionItems: [
      { id: 1, itemName: '외관검사', standard: '도장 상태 양호', result: '합격', note: '' },
      { id: 2, itemName: '치수검사', standard: '±5mm 이내', result: '합격', note: '' },
      { id: 3, itemName: '작동검사', standard: '원활한 개폐 동작', result: '합격', note: '' },
    ],
    approvalStatus: '결재완료',
    approvedBy: '품질팀장 박품질',
    approvedAt: '2025-12-21 16:30',
    scheduleHistory: [],
    createdAt: '2025-12-20',
    createdBy: '품질팀 최품질',
  },

  // [통합테스트 6] IQC-251222-01: 포스코건설 - 더샵 송도 (스크린 코너형 2대) - 합격
  {
    id: 306,
    inspectionNo: 'IQC-251222-01',
    requestDate: '2025-12-22',
    requestedBy: '생산팀 김스크린',
    status: '검사완료',
    inspectionType: '중간검사',
    workOrderNo: 'KD-WO-251217-06',
    orderNo: 'KD-TS-251217-05',
    lotNo: 'KD-TS-251217-05',
    splitNo: 'KD-TS-251217-05-01',
    customerName: '포스코건설(주)',
    siteName: '더샵 송도',
    setLotNo: 'IQC-251222-01',
    lotNos: ['LOT-20251221-001', 'LOT-20251221-002'],
    inspector: '품질팀 이검사',
    scheduledDate: '2025-12-22',
    scheduledTime: '10:00',
    totalItems: 2,
    completedItems: 2,
    passedItems: 2,
    failedItems: 0,
    items: [
      { id: 1, floor: '1층', location: 'H-01', productName: '스크린 셔터 (코너형)', productCode: 'SH3530C', orderSpec: '3500×3000', productLot: 'LOT-20251221-001', installedSpec: '3500×3000', specMatch: true, result: '합격', inspectedAt: '2025-12-22 10:30', note: '코너형 가이드레일 연결부 양호' },
      { id: 2, floor: '1층', location: 'H-02', productName: '스크린 셔터 (코너형)', productCode: 'SH3530C', orderSpec: '3500×3000', productLot: 'LOT-20251221-002', installedSpec: '3500×3000', specMatch: true, result: '합격', inspectedAt: '2025-12-22 11:00', note: '' },
    ],
    inspectionItems: [
      { id: 1, itemName: '외관검사', standard: '찍힘, 스크래치 없음', result: '합격', note: '' },
      { id: 2, itemName: '치수검사', standard: '±5mm 이내', result: '합격', note: '' },
      { id: 3, itemName: '작동검사', standard: '원활한 개폐 동작', result: '합격', note: '' },
      { id: 4, itemName: '코너부 검사', standard: '코너 연결부 밀착', result: '합격', note: '코너 가이드 연결 양호' },
    ],
    approvalStatus: '결재완료',
    approvedBy: '품질팀장 박품질',
    approvedAt: '2025-12-22 11:30',
    scheduleHistory: [],
    createdAt: '2025-12-22',
    createdBy: '품질팀 이검사',
  },

  // [통합테스트 7] IQC-251220-03: 호반건설 - 써밋 광교 1차분 (스크린 2대) - 합격
  {
    id: 307,
    inspectionNo: 'IQC-251220-03',
    requestDate: '2025-12-20',
    requestedBy: '생산팀 이스크린',
    status: '검사완료',
    inspectionType: '중간검사',
    workOrderNo: 'KD-WO-251217-07',
    orderNo: 'KD-TS-251217-06',
    lotNo: 'KD-TS-251217-06',
    splitNo: 'KD-TS-251217-06-01',
    customerName: '호반건설(주)',
    siteName: '써밋 광교',
    setLotNo: 'IQC-251220-03',
    lotNos: ['LOT-20251218-004', 'LOT-20251218-005'],
    inspector: '품질팀 이검사',
    scheduledDate: '2025-12-20',
    scheduledTime: '11:00',
    totalItems: 2,
    completedItems: 2,
    passedItems: 2,
    failedItems: 0,
    items: [
      { id: 1, floor: 'B1', location: 'I-01', productName: '스크린 셔터 (와이어)', productCode: 'SH3228', orderSpec: '3200×2800', productLot: 'LOT-20251218-004', installedSpec: '3200×2800', specMatch: true, result: '합격', inspectedAt: '2025-12-20 11:30', note: '' },
      { id: 2, floor: 'B1', location: 'I-02', productName: '스크린 셔터 (와이어)', productCode: 'SH3228', orderSpec: '3200×2800', productLot: 'LOT-20251218-005', installedSpec: '3200×2800', specMatch: true, result: '합격', inspectedAt: '2025-12-20 12:00', note: '' },
    ],
    inspectionItems: [
      { id: 1, itemName: '외관검사', standard: '찍힘, 스크래치 없음', result: '합격', note: '' },
      { id: 2, itemName: '치수검사', standard: '±5mm 이내', result: '합격', note: '' },
      { id: 3, itemName: '작동검사', standard: '원활한 개폐 동작', result: '합격', note: '' },
    ],
    approvalStatus: '결재완료',
    approvedBy: '품질팀장 박품질',
    approvedAt: '2025-12-20 12:30',
    scheduleHistory: [],
    createdAt: '2025-12-20',
    createdBy: '품질팀 이검사',
  },

  // [통합테스트 8] IQC-251223-01: 호반건설 - 써밋 광교 2차분 (스크린 2대) - 합격
  {
    id: 308,
    inspectionNo: 'IQC-251223-01',
    requestDate: '2025-12-23',
    requestedBy: '생산팀 이스크린',
    status: '검사완료',
    inspectionType: '중간검사',
    workOrderNo: 'KD-WO-251217-08',
    orderNo: 'KD-TS-251217-06',
    lotNo: 'KD-TS-251217-06',
    splitNo: 'KD-TS-251217-06-02',
    customerName: '호반건설(주)',
    siteName: '써밋 광교',
    setLotNo: 'IQC-251223-01',
    lotNos: ['LOT-20251222-001', 'LOT-20251222-002'],
    inspector: '품질팀 최품질',
    scheduledDate: '2025-12-23',
    scheduledTime: '09:00',
    totalItems: 2,
    completedItems: 2,
    passedItems: 2,
    failedItems: 0,
    items: [
      { id: 1, floor: 'B1', location: 'I-03', productName: '스크린 셔터 (와이어)', productCode: 'SH3228', orderSpec: '3200×2800', productLot: 'LOT-20251222-001', installedSpec: '3200×2800', specMatch: true, result: '합격', inspectedAt: '2025-12-23 09:30', note: '' },
      { id: 2, floor: '1층', location: 'J-01', productName: '스크린 셔터 (와이어)', productCode: 'SH3228', orderSpec: '3200×2800', productLot: 'LOT-20251222-002', installedSpec: '3200×2800', specMatch: true, result: '합격', inspectedAt: '2025-12-23 10:00', note: '' },
    ],
    inspectionItems: [
      { id: 1, itemName: '외관검사', standard: '찍힘, 스크래치 없음', result: '합격', note: '' },
      { id: 2, itemName: '치수검사', standard: '±5mm 이내', result: '합격', note: '' },
      { id: 3, itemName: '작동검사', standard: '원활한 개폐 동작', result: '합격', note: '' },
    ],
    approvalStatus: '결재완료',
    approvedBy: '품질팀장 박품질',
    approvedAt: '2025-12-23 10:30',
    scheduleHistory: [],
    createdAt: '2025-12-23',
    createdBy: '품질팀 최품질',
  },

  // [통합테스트 9] IQC-251221-02: 태영건설 - 데시앙 동탄 (스크린 3대) - 불합격 (NCR 발행)
  {
    id: 309,
    inspectionNo: 'IQC-251221-02',
    requestDate: '2025-12-21',
    requestedBy: '생산팀 김스크린',
    status: '불합격',
    inspectionType: '중간검사',
    workOrderNo: 'KD-WO-251217-11',
    orderNo: 'KD-TS-251217-09',
    lotNo: 'KD-TS-251217-09',
    splitNo: 'KD-TS-251217-09-01',
    customerName: '태영건설(주)',
    siteName: '데시앙 동탄',
    setLotNo: 'IQC-251221-02',
    lotNos: ['LOT-20251220-003', 'LOT-20251220-004', 'LOT-20251220-005'],
    inspector: '품질팀 이검사',
    scheduledDate: '2025-12-21',
    scheduledTime: '15:00',
    totalItems: 3,
    completedItems: 3,
    passedItems: 1,
    failedItems: 2,
    items: [
      { id: 1, floor: 'B1', location: 'K-01', productName: '스크린 셔터 (와이어)', productCode: 'SH2822', orderSpec: '2800×2200', productLot: 'LOT-20251220-003', installedSpec: '2800×2200', specMatch: true, result: '합격', inspectedAt: '2025-12-21 15:30', note: '' },
      { id: 2, floor: 'B1', location: 'K-02', productName: '스크린 셔터 (와이어)', productCode: 'SH2822', orderSpec: '2800×2200', productLot: 'LOT-20251220-004', installedSpec: '2795×2200', specMatch: false, result: '불합격', inspectedAt: '2025-12-21 16:00', note: '가이드레일 설치 불량 - 기울어짐 발견' },
      { id: 3, floor: '1층', location: 'L-01', productName: '스크린 셔터 (와이어)', productCode: 'SH2822', orderSpec: '2800×2200', productLot: 'LOT-20251220-005', installedSpec: '2800×2195', specMatch: false, result: '불합격', inspectedAt: '2025-12-21 16:30', note: '스크린 원단 손상 - 재작업 필요' },
    ],
    inspectionItems: [
      { id: 1, itemName: '외관검사', standard: '찍힘, 스크래치 없음', result: '불합격', note: '원단 손상 발견' },
      { id: 2, itemName: '치수검사', standard: '±5mm 이내', result: '불합격', note: '공차 초과' },
      { id: 3, itemName: '작동검사', standard: '원활한 개폐 동작', result: '불합격', note: '개폐 시 걸림 발생' },
    ],
    ncrNo: 'NCR-251221-01',
    ncrStatus: '재작업중',
    ncrNote: '가이드레일 재설치 및 스크린 원단 교체 작업 진행중',
    approvalStatus: '결재완료',
    approvedBy: '품질팀장 박품질',
    approvedAt: '2025-12-21 17:00',
    scheduleHistory: [],
    createdAt: '2025-12-21',
    createdBy: '품질팀 이검사',
  },

  // [통합테스트 10] FQC-251219-01: 두산건설 - 위브 청라 (스크린 1대) - 최종검사 합격 (출하완료)
  {
    id: 310,
    inspectionNo: 'FQC-251219-01',
    requestDate: '2025-12-19',
    requestedBy: '생산팀 김스크린',
    status: '검사완료',
    inspectionType: '최종검사',
    workOrderNo: 'KD-WO-251217-12',
    orderNo: 'KD-TS-251217-10',
    lotNo: 'KD-TS-251217-10',
    splitNo: 'KD-TS-251217-10-01',
    customerName: '두산건설(주)',
    siteName: '위브 청라',
    setLotNo: 'FQC-251219-01',
    lotNos: ['LOT-20251217-001'],
    inspector: '품질팀 이검사',
    scheduledDate: '2025-12-19',
    scheduledTime: '09:00',
    totalItems: 1,
    completedItems: 1,
    passedItems: 1,
    failedItems: 0,
    items: [
      { id: 1, floor: '1층', location: 'M-01', productName: '스크린 셔터 (와이어)', productCode: 'SH3225', orderSpec: '3200×2500', productLot: 'LOT-20251217-001', installedSpec: '3200×2500', specMatch: true, result: '합격', inspectedAt: '2025-12-19 09:30', note: '최종검사 합격 - 출하 가능' },
    ],
    inspectionItems: [
      { id: 1, itemName: '외관검사', standard: '찍힘, 스크래치 없음', result: '합격', note: '' },
      { id: 2, itemName: '치수검사', standard: '±5mm 이내', result: '합격', note: '' },
      { id: 3, itemName: '작동검사', standard: '원활한 개폐 동작', result: '합격', note: '' },
      { id: 4, itemName: '안전장치', standard: '급정지 기능 정상', result: '합격', note: '' },
      { id: 5, itemName: '포장상태', standard: '포장 이상 없음', result: '합격', note: '출하 포장 완료' },
    ],
    shipmentNo: 'SL-251220-01',
    shipmentStatus: '출하완료',
    approvalStatus: '결재완료',
    approvedBy: '품질팀장 박품질',
    approvedAt: '2025-12-19 10:00',
    scheduleHistory: [],
    createdAt: '2025-12-19',
    createdBy: '품질팀 이검사',
  },
];

// ============ 거래처 관리 샘플 데이터 ============
const initialCustomers = [
  {
    id: 'CUS-001',
    customerCode: 'CUS-001',
    customerName: '삼성물산(주)',
    ceo: '김삼성',
    businessNo: '123-45-67890',
    businessType: '건설업',
    businessItem: '건축,토목',
    zipCode: '06235',
    address: '서울시 강남구 테헤란로 123',
    addressDetail: '삼성빌딩 15층',
    phone: '02-1234-5678',
    fax: '02-1234-5679',
    email: 'samsung@samsung-const.co.kr',
    customerType: '매출',
    creditGrade: 'A',
    creditNote: '우량 거래처',
    creditLimit: 100000000,
    paymentTerms: '월말 마감 익월 10일 결제',
    paymentMethod: '계좌이체',
    contacts: [
      { id: 1, name: '박현장', position: '현장소장', phone: '010-1234-5678', email: 'park@samsung-const.co.kr', isPrimary: true },
      { id: 2, name: '이구매', position: '구매담당', phone: '010-2345-6789', email: 'lee@samsung-const.co.kr', isPrimary: false },
    ],
    transactions: [
      { date: '2025-02-20', type: '수주', amount: 52000000, balance: 52000000, note: 'KD-SO-250205-01' },
      { date: '2025-02-25', type: '입금', amount: 52000000, balance: 0, note: '전액입금' },
    ],
    receivables: { total: 0, overdue: 0, overdueDays: 0 },
    registeredAt: '2024-01-15',
    registeredBy: '판매팀 김판매',
    modifiedAt: '2025-02-01',
    modifiedBy: '판매팀 김판매',
  },
  {
    id: 'CUS-002',
    customerCode: 'CUS-002',
    customerName: '현대건설(주)',
    ceo: '정현대',
    businessNo: '234-56-78901',
    businessType: '건설업',
    businessItem: '건축,인테리어',
    zipCode: '04520',
    address: '서울시 중구 을지로 234',
    addressDetail: '현대빌딩 8층',
    phone: '02-2345-6789',
    fax: '02-2345-6780',
    email: 'info@hyundai-dev.co.kr',
    customerType: '매출',
    creditGrade: 'B',
    creditNote: '결제 약간 지연 이력 있음',
    creditLimit: 50000000,
    paymentTerms: '월말 마감 익월 말 결제',
    paymentMethod: '계좌이체',
    contacts: [
      { id: 1, name: '최구매', position: '구매팀장', phone: '010-3456-7890', email: 'choi@hyundai-dev.co.kr', isPrimary: true },
    ],
    transactions: [
      { date: '2025-02-15', type: '수주', amount: 28000000, balance: 28000000, note: 'KD-SO-250208-01' },
    ],
    receivables: { total: 28000000, overdue: 0, overdueDays: 0 },
    registeredAt: '2024-03-20',
    registeredBy: '판매팀 이판매',
    modifiedAt: '2025-01-15',
    modifiedBy: '판매팀 이판매',
  },
  {
    id: 'CUS-003',
    customerCode: 'CUS-003',
    customerName: '대우건설(주)',
    ceo: '한화중',
    businessNo: '345-67-89012',
    businessType: '건설업',
    businessItem: '건축,시설공사',
    zipCode: '07321',
    address: '서울시 영등포구 여의대로 345',
    addressDetail: '한화빌딩 3층',
    phone: '02-3456-7890',
    fax: '02-3456-7891',
    email: 'info@hanwha-const.co.kr',
    customerType: '매출',
    creditGrade: 'C',
    creditNote: '입금약속 미이행 이력 있음 - 경리승인 필요',
    creditLimit: 20000000,
    paymentTerms: '선입금 50% 후 잔금',
    paymentMethod: '계좌이체',
    contacts: [
      { id: 1, name: '김담당', position: '공사담당', phone: '010-4567-8901', email: 'kim@hanwha-const.co.kr', isPrimary: true },
    ],
    transactions: [
      { date: '2025-02-18', type: '수주', amount: 18000000, balance: 18000000, note: 'KD-SO-250210-01' },
    ],
    receivables: { total: 18000000, overdue: 5000000, overdueDays: 15 },
    registeredAt: '2024-06-10',
    registeredBy: '판매팀 박판매',
    modifiedAt: '2025-02-10',
    modifiedBy: '경리팀 최경리',
  },
  {
    id: 'CUS-004',
    customerCode: 'CUS-004',
    customerName: '(주)서울인테리어',
    ceo: '박부산',
    businessNo: '456-78-90123',
    businessType: '건설업',
    businessItem: '건축,토목',
    zipCode: '48060',
    address: '부산시 해운대구 센텀중앙로 456',
    addressDetail: '센텀빌딩 12층',
    phone: '051-456-7890',
    fax: '051-456-7891',
    email: 'info@busan-const.co.kr',
    customerType: '매출',
    creditGrade: 'A',
    creditNote: '우량 거래처',
    creditLimit: 80000000,
    paymentTerms: '월말 마감 익월 15일 결제',
    paymentMethod: '계좌이체',
    contacts: [
      { id: 1, name: '이현장', position: '현장소장', phone: '010-5678-9012', email: 'lee@busan-const.co.kr', isPrimary: true },
    ],
    transactions: [
      { date: '2025-02-20', type: '수주', amount: 35000000, balance: 35000000, note: 'KD-SO-250212-01' },
    ],
    receivables: { total: 35000000, overdue: 0, overdueDays: 0 },
    registeredAt: '2024-02-28',
    registeredBy: '판매팀 최판매',
    modifiedAt: '2025-02-20',
    modifiedBy: '판매팀 최판매',
  },
  {
    id: 'SUP-001',
    customerCode: 'SUP-001',
    customerName: '(주)대한알루미늄',
    ceo: '김대한',
    businessNo: '567-89-01234',
    businessType: '제조업',
    businessItem: '알루미늄 가공',
    zipCode: '15850',
    address: '경기도 군포시 산본로 567',
    addressDetail: '대한공장',
    phone: '031-567-8901',
    fax: '031-567-8902',
    email: 'sales@daehan-al.co.kr',
    customerType: '매입',
    supplyType: '자재',
    creditGrade: 'A',
    creditNote: '주요 자재 공급처',
    creditLimit: 0,
    paymentTerms: '월말 마감 익월 10일 지급',
    paymentMethod: '계좌이체',
    contacts: [
      { id: 1, name: '박판매', position: '판매팀장', phone: '010-6789-0123', email: 'park@daehan-al.co.kr', isPrimary: true },
    ],
    transactions: [],
    receivables: { total: 0, overdue: 0, overdueDays: 0 },
    registeredAt: '2023-05-15',
    registeredBy: '구매팀 정구매',
    modifiedAt: '2024-12-01',
    modifiedBy: '구매팀 정구매',
  },
];

// ============ 현장 관리 샘플 데이터 ============
const initialSites = [
  {
    id: 'SITE-001',
    siteCode: 'PJ-250201-01',
    siteName: '강남 더리버 아파트 신축현장',
    customerId: 1, // 삼성물산(주) - customerMasterConfig 기준
    customerName: '삼성물산(주)',
    orderNo: 'KD-SO-250205-01',
    siteAddress: '서울시 강남구 압구정로 123',
    siteContact: '02-1234-9999',
    installManager: '박설치',
    installManagerPhone: '010-9999-1234',
    installScheduledDate: '2025-03-01',
    installCompletedDate: '2025-02-28',
    status: '설치완료',
    progress: 100,
    note: 'B1층 주차장 스크린 셔터 설치 완료',
    orders: [
      { orderNo: 'KD-SO-250205-01', product: '스크린 셔터', qty: 5, amount: 52000000 },
    ],
    shipments: [
      { shipmentNo: 'KD-SH-250215-01', date: '2025-02-15', qty: 5, status: '배송완료' },
    ],
    history: [
      { date: '2025-02-01', action: '현장등록', note: '신규 현장 등록', by: '판매팀 김판매' },
      { date: '2025-02-15', action: '출하완료', note: '전량 출하', by: '물류팀 박물류' },
      { date: '2025-02-28', action: '설치완료', note: '설치 검수 완료', by: '박설치' },
    ],
    registeredAt: '2025-02-01',
    registeredBy: '판매팀 김판매',
  },
  {
    id: 'SITE-002',
    siteCode: 'PJ-250208-01',
    siteName: '중구 을지타워 리모델링현장',
    customerId: 2, // 현대건설(주) - customerMasterConfig 기준
    customerName: '현대건설(주)',
    orderNo: 'KD-SO-250208-01',
    siteAddress: '서울시 중구 을지로 456',
    siteContact: '02-2345-9999',
    installManager: '이설치',
    installManagerPhone: '010-8888-2345',
    installScheduledDate: '2025-03-15',
    installCompletedDate: null,
    status: '생산완료',
    progress: 60,
    note: '입금 확인 후 출고 예정',
    orders: [
      { orderNo: 'KD-SO-250208-01', product: '스크린 셔터', qty: 3, amount: 28000000 },
    ],
    shipments: [],
    history: [
      { date: '2025-02-08', action: '현장등록', note: '신규 현장 등록', by: '판매팀 이판매' },
      { date: '2025-02-15', action: '생산완료', note: '생산 완료, 출고보류', by: '생산팀 김생산' },
    ],
    registeredAt: '2025-02-08',
    registeredBy: '판매팀 이판매',
  },
  {
    id: 'SITE-003',
    siteCode: 'PJ-250212-01',
    siteName: '해운대 마린시티 오피스텔',
    customerId: 4, // (주)서울인테리어 - customerMasterConfig 기준
    customerName: '(주)서울인테리어',
    orderNo: 'KD-SO-250212-01',
    siteAddress: '부산시 해운대구 마린시티 789',
    siteContact: '051-789-9999',
    installManager: '최설치',
    installManagerPhone: '010-7777-3456',
    installScheduledDate: '2025-03-25',
    installCompletedDate: null,
    status: '생산중',
    progress: 40,
    note: '분할 출하 예정 - 1차 3/15, 2차 3/25',
    orders: [
      { orderNo: 'KD-SO-250212-01', product: '슬랫 셔터', qty: 8, amount: 35000000 },
    ],
    shipments: [
      { shipmentNo: 'KD-SH-250315-01', date: '2025-03-15', qty: 4, status: '출하준비' },
    ],
    history: [
      { date: '2025-02-12', action: '현장등록', note: '신규 현장 등록', by: '판매팀 최판매' },
      { date: '2025-02-15', action: '생산시작', note: '분할 생산 시작', by: '생산팀 박생산' },
    ],
    registeredAt: '2025-02-12',
    registeredBy: '판매팀 최판매',
  },
];

// ============ 단가 관리 샘플 데이터 ============
const initialPrices = [
  {
    id: 'PRC-001',
    priceCode: 'PRC-001',
    customerId: 1, // 삼성물산(주) - customerMasterConfig 기준
    customerName: '삼성물산(주)',
    productCode: 'SCR-001',
    productName: '스크린 셔터 (표준형)',
    spec: '기본규격',
    unit: 'EA',
    basePrice: 2500000,
    discountRate: 5,
    finalPrice: 2375000,
    currency: 'KRW',
    validFrom: '2025-01-01',
    validTo: '2025-12-31',
    minQty: 1,
    qtyPricing: [
      { minQty: 1, maxQty: 4, price: 2375000 },
      { minQty: 5, maxQty: 9, price: 2300000 },
      { minQty: 10, maxQty: 999, price: 2200000 },
    ],
    status: '적용중',
    approvedBy: '판매팀장 박판매',
    approvedAt: '2024-12-20',
    history: [
      { date: '2024-12-20', action: '신규등록', oldPrice: null, newPrice: 2375000, by: '판매팀 김판매' },
    ],
    registeredAt: '2024-12-20',
    registeredBy: '판매팀 김판매',
  },
  {
    id: 'PRC-002',
    priceCode: 'PRC-002',
    customerId: 1, // 삼성물산(주) - customerMasterConfig 기준
    customerName: '삼성물산(주)',
    productCode: 'SLT-001',
    productName: '슬랫 셔터 (일반형)',
    spec: '기본규격',
    unit: 'EA',
    basePrice: 3500000,
    discountRate: 5,
    finalPrice: 3325000,
    currency: 'KRW',
    validFrom: '2025-01-01',
    validTo: '2025-12-31',
    minQty: 1,
    qtyPricing: [],
    status: '적용중',
    approvedBy: '판매팀장 박판매',
    approvedAt: '2024-12-20',
    history: [],
    registeredAt: '2024-12-20',
    registeredBy: '판매팀 김판매',
  },
  {
    id: 'PRC-003',
    priceCode: 'PRC-003',
    customerId: 2, // 현대건설(주) - customerMasterConfig 기준
    customerName: '현대건설(주)',
    productCode: 'SCR-001',
    productName: '스크린 셔터 (표준형)',
    spec: '기본규격',
    unit: 'EA',
    basePrice: 2500000,
    discountRate: 3,
    finalPrice: 2425000,
    currency: 'KRW',
    validFrom: '2025-01-01',
    validTo: '2025-12-31',
    minQty: 1,
    qtyPricing: [],
    status: '적용중',
    approvedBy: '판매팀장 박판매',
    approvedAt: '2024-12-25',
    history: [
      { date: '2024-12-25', action: '신규등록', oldPrice: null, newPrice: 2425000, by: '판매팀 이판매' },
    ],
    registeredAt: '2024-12-25',
    registeredBy: '판매팀 이판매',
  },
  {
    id: 'PRC-004',
    priceCode: 'PRC-004',
    customerId: null,
    customerName: '기본단가',
    productCode: 'SCR-001',
    productName: '스크린 셔터 (표준형)',
    spec: '기본규격',
    unit: 'EA',
    basePrice: 2500000,
    discountRate: 0,
    finalPrice: 2500000,
    currency: 'KRW',
    validFrom: '2024-01-01',
    validTo: '2099-12-31',
    minQty: 1,
    qtyPricing: [],
    status: '적용중',
    approvedBy: '대표이사',
    approvedAt: '2024-01-01',
    history: [],
    registeredAt: '2024-01-01',
    registeredBy: '시스템',
  },
  {
    id: 'PRC-005',
    priceCode: 'PRC-005',
    customerId: null,
    customerName: '기본단가',
    productCode: 'SLT-001',
    productName: '슬랫 셔터 (일반형)',
    spec: '기본규격',
    unit: 'EA',
    basePrice: 3500000,
    discountRate: 0,
    finalPrice: 3500000,
    currency: 'KRW',
    validFrom: '2024-01-01',
    validTo: '2099-12-31',
    minQty: 1,
    qtyPricing: [],
    status: '적용중',
    approvedBy: '대표이사',
    approvedAt: '2024-01-01',
    history: [],
    registeredAt: '2024-01-01',
    registeredBy: '시스템',
  },
];

// ============ 견적 관리 ============

// 견적 샘플 데이터
// 채번규칙: KD-PR-YYMMDD-## (견적서), 현장코드: PJ-YYMMDD-## (현장)
const sampleQuotesData = [
  // ========== 스크린샷에 맞는 샘플 데이터 ==========
  // 1: KD-PR-240115-01 - 최초 작성
  {
    id: 1,
    quoteNo: 'KD-PR-240115-01',
    quoteDate: '2024-01-15',
    status: '최초작성',
    productName: 'SCR-001',
    productCode: 'SCR-001',
    qty: 10,
    totalAmount: 15000000,
    customerId: 1, // 삼성물산(주)
    customerCode: 'CUS-001',
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteName: '강남 오피스텔 현장',
    siteCode: 'PJ-240110-01',
    manager: '김철수',
    contact: '010-1111-1111',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    dueDate: '2024-02-15',
    createdBy: '판매1팀 김판매',
    note: '급하게 진행 필요',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 15000000,
    items: []
  },
  // 2: KD-PR-240116-01 - 2차 수정
  {
    id: 2,
    quoteNo: 'KD-PR-240116-01',
    quoteDate: '2024-01-16',
    status: '2차 수정',
    productName: 'STL-002',
    productCode: 'STL-002',
    qty: 5,
    totalAmount: 8500000,
    customerId: 2, // 현대건설(주)
    customerCode: 'CUS-002',
    customerName: '현대건설(주)',
    creditGrade: 'A',
    siteName: '판교 공장',
    siteCode: 'PJ-240112-01',
    manager: '이영희',
    contact: '010-2222-2222',
    deliveryAddress: '경기도 성남시 분당구 판교로 200',
    dueDate: '2024-02-20',
    createdBy: '판매1팀 이판매',
    note: '-',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 8500000,
    items: []
  },
  // 3: KD-PR-240117-01 - 최종확정
  {
    id: 3,
    quoteNo: 'KD-PR-240117-01',
    quoteDate: '2024-01-17',
    status: '최종확정',
    productName: 'SCR-003',
    productCode: 'SCR-003',
    qty: 20,
    totalAmount: 25000000,
    customerId: 3, // 대우건설(주)
    customerCode: 'CUS-003',
    customerName: '대우건설(주)',
    creditGrade: 'A',
    siteName: '송도 아파트 현장',
    siteCode: 'PJ-240113-01',
    manager: '박민수',
    contact: '010-3333-3333',
    deliveryAddress: '인천시 연수구 송도동 300',
    dueDate: '2024-02-25',
    createdBy: '판매2팀 박판매',
    note: '확정 완료',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 25000000,
    items: []
  },
  // 4: KD-PR-240118-01 - 수주전환
  {
    id: 4,
    quoteNo: 'KD-PR-240118-01',
    quoteDate: '2024-01-18',
    status: '수주전환',
    productName: 'STL-004',
    productCode: 'STL-004',
    qty: 8,
    totalAmount: 12000000,
    customerId: 4, // (주)서울인테리어
    customerCode: 'CUS-004',
    customerName: '(주)서울인테리어',
    creditGrade: 'B',
    siteName: '분당 상가 현장',
    siteCode: 'PJ-240114-01',
    manager: '최지원',
    contact: '010-4444-4444',
    deliveryAddress: '경기도 성남시 분당구 수내동 400',
    dueDate: '2024-03-01',
    createdBy: '판매1팀 최판매',
    note: '수주 전환 완료',
    relatedOrders: ['KD-TS-240123-01'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 12000000,
    items: []
  },
  // 5: KD-PR-240119-01 - 3차 수정
  {
    id: 5,
    quoteNo: 'KD-PR-240119-01',
    quoteDate: '2024-01-19',
    status: '3차 수정',
    productName: 'SCR-005',
    productCode: 'SCR-005',
    qty: 15,
    totalAmount: 22000000,
    customerId: 1, // 삼성물산(주) - 다른 현장
    customerCode: 'CUS-001',
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteName: '용산 오피스빌딩',
    siteCode: 'PJ-240115-01',
    manager: '정수민',
    contact: '010-5555-5555',
    deliveryAddress: '서울시 용산구 한강로 500',
    dueDate: '2024-03-05',
    createdBy: '판매2팀 정판매',
    note: '3차 수정 중',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 22000000,
    items: []
  },
  // 6: KD-PR-250208-01 - 2차 수정
  {
    id: 6,
    quoteNo: 'KD-PR-250208-01',
    quoteDate: '2025-02-08',
    status: '2차 수정',
    productName: 'FD-002',
    productCode: 'FD-002',
    qty: 120,
    totalAmount: 48000000,
    customerId: 1, // 삼성물산(주)
    customerCode: 'CUS-001',
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteName: '강남 타워 신축현장',
    siteCode: 'PJ-250201-01',
    manager: '김영업',
    contact: '010-1111-1111',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    dueDate: '2025-03-20',
    createdBy: '판매1팀 김판매',
    note: '-',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 48000000,
    items: []
  },
  // 7: KD-PR-250215-01 - 최종확정
  {
    id: 7,
    quoteNo: 'KD-PR-250215-01',
    quoteDate: '2025-02-15',
    status: '최종확정',
    productName: 'ST-001',
    productCode: 'ST-001',
    qty: 80,
    totalAmount: 35000000,
    customerId: 2, // 현대건설(주)
    customerCode: 'CUS-002',
    customerName: '현대건설(주)',
    creditGrade: 'A',
    siteName: '연수 오피스텔',
    siteCode: 'PJ-250210-01',
    manager: '홍길동',
    contact: '010-2222-2222',
    deliveryAddress: '인천시 연수구 동춘동 500',
    dueDate: '2025-04-10',
    createdBy: '판매1팀 이판매',
    note: '오피스텔 신축 공사',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 35000000,
    items: []
  },
  // 8: KD-PR-251029-01 - 최초 작성
  {
    id: 8,
    quoteNo: 'KD-PR-251029-01',
    quoteDate: '2025-10-29',
    status: '최초작성',
    productName: '스크린 셔터-표준형',
    productCode: 'SCR-001',
    qty: 1,
    totalAmount: 3400000,
    customerId: 3, // 대우건설(주)
    customerCode: 'CUS-003',
    customerName: '대우건설(주)',
    creditGrade: 'A',
    siteName: '송도 오피스텔 A동',
    siteCode: 'PJ-251025-01',
    manager: '김영업',
    contact: '010-6666-6666',
    deliveryAddress: '인천시 연수구 송도동 100',
    dueDate: '2025-11-30',
    createdBy: '판매1팀 김영업',
    note: '송도 오피스텔 A동 101호 거실창',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 3400000,
    items: []
  },

  // ========== 테스트용: 스크린+슬랫 혼합 견적 ==========
  {
    id: 9,
    quoteNo: 'KD-PR-250301-01',
    quoteDate: '2025-03-01',
    status: '최종확정',
    productName: '스크린/슬랫 셔터',
    productCode: 'MIX-001',
    qty: 5,
    totalAmount: 32000000,
    customerId: 2, // 현대건설(주)
    customerCode: 'CUS-002',
    customerName: '현대건설(주)',
    creditGrade: 'A',
    siteName: '판교 테크노밸리 신축',
    siteCode: 'PJ-250225-01',
    manager: '김테크',
    contact: '010-5555-5555',
    deliveryAddress: '경기도 성남시 분당구 판교로 123',
    dueDate: '2025-04-15',
    createdBy: '판매1팀 박판매',
    note: '[테스트] 스크린+슬랫 혼합 주문 - 공정 분리 테스트',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 32000000,
    items: [
      { id: 1, floor: '1층', location: 'A-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 6000, height: 2500, guideType: '일반', motorPower: '220V', controller: '없음', qty: 2, wingIndex: 50, inspectionFee: 50000, unitPrice: 8000000, amount: 16000000, orderStatus: 'pending', orderId: null },
      { id: 2, floor: 'B1', location: 'B-01', category: '슬랫', productName: '슬랫 셔터', width: 4000, height: 2000, guideType: '일반', motorPower: '220V', controller: '없음', qty: 3, wingIndex: 45, inspectionFee: 50000, unitPrice: 5333333, amount: 16000000, orderStatus: 'pending', orderId: null }
    ]
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // E2E 테스트용 견적 데이터 (새 수식 기준 자동산출 결과 포함)
  // ═══════════════════════════════════════════════════════════════════════════
  {
    id: 101,
    quoteNo: 'KD-PR-251216-01',
    quoteDate: '2025-12-16',
    status: '최종확정',
    productName: '스크린 셔터 (E2E 테스트 1)',
    productCode: 'SCR-E2E-001',
    qty: 3,
    totalAmount: 18500000,
    customerId: 1,
    customerCode: 'CUS-001',
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteName: '[E2E테스트] 강남 오피스 A동',
    siteCode: 'PJ-251210-01',
    manager: '김테스트',
    contact: '010-1234-5678',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    dueDate: '2025-12-30',
    createdBy: '[E2E] 시스템',
    note: 'E2E 전체 프로세스 테스트 - 스크린 제품 (W3000×H2500)',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 18500000,
    // 새 수식 기준 자동산출 파라미터
    autoCalcParams: { PC: '스크린', W0: 3000, H0: 2500, QTY: 3, V: '220', WIRE: '유선', CT: '매립', GT: '벽면형' },
    // 자동산출 결과 (formulaEngine 기준)
    autoCalcResult: {
      W1: 3140, H1: 2850, M: 8.95, K: 60.41,
      SHAFT_INCH: '5', MAIN_SHAFT_LEN: 4500, SUB_SHAFT_LEN: 300,
      MOTOR_KG: 300, GR_MAT_LEN: 3000, CASE_MAT_LEN: 4270,
      HJ_MAT_LEN: 3000, HWANBONG_QTY: 2, JOINTBAR_QTY: 4,
      SQP3000_QTY: 2, SQP6000_QTY: 1
    },
    items: [
      { id: 1, floor: '1층', location: 'A-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 50, inspectionFee: 50000, unitPrice: 6166667, amount: 6166667, orderStatus: 'pending', orderId: null, process: 'screen' },
      { id: 2, floor: '2층', location: 'A-02', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 50, inspectionFee: 50000, unitPrice: 6166667, amount: 6166667, orderStatus: 'pending', orderId: null, process: 'screen' },
      { id: 3, floor: '3층', location: 'A-03', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 50, inspectionFee: 50000, unitPrice: 6166667, amount: 6166666, orderStatus: 'pending', orderId: null, process: 'screen' }
    ]
  },
  {
    id: 102,
    quoteNo: 'KD-PR-251216-02',
    quoteDate: '2025-12-16',
    status: '최종확정',
    productName: '철재 슬랫 셔터 (E2E 테스트 2)',
    productCode: 'STL-E2E-001',
    qty: 2,
    totalAmount: 15000000,
    customerId: 2,
    customerName: '현대건설(주)',
    creditGrade: 'A',
    siteName: '[E2E테스트] 판교 물류센터',
    siteCode: 'PJ-251216-02',
    manager: '이테스트',
    contact: '010-2345-6789',
    deliveryAddress: '경기도 성남시 분당구 판교로 200',
    dueDate: '2025-12-28',
    createdBy: '[E2E] 시스템',
    note: 'E2E 전체 프로세스 테스트 - 철재 슬랫 제품 (W4000×H3000)',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 15000000,
    autoCalcParams: { PC: '철재', W0: 4000, H0: 3000, QTY: 2, V: '220', WIRE: '유선', CT: '노출', GT: '코너형' },
    autoCalcResult: {
      W1: 4110, H1: 3350, M: 13.77, K: 344.21,
      SHAFT_INCH: '4', MAIN_SHAFT_LEN: 4500,
      MOTOR_KG: 300, GR_MAT_LEN: 3500, CASE_MAT_LEN: 4270,
      HJ_MAT_LEN: 4000, JOINTBAR_QTY: 5,
      SQP3000_QTY: 5, SQP6000_QTY: 1
    },
    items: [
      { id: 1, floor: 'B1', location: 'C-01', category: '슬랫', productName: '철재 슬랫 셔터', width: 4000, height: 3000, guideType: '코너형', motorPower: '220V', controller: '노출형', qty: 1, wingIndex: 60, inspectionFee: 50000, unitPrice: 7500000, amount: 7500000, orderStatus: 'pending', orderId: null, process: 'slat' },
      { id: 2, floor: 'B2', location: 'C-02', category: '슬랫', productName: '철재 슬랫 셔터', width: 4000, height: 3000, guideType: '코너형', motorPower: '220V', controller: '노출형', qty: 1, wingIndex: 60, inspectionFee: 50000, unitPrice: 7500000, amount: 7500000, orderStatus: 'pending', orderId: null, process: 'slat' }
    ]
  },
  {
    id: 103,
    quoteNo: 'KD-PR-251216-03',
    quoteDate: '2025-12-16',
    status: '최종확정',
    productName: '스크린+슬랫 혼합 (E2E 테스트 3)',
    productCode: 'MIX-E2E-001',
    qty: 4,
    totalAmount: 28000000,
    customerId: 3,
    customerName: '대우건설(주)',
    creditGrade: 'A',
    siteName: '[E2E테스트] 송도 아파트 B동',
    siteCode: 'PJ-251216-03',
    manager: '박테스트',
    contact: '010-3456-7890',
    deliveryAddress: '인천시 연수구 송도동 300',
    dueDate: '2025-12-25',
    createdBy: '[E2E] 시스템',
    note: 'E2E 전체 프로세스 테스트 - 스크린+슬랫 혼합 (공정분리 테스트)',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 28000000,
    items: [
      { id: 1, floor: '1층', location: 'D-01', category: '스크린', productName: '스크린 셔터 (대형)', width: 6000, height: 4000, guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, wingIndex: 80, inspectionFee: 80000, unitPrice: 12000000, amount: 12000000, orderStatus: 'pending', orderId: null, process: 'screen' },
      { id: 2, floor: '1층', location: 'D-02', category: '슬랫', productName: '철재 슬랫 셔터', width: 3500, height: 2500, guideType: '벽면형', motorPower: '220V', controller: '노출형', qty: 2, wingIndex: 45, inspectionFee: 50000, unitPrice: 5000000, amount: 10000000, orderStatus: 'pending', orderId: null, process: 'slat' },
      { id: 3, floor: '2층', location: 'D-03', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 50, inspectionFee: 50000, unitPrice: 6000000, amount: 6000000, orderStatus: 'pending', orderId: null, process: 'screen' }
    ]
  },
  {
    id: 104,
    quoteNo: 'KD-PR-251216-04',
    quoteDate: '2025-12-16',
    status: '최종확정',
    productName: '스크린 대형 (E2E 테스트 4)',
    productCode: 'SCR-E2E-002',
    qty: 2,
    totalAmount: 22000000,
    customerId: 4,
    customerName: '(주)서울인테리어',
    creditGrade: 'B',
    siteName: '[E2E테스트] 용산 호텔',
    siteCode: 'PJ-251216-04',
    manager: '최테스트',
    contact: '010-4567-8901',
    deliveryAddress: '서울시 용산구 한강로 400',
    dueDate: '2025-12-31',
    createdBy: '[E2E] 시스템',
    note: 'E2E 전체 프로세스 테스트 - 대형 스크린 (W6000×H4000) 모터 용량 체크',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 22000000,
    autoCalcParams: { PC: '스크린', W0: 6000, H0: 4000, QTY: 2, V: '380', WIRE: '무선', CT: '매립', GT: '벽면형' },
    autoCalcResult: {
      W1: 6140, H1: 4350, M: 26.71, K: 138.44,
      SHAFT_INCH: '5', MAIN_SHAFT_LEN: 7000, SUB_SHAFT_LEN: 300,
      MOTOR_KG: 500, GR_MAT_LEN: 4500, CASE_MAT_LEN: 6700,
      HJ_MAT_LEN: 3000, HWANBONG_QTY: 3, JOINTBAR_QTY: 7,
      SQP3000_QTY: 4, SQP6000_QTY: 1
    },
    items: [
      { id: 1, floor: '로비', location: 'E-01', category: '스크린', productName: '스크린 셔터 (대형)', width: 6000, height: 4000, guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, wingIndex: 80, inspectionFee: 80000, unitPrice: 11000000, amount: 11000000, orderStatus: 'pending', orderId: null, process: 'screen' },
      { id: 2, floor: '연회장', location: 'E-02', category: '스크린', productName: '스크린 셔터 (대형)', width: 6000, height: 4000, guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, wingIndex: 80, inspectionFee: 80000, unitPrice: 11000000, amount: 11000000, orderStatus: 'pending', orderId: null, process: 'screen' }
    ]
  },
  {
    id: 105,
    quoteNo: 'KD-PR-251216-05',
    quoteDate: '2025-12-16',
    status: '최종확정',
    productName: '전 공정 통합 (E2E 테스트 5)',
    productCode: 'FULL-E2E-001',
    qty: 6,
    totalAmount: 45000000,
    customerId: 1,
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteName: '[E2E테스트] 삼성타운 종합',
    siteCode: 'PJ-251216-05',
    manager: '정테스트',
    contact: '010-5678-9012',
    deliveryAddress: '서울시 서초구 서초대로 500',
    dueDate: '2026-01-15',
    createdBy: '[E2E] 시스템',
    note: 'E2E 전체 프로세스 테스트 - 스크린+슬랫+절곡 전 공정 통합 테스트',
    relatedOrders: [],
    discountRate: 5,
    discountAmount: 2250000,
    finalAmount: 42750000,
    items: [
      { id: 1, floor: '1층', location: 'F-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3500, height: 2800, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 2, wingIndex: 55, inspectionFee: 50000, unitPrice: 7000000, amount: 14000000, orderStatus: 'pending', orderId: null, process: 'screen' },
      { id: 2, floor: '2층', location: 'F-02', category: '슬랫', productName: '철재 슬랫 셔터', width: 4500, height: 3200, guideType: '코너형', motorPower: '220V', controller: '노출형', qty: 2, wingIndex: 65, inspectionFee: 60000, unitPrice: 8000000, amount: 16000000, orderStatus: 'pending', orderId: null, process: 'slat' },
      { id: 3, floor: '3층', location: 'F-03', category: '스크린', productName: '스크린 셔터 (대형)', width: 5000, height: 3500, guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 2, wingIndex: 70, inspectionFee: 70000, unitPrice: 7500000, amount: 15000000, orderStatus: 'pending', orderId: null, process: 'screen' }
    ]
  },

  // ═══════════════════════════════════════════════════════════════════════════
  // 전체 워크플로우 통합 테스트 데이터 10건 (ID: 201-210)
  // 견적 → 수주 → 생산 → 품질검사 → 출하 → 회계 전체 연동
  // ═══════════════════════════════════════════════════════════════════════════

  // [통합테스트 1] 삼성물산 - 래미안 강남 프레스티지 (A등급, 스크린 3대)
  {
    id: 201,
    quoteNo: 'KD-PR-251217-01',
    quoteDate: '2025-12-17',
    status: '수주전환',
    productName: '스크린 셔터 (표준형)',
    productCode: 'SH3025',
    qty: 3,
    totalAmount: 24000000,
    customerId: 1,  // C-001 삼성물산(주)
    customerCode: 'CUS-001',
    customerName: '삼성물산(주)',
    creditGrade: 'A',
    siteId: 1,  // S-001
    siteName: '래미안 강남 프레스티지',
    siteCode: 'S-001',
    manager: '김건설',
    contact: '010-1234-5678',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    dueDate: '2026-01-15',
    createdBy: '판매1팀 김영업',
    note: '[통합테스트1] A등급 정상 플로우 - 스크린 3대',
    relatedOrders: ['KD-TS-251217-01'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 24000000,
    items: [
      { id: 1, floor: '1층', location: 'A-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 50, inspectionFee: 50000, unitPrice: 8000000, amount: 8000000, orderStatus: 'converted', orderId: 201, process: 'screen' },
      { id: 2, floor: '2층', location: 'A-02', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 50, inspectionFee: 50000, unitPrice: 8000000, amount: 8000000, orderStatus: 'converted', orderId: 201, process: 'screen' },
      { id: 3, floor: '3층', location: 'A-03', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 50, inspectionFee: 50000, unitPrice: 8000000, amount: 8000000, orderStatus: 'converted', orderId: 201, process: 'screen' }
    ]
  },

  // [통합테스트 2] 현대건설 - 힐스테이트 판교 (A등급, 스크린+슬랫 혼합)
  {
    id: 202,
    quoteNo: 'KD-PR-251217-02',
    quoteDate: '2025-12-17',
    status: '수주전환',
    productName: '스크린/슬랫 셔터 혼합',
    productCode: 'MIX-001',
    qty: 4,
    totalAmount: 32000000,
    customerId: 2,  // C-002 현대건설(주)
    customerCode: 'CUS-002',
    customerName: '현대건설(주)',
    creditGrade: 'A',
    siteId: 11,  // S-011
    siteName: '힐스테이트 판교 더 퍼스트',
    siteCode: 'S-011',
    manager: '박현장',
    contact: '010-2345-6789',
    deliveryAddress: '경기도 성남시 분당구 판교로 200',
    dueDate: '2026-01-20',
    createdBy: '판매1팀 이영업',
    note: '[통합테스트2] 스크린+슬랫 혼합 공정 분리 테스트',
    relatedOrders: ['KD-TS-251217-02'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 32000000,
    items: [
      { id: 1, floor: 'B1', location: 'B-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 4000, height: 3000, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 2, wingIndex: 60, inspectionFee: 50000, unitPrice: 9000000, amount: 18000000, orderStatus: 'converted', orderId: 202, process: 'screen' },
      { id: 2, floor: '1층', location: 'B-02', category: '슬랫', productName: '철재 슬랫 셔터', width: 3500, height: 2500, guideType: '벽면형', motorPower: '220V', controller: '노출형', qty: 2, wingIndex: 55, inspectionFee: 50000, unitPrice: 7000000, amount: 14000000, orderStatus: 'converted', orderId: 202, process: 'slat' }
    ]
  },

  // [통합테스트 3] 대우건설 - 푸르지오 일산 (A등급, 대형 스크린)
  {
    id: 203,
    quoteNo: 'KD-PR-251217-03',
    quoteDate: '2025-12-17',
    status: '수주전환',
    productName: '스크린 셔터 (대형)',
    productCode: 'SH6040',
    qty: 2,
    totalAmount: 28000000,
    customerId: 3,  // C-003 대우건설(주)
    customerCode: 'CUS-003',
    customerName: '대우건설(주)',
    creditGrade: 'A',
    siteId: 21,  // S-021
    siteName: '푸르지오 일산 센트럴파크',
    siteCode: 'S-021',
    manager: '최건설',
    contact: '010-3456-7890',
    deliveryAddress: '경기도 고양시 일산동구 마두동 500',
    dueDate: '2026-01-25',
    createdBy: '판매2팀 박영업',
    note: '[통합테스트3] 대형 스크린(6m×4m) 모터용량 500KG 테스트',
    relatedOrders: ['KD-TS-251217-03'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 28000000,
    items: [
      { id: 1, floor: '로비', location: 'C-01', category: '스크린', productName: '스크린 셔터 (대형)', width: 6000, height: 4000, guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, wingIndex: 80, inspectionFee: 80000, unitPrice: 14000000, amount: 14000000, orderStatus: 'converted', orderId: 203, process: 'screen' },
      { id: 2, floor: '연회장', location: 'C-02', category: '스크린', productName: '스크린 셔터 (대형)', width: 6000, height: 4000, guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, wingIndex: 80, inspectionFee: 80000, unitPrice: 14000000, amount: 14000000, orderStatus: 'converted', orderId: 203, process: 'screen' }
    ]
  },

  // [통합테스트 4] GS건설 - 자이 위례 (A등급, 슬랫 전용)
  {
    id: 204,
    quoteNo: 'KD-PR-251217-04',
    quoteDate: '2025-12-17',
    status: '수주전환',
    productName: '철재 슬랫 셔터',
    productCode: 'ST4030',
    qty: 5,
    totalAmount: 35000000,
    customerId: 4,  // C-004 GS건설(주)
    customerCode: 'CUS-004',
    customerName: 'GS건설(주)',
    creditGrade: 'A',
    siteId: 31,  // S-031
    siteName: '자이 위례 더 퍼스트',
    siteCode: 'S-031',
    manager: '정건설',
    contact: '010-4567-8901',
    deliveryAddress: '경기도 성남시 수정구 위례동 100',
    dueDate: '2026-01-30',
    createdBy: '판매2팀 최영업',
    note: '[통합테스트4] 슬랫 전용 공정 테스트',
    relatedOrders: ['KD-TS-251217-04'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 35000000,
    items: [
      { id: 1, floor: 'B1', location: 'D-01', category: '슬랫', productName: '철재 슬랫 셔터', width: 4000, height: 3000, guideType: '벽면형', motorPower: '220V', controller: '노출형', qty: 3, wingIndex: 60, inspectionFee: 50000, unitPrice: 7000000, amount: 21000000, orderStatus: 'converted', orderId: 204, process: 'slat' },
      { id: 2, floor: '1층', location: 'D-02', category: '슬랫', productName: '철재 슬랫 셔터', width: 4000, height: 3000, guideType: '코너형', motorPower: '220V', controller: '노출형', qty: 2, wingIndex: 60, inspectionFee: 50000, unitPrice: 7000000, amount: 14000000, orderStatus: 'converted', orderId: 204, process: 'slat' }
    ]
  },

  // [통합테스트 5] 포스코건설 - 더샵 송도 (A등급, 코너형 가이드)
  {
    id: 205,
    quoteNo: 'KD-PR-251217-05',
    quoteDate: '2025-12-17',
    status: '수주전환',
    productName: '스크린 셔터 (코너형)',
    productCode: 'SH3530-C',
    qty: 3,
    totalAmount: 27000000,
    customerId: 5,  // C-005 포스코건설(주)
    customerCode: 'CUS-005',
    customerName: '포스코건설(주)',
    creditGrade: 'A',
    siteId: 41,  // S-041
    siteName: '더샵 송도 센트럴파크',
    siteCode: 'S-041',
    manager: '강건설',
    contact: '010-5678-9012',
    deliveryAddress: '인천시 연수구 송도동 200',
    dueDate: '2026-02-05',
    createdBy: '판매1팀 김영업',
    note: '[통합테스트5] 코너형 가이드레일 BOM 산출 테스트',
    relatedOrders: ['KD-TS-251217-05'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 27000000,
    items: [
      { id: 1, floor: '1층', location: 'E-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3500, height: 3000, guideType: '코너형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 60, inspectionFee: 50000, unitPrice: 9000000, amount: 9000000, orderStatus: 'converted', orderId: 205, process: 'screen' },
      { id: 2, floor: '2층', location: 'E-02', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3500, height: 3000, guideType: '코너형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 60, inspectionFee: 50000, unitPrice: 9000000, amount: 9000000, orderStatus: 'converted', orderId: 205, process: 'screen' },
      { id: 3, floor: '3층', location: 'E-03', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3500, height: 3000, guideType: '코너형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 60, inspectionFee: 50000, unitPrice: 9000000, amount: 9000000, orderStatus: 'converted', orderId: 205, process: 'screen' }
    ]
  },

  // [통합테스트 6] 롯데건설 - 캐슬 잠실 (B등급, 경리승인 필요)
  {
    id: 206,
    quoteNo: 'KD-PR-251217-06',
    quoteDate: '2025-12-17',
    status: '최종확정',
    productName: '스크린 셔터 (표준형)',
    productCode: 'SH4028',
    qty: 4,
    totalAmount: 36000000,
    customerId: 6,  // C-006 롯데건설(주)
    customerCode: 'CUS-006',
    customerName: '롯데건설(주)',
    creditGrade: 'B',
    siteId: 51,  // S-051
    siteName: '캐슬 잠실 파인시티',
    siteCode: 'S-051',
    manager: '윤건설',
    contact: '010-6789-0123',
    deliveryAddress: '서울시 송파구 잠실동 300',
    dueDate: '2026-02-10',
    createdBy: '판매2팀 이영업',
    note: '[통합테스트6] B등급 경리승인 대기 테스트',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 36000000,
    items: [
      { id: 1, floor: 'B1', location: 'F-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 4000, height: 2800, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 2, wingIndex: 55, inspectionFee: 50000, unitPrice: 9000000, amount: 18000000, orderStatus: 'pending', orderId: null, process: 'screen' },
      { id: 2, floor: '1층', location: 'F-02', category: '스크린', productName: '스크린 셔터 (표준형)', width: 4000, height: 2800, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 2, wingIndex: 55, inspectionFee: 50000, unitPrice: 9000000, amount: 18000000, orderStatus: 'pending', orderId: null, process: 'screen' }
    ]
  },

  // [통합테스트 7] 호반건설 - 써밋 광교 (A등급, 분할출하)
  {
    id: 207,
    quoteNo: 'KD-PR-251217-07',
    quoteDate: '2025-12-17',
    status: '수주전환',
    productName: '스크린/슬랫 셔터 혼합',
    productCode: 'MIX-002',
    qty: 6,
    totalAmount: 48000000,
    customerId: 7,  // C-007 호반건설(주)
    customerCode: 'CUS-007',
    customerName: '호반건설(주)',
    creditGrade: 'A',
    siteId: 61,  // S-061
    siteName: '써밋 광교 센트럴시티',
    siteCode: 'S-061',
    manager: '서건설',
    contact: '010-7890-1234',
    deliveryAddress: '경기도 수원시 영통구 광교동 400',
    dueDate: '2026-02-15',
    createdBy: '판매1팀 박영업',
    note: '[통합테스트7] 분할출하(1차/2차) 테스트',
    relatedOrders: ['KD-TS-251217-07'],
    discountRate: 5,
    discountAmount: 2400000,
    finalAmount: 45600000,
    items: [
      { id: 1, floor: 'B1', location: 'G-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3500, height: 2800, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 2, wingIndex: 55, inspectionFee: 50000, unitPrice: 8500000, amount: 17000000, orderStatus: 'converted', orderId: 207, process: 'screen' },
      { id: 2, floor: 'B2', location: 'G-02', category: '슬랫', productName: '철재 슬랫 셔터', width: 4000, height: 3000, guideType: '벽면형', motorPower: '220V', controller: '노출형', qty: 2, wingIndex: 60, inspectionFee: 50000, unitPrice: 7500000, amount: 15000000, orderStatus: 'converted', orderId: 207, process: 'slat' },
      { id: 3, floor: '1층', location: 'G-03', category: '스크린', productName: '스크린 셔터 (대형)', width: 5000, height: 3500, guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 2, wingIndex: 70, inspectionFee: 70000, unitPrice: 8000000, amount: 16000000, orderStatus: 'converted', orderId: 207, process: 'screen' }
    ]
  },

  // [통합테스트 8] 한화건설 - 포레나 수지 (A등급, 추가분 수주)
  {
    id: 208,
    quoteNo: 'KD-PR-251217-08',
    quoteDate: '2025-12-17',
    status: '수주전환',
    productName: '스크린 셔터 (표준형)',
    productCode: 'SH3025',
    qty: 2,
    totalAmount: 16000000,
    customerId: 8,  // C-008 한화건설(주)
    customerCode: 'CUS-008',
    customerName: '한화건설(주)',
    creditGrade: 'A',
    siteId: 71,  // S-071
    siteName: '포레나 수지 더 센트럴',
    siteCode: 'S-071',
    manager: '한건설',
    contact: '010-8901-2345',
    deliveryAddress: '경기도 용인시 수지구 풍덕천동 500',
    dueDate: '2026-02-20',
    createdBy: '판매2팀 최영업',
    note: '[통합테스트8] 추가분 수주(원수주 연결) 테스트',
    relatedOrders: ['KD-TS-251217-08'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 16000000,
    items: [
      { id: 1, floor: '4층', location: 'H-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 50, inspectionFee: 50000, unitPrice: 8000000, amount: 8000000, orderStatus: 'converted', orderId: 208, process: 'screen' },
      { id: 2, floor: '5층', location: 'H-02', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3000, height: 2500, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 1, wingIndex: 50, inspectionFee: 50000, unitPrice: 8000000, amount: 8000000, orderStatus: 'converted', orderId: 208, process: 'screen' }
    ]
  },

  // [통합테스트 9] 태영건설 - 데시앙 동탄 (A등급, 품질불량→재작업)
  {
    id: 209,
    quoteNo: 'KD-PR-251217-09',
    quoteDate: '2025-12-17',
    status: '수주전환',
    productName: '스크린 셔터 (프리미엄)',
    productCode: 'SH4535',
    qty: 3,
    totalAmount: 33000000,
    customerId: 9,  // C-009 태영건설(주)
    customerCode: 'CUS-009',
    customerName: '태영건설(주)',
    creditGrade: 'A',
    siteId: 81,  // S-081
    siteName: '데시앙 동탄 파크뷰',
    siteCode: 'S-081',
    manager: '조건설',
    contact: '010-9012-3456',
    deliveryAddress: '경기도 화성시 동탄동 600',
    dueDate: '2026-02-25',
    createdBy: '판매1팀 김영업',
    note: '[통합테스트9] 품질불량 → 재작업 플로우 테스트',
    relatedOrders: ['KD-TS-251217-09'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 33000000,
    items: [
      { id: 1, floor: '로비', location: 'I-01', category: '스크린', productName: '스크린 셔터 (프리미엄)', width: 4500, height: 3500, guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, wingIndex: 70, inspectionFee: 60000, unitPrice: 11000000, amount: 11000000, orderStatus: 'converted', orderId: 209, process: 'screen' },
      { id: 2, floor: '카페', location: 'I-02', category: '스크린', productName: '스크린 셔터 (프리미엄)', width: 4500, height: 3500, guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, wingIndex: 70, inspectionFee: 60000, unitPrice: 11000000, amount: 11000000, orderStatus: 'converted', orderId: 209, process: 'screen' },
      { id: 3, floor: '헬스장', location: 'I-03', category: '스크린', productName: '스크린 셔터 (프리미엄)', width: 4500, height: 3500, guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, wingIndex: 70, inspectionFee: 60000, unitPrice: 11000000, amount: 11000000, orderStatus: 'converted', orderId: 209, process: 'screen' }
    ]
  },

  // [통합테스트 10] 두산건설 - 위브 청라 (A등급, 전체 완료 시나리오)
  {
    id: 210,
    quoteNo: 'KD-PR-251217-10',
    quoteDate: '2025-12-17',
    status: '수주전환',
    productName: '스크린/슬랫 셔터 혼합',
    productCode: 'MIX-003',
    qty: 5,
    totalAmount: 40000000,
    customerId: 10,  // C-010 두산건설(주)
    customerCode: 'CUS-010',
    customerName: '두산건설(주)',
    creditGrade: 'A',
    siteId: 91,  // S-091
    siteName: '위브 청라 더 퍼스트',
    siteCode: 'S-091',
    manager: '임건설',
    contact: '010-0123-4567',
    deliveryAddress: '인천시 서구 청라동 700',
    dueDate: '2026-03-01',
    createdBy: '판매2팀 이영업',
    note: '[통합테스트10] 전체 완료 시나리오 (견적→수주→생산→품질→출하→회계)',
    relatedOrders: ['KD-TS-251217-10'],
    discountRate: 3,
    discountAmount: 1200000,
    finalAmount: 38800000,
    items: [
      { id: 1, floor: 'B1', location: 'J-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 3500, height: 2800, guideType: '벽면형', motorPower: '220V', controller: '매립형', qty: 2, wingIndex: 55, inspectionFee: 50000, unitPrice: 8500000, amount: 17000000, orderStatus: 'converted', orderId: 210, process: 'screen' },
      { id: 2, floor: '1층', location: 'J-02', category: '슬랫', productName: '철재 슬랫 셔터', width: 4000, height: 3000, guideType: '벽면형', motorPower: '220V', controller: '노출형', qty: 2, wingIndex: 60, inspectionFee: 50000, unitPrice: 7000000, amount: 14000000, orderStatus: 'converted', orderId: 210, process: 'slat' },
      { id: 3, floor: '2층', location: 'J-03', category: '스크린', productName: '스크린 셔터 (대형)', width: 5000, height: 3500, guideType: '벽면형', motorPower: '380V', controller: '매립형', qty: 1, wingIndex: 70, inspectionFee: 70000, unitPrice: 9000000, amount: 9000000, orderStatus: 'converted', orderId: 210, process: 'screen' }
    ]
  },
];

// ============ 거래처 관리 ============

// 신용등급 배지 컴포넌트
const CreditGradeBadge = ({ grade, showLabel = true }) => {
  const colors = {
    'A': 'bg-green-100 text-green-700 border-green-200',
    'B': 'bg-yellow-100 text-yellow-700 border-yellow-200',
    'C': 'bg-red-100 text-red-700 border-red-200',
  };
  const labels = { 'A': '우량', 'B': '관리', 'C': '위험' };
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded border text-xs font-medium ${colors[grade] || 'bg-gray-100 text-gray-700 border-gray-200'}`}>
      {grade}{showLabel && labels[grade] ? ` (${labels[grade]})` : ''}
    </span>
  );
};

// ============ 공정관리 ============
const ProcessList = ({ processes = sampleProcesses, onNavigate }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [processList, setProcessList] = useState(processes);

  const tabs = [
    { id: 'all', label: '전체', count: processList.length },
    { id: 'active', label: '사용중', count: processList.filter(p => p.isActive).length },
    { id: 'inactive', label: '미사용', count: processList.filter(p => !p.isActive).length },
  ];

  const filtered = processList
    .filter(p => activeTab === 'all' || (activeTab === 'active' ? p.isActive : !p.isActive))
    .filter(p =>
      p.processCode.toLowerCase().includes(search.toLowerCase()) ||
      p.processName.toLowerCase().includes(search.toLowerCase()) ||
      p.department.toLowerCase().includes(search.toLowerCase())
    )
    .sort((a, b) => b.id - a.id);

  // 목록 선택 훅
  const { selectedIds, handleSelect, handleSelectAll, isAllSelected, hasSelection, isMultiSelect, isSelected } = useListSelection(filtered);

  const handleCreate = () => {
    onNavigate('process-create');
  };

  const handleEdit = (process) => {
    onNavigate('process-edit', process);
  };

  const handleView = (process) => {
    onNavigate('process-detail', process);
  };

  const handleDelete = (process) => {
    if (window.confirm(`${process.processName} 공정을 삭제하시겠습니까?`)) {
      setProcessList(prev => prev.filter(p => p.id !== process.id));
    }
  };

  const handleBulkDelete = () => {
    if (window.confirm(`선택한 ${selectedIds.length}건을 삭제하시겠습니까?`)) {
      setProcessList(prev => prev.filter(p => !selectedIds.includes(p.id)));
    }
  };

  const handleToggleActive = (process) => {
    setProcessList(prev => prev.map(p =>
      p.id === process.id ? { ...p, isActive: !p.isActive, updatedAt: new Date().toISOString().split('T')[0] } : p
    ));
  };

  return (
    <div className="space-y-4">
      {/* 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <GitBranch className="w-6 h-6 text-blue-500" />
          공정 목록
        </h1>
        <div className="flex items-center justify-end gap-2">
          {isMultiSelect && (
            <Button variant="danger" onClick={handleBulkDelete}>
              <Trash2 className="w-4 h-4" /> 선택 삭제 ({selectedIds.length})
            </Button>
          )}
          <Button variant="primary" onClick={handleCreate}>
            <Plus className="w-4 h-4" /> 공정 등록
          </Button>
        </div>
      </div>

      {/* 탭 + 검색 */}
      <Card>
        <div className="flex items-center justify-between mb-4">
          <div className="flex gap-1">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${activeTab === tab.id
                    ? 'bg-blue-100 text-blue-700'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'
                  }`}
              >
                {tab.label} ({tab.count})
              </button>
            ))}
          </div>
          <SearchInput
            value={search}
            onChange={setSearch}
            placeholder="공정코드, 공정명, 담당부서 검색..."
            className="w-64"
          />
        </div>

        {/* 목록 테이블 */}
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-center w-10">
                  <input type="checkbox" checked={isAllSelected} onChange={handleSelectAll} className="rounded" />
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600">공정코드</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600">공정명</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600">구분</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600">담당부서</th>
                <th className="px-4 py-3 text-center text-xs font-semibold text-gray-600">분류규칙</th>
                <th className="px-4 py-3 text-center text-xs font-semibold text-gray-600">인원</th>
                <th className="px-4 py-3 text-center text-xs font-semibold text-gray-600">상태</th>
                {hasSelection && <th className="px-4 py-3 text-center text-xs font-semibold text-gray-600">작업</th>}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {filtered.map((process) => (
                <tr key={process.id} className={`hover:bg-gray-50 ${isSelected(process.id) ? 'bg-blue-50' : ''}`}>
                  <td className="px-4 py-3 text-center">
                    <input type="checkbox" checked={isSelected(process.id)} onChange={() => handleSelect(process.id)} className="rounded" />
                  </td>
                  <td className="px-4 py-3">
                    <button onClick={() => handleView(process)} className="font-mono text-blue-600 font-medium hover:underline">
                      {process.processCode}
                    </button>
                  </td>
                  <td className="px-4 py-3">
                    <button onClick={() => handleView(process)} className="text-left w-full">
                      <div className="font-medium text-gray-900 hover:text-blue-600">{process.processName}</div>
                      <div className="text-xs text-gray-500">{process.description}</div>
                    </button>
                  </td>
                  <td className="px-4 py-3">
                    <StatusBadge status={process.processType} />
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-700">{process.department}</td>
                  <td className="px-4 py-3 text-center">
                    {(process.autoClassifyRules?.length || 0) > 0 ? (
                      <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-purple-100 text-purple-700 rounded-full text-xs font-medium">
                        <GitBranch className="w-3 h-3" />
                        {process.autoClassifyRules.length}개
                      </span>
                    ) : (
                      <span className="text-gray-400 text-xs">-</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-center text-sm">{process.personnel || process.requiredWorkers || 1}명</td>
                  <td className="px-4 py-3 text-center">
                    <button
                      onClick={() => handleToggleActive(process)}
                      className={`px-2 py-1 rounded text-xs font-medium ${process.isActive
                          ? 'bg-green-100 text-green-700'
                          : 'bg-gray-100 text-gray-500'
                        }`}
                    >
                      {process.isActive ? '사용중' : '미사용'}
                    </button>
                  </td>
                  {hasSelection && (
                    <td className="px-4 py-3 text-center">
                      {isSelected(process.id) && (
                        <div className="flex items-center justify-center gap-1">
                          <button onClick={() => handleEdit(process)} className="p-1 hover:bg-gray-200 rounded" title="수정">
                            <Edit2 className="w-4 h-4 text-blue-600" />
                          </button>
                          <button onClick={() => handleDelete(process)} className="p-1 hover:bg-gray-200 rounded" title="삭제">
                            <Trash2 className="w-4 h-4 text-red-600" />
                          </button>
                        </div>
                      )}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {filtered.length === 0 && (
          <div className="text-center py-12 text-gray-500">
            검색 결과가 없습니다
          </div>
        )}
      </Card>
    </div>
  );
};

// 공정 등록/수정 폼
const ProcessForm = ({ process, onSave, onBack }) => {
  // 부서 목록
  const departments = [
    { code: 'SCREEN', name: '스크린생산부서' },
    { code: 'FOLD', name: '절곡생산부서' },
    { code: 'SLAT', name: '슬랫생산부서' },
    { code: 'QC', name: '품질관리부서' },
    { code: 'PACK', name: '포장/출하부서' },
  ];

  // 작업일지 양식 목록 (문서양식관리에서 가져옴)
  const workSheetTemplates = (documentTemplateConfig.documentTypes || [])
    .filter(doc => doc.code && doc.code.startsWith('WL-') && doc.isActive)
    .map(doc => ({ code: doc.code, name: doc.name, description: doc.description }));

  // 자동 분류 규칙용 조건 옵션
  const ruleConditionFields = [
    { value: 'itemName', label: '품목명' },
    { value: 'itemCode', label: '품목코드' },
    { value: 'category', label: '품목분류' },
    { value: 'material', label: '원자재' },
    { value: 'size', label: '규격' },
  ];

  const ruleConditionOperators = [
    { value: 'startsWith', label: '~로 시작' },
    { value: 'endsWith', label: '~로 끝남' },
    { value: 'contains', label: '~를 포함' },
    { value: 'equals', label: '정확히 일치' },
  ];

  // 등록 방식 (패턴 규칙 vs 개별 품목)
  const registrationMethods = [
    { value: 'pattern', label: '패턴 규칙 (코드/명칭 기반 자동 분류)' },
    { value: 'individual', label: '개별 품목 (특정 품목 직접 지정)' },
  ];

  // 규칙 유형 (품목코드 또는 품목명)
  const ruleTypes = [
    { value: 'itemCode', label: '품목코드' },
    { value: 'itemName', label: '품목명' },
  ];

  const [formData, setFormData] = useState({
    processName: process?.processName || '',
    processType: process?.processType || '생산',
    department: process?.department || '',
    workSheetType: process?.workSheetType || '',
    isActive: process?.isActive ?? true,
    workSteps: process?.workSteps?.join(', ') || '',
    // 작업 정보
    requiredWorkers: process?.requiredWorkers || '1',
    equipmentInfo: process?.equipmentInfo || '',
    // 자동 분류 규칙
    autoClassifyRules: process?.autoClassifyRules || [],
    // 설명
    description: process?.description || '',
  });

  // 규칙 추가 다이얼로그 상태
  const [showRuleModal, setShowRuleModal] = useState(false);
  const [editingRule, setEditingRule] = useState(null);
  const [ruleForm, setRuleForm] = useState({
    registrationMethod: 'pattern', // 'pattern' or 'individual'
    field: 'itemCode',
    operator: 'startsWith',
    value: '',
    priority: 10,
    description: '',
    matchedItems: [], // 패턴 매칭된 품목 리스트
  });
  const [isSearching, setIsSearching] = useState(false);

  // 샘플 품목 데이터 (itemMasterConfig에서 가져옴)
  // 품목코드 규칙:
  // - 부자재/원자재/소모품: 품목명-규격
  // - 구매부품: 품목명-규격 (규격 = 전원+용량)
  // - 절곡부품: 품목코드+종류코드+모양&길이코드 (예: RM24)
  // - 제품: 품목명 = 품목코드
  const sampleItemsData = [
    // 부자재 - 규칙: 품목명-규격
    { id: 26, itemCode: '스크린원단-0.3T', itemName: '스크린원단', spec: '0.3T', itemType: '부자재' },
    { id: 27, itemCode: '스크린원단-0.5T', itemName: '스크린원단', spec: '0.5T', itemType: '부자재' },
    { id: 28, itemCode: '슬랫-75mm', itemName: '슬랫', spec: '75mm', itemType: '부자재' },
    { id: 29, itemCode: '슬랫-100mm', itemName: '슬랫', spec: '100mm', itemType: '부자재' },
    { id: 30, itemCode: '가이드레일-60×60', itemName: '가이드레일', spec: '60×60', itemType: '부자재' },
    { id: 31, itemCode: '가이드레일-80×80', itemName: '가이드레일', spec: '80×80', itemType: '부자재' },
    { id: 32, itemCode: '샤프트-4인치', itemName: '샤프트', spec: '4인치', itemType: '부자재' },
    { id: 33, itemCode: '샤프트-6인치', itemName: '샤프트', spec: '6인치', itemType: '부자재' },
    { id: 34, itemCode: '스프링-중형', itemName: '스프링', spec: '중형', itemType: '부자재' },
    { id: 35, itemCode: '체인-#35', itemName: '체인', spec: '#35', itemType: '부자재' },
    // 원자재 - 규칙: 품목명-규격
    { id: 36, itemCode: '철판-1.2T', itemName: '철판', spec: '1.2T', itemType: '원자재' },
    { id: 37, itemCode: '철판-1.6T', itemName: '철판', spec: '1.6T', itemType: '원자재' },
    { id: 38, itemCode: '아연도금강판-1.0T', itemName: '아연도금강판', spec: '1.0T', itemType: '원자재' },
    { id: 39, itemCode: '아연도금강판-1.6T', itemName: '아연도금강판', spec: '1.6T', itemType: '원자재' },
    { id: 40, itemCode: '스테인리스-1.0T', itemName: '스테인리스', spec: '1.0T', itemType: '원자재' },
    { id: 41, itemCode: '스테인리스-1.5T', itemName: '스테인리스', spec: '1.5T', itemType: '원자재' },
    { id: 42, itemCode: '알루미늄판-1.5T', itemName: '알루미늄판', spec: '1.5T', itemType: '원자재' },
    { id: 43, itemCode: '알루미늄판-2.0T', itemName: '알루미늄판', spec: '2.0T', itemType: '원자재' },
    { id: 44, itemCode: '각파이프-40×40', itemName: '각파이프', spec: '40×40', itemType: '원자재' },
    { id: 45, itemCode: '각파이프-50×50', itemName: '각파이프', spec: '50×50', itemType: '원자재' },
    // 구매부품 - 규칙: 품목명-규격 (규격 = 전원+용량, 공백제거)
    { id: 21, itemCode: '전동개폐기-220V300KG', itemName: '전동개폐기', power: '220V', capacity: '300KG', itemType: '부품', subType: '구매 부품' },
    { id: 22, itemCode: '전동개폐기-380V600KG', itemName: '전동개폐기', power: '380V', capacity: '600KG', itemType: '부품', subType: '구매 부품' },
    { id: 23, itemCode: '제어반-220V500KG', itemName: '제어반', power: '220V', capacity: '500KG', itemType: '부품', subType: '구매 부품' },
    { id: 24, itemCode: '연기감지기-220V150KG', itemName: '연기감지기', power: '220V', capacity: '150KG', itemType: '부품', subType: '구매 부품' },
    { id: 25, itemCode: '수동개폐기-220V400KG', itemName: '수동개폐기', power: '220V', capacity: '400KG', itemType: '부품', subType: '구매 부품' },
    // 조립부품 - 규칙: 품목명 설치유형-측면규격(가로)*측면규격(세로)*길이(앞2자리)
    // 예: 가이드레일 벽면형-1211*1111*24
    { id: 11, itemCode: '셔터박스 벽면형-3000*3500*30', itemName: '셔터박스', installType: '벽면형', sideWidth: '3000', sideHeight: '3500', length: '3000', itemType: '부품', subType: '조립 부품' },
    { id: 12, itemCode: '슬랫조립체 벽면형-2500*3000*24', itemName: '슬랫조립체', installType: '벽면형', sideWidth: '2500', sideHeight: '3000', length: '2438', itemType: '부품', subType: '조립 부품' },
    { id: 13, itemCode: '가이드조립체 측면형-1200*1100*30', itemName: '가이드조립체', installType: '측면형', sideWidth: '1200', sideHeight: '1100', length: '3000', itemType: '부품', subType: '조립 부품' },
    { id: 14, itemCode: '개폐기조립체 벽면형-400*350*24', itemName: '개폐기조립체', installType: '벽면형', sideWidth: '400', sideHeight: '350', length: '2438', itemType: '부품', subType: '조립 부품' },
    { id: 15, itemCode: '제어반조립체 벽면형-500*400*35', itemName: '제어반조립체', installType: '벽면형', sideWidth: '500', sideHeight: '400', length: '3500', itemType: '부품', subType: '조립 부품' },
    // 절곡부품 - 규칙: 품목코드+종류코드+모양&길이코드 (예: RM24)
    { id: 16, itemCode: 'RM24', itemName: '가이드레일(벽면형)', partType: '본체', length: '2438', itemType: '부품', subType: '절곡 부품' },
    { id: 17, itemCode: 'SM30', itemName: '가이드레일(측면형)', partType: '본체', length: '3000', itemType: '부품', subType: '절곡 부품' },
    { id: 18, itemCode: 'CB24', itemName: '케이스', partType: '후면코너부', length: '2438', itemType: '부품', subType: '절곡 부품' },
    { id: 19, itemCode: 'BE30', itemName: '하단마감재(스크린)', partType: 'EGI', length: '3000', itemType: '부품', subType: '절곡 부품' },
    { id: 20, itemCode: 'LA24', itemName: 'L-Bar', partType: '스크린용', length: '2438', itemType: '부품', subType: '절곡 부품' },
    // 제품 - 규칙: 품목명 = 품목코드
    { id: 1, itemCode: '방화셔터 W3000×H4000', itemName: '방화셔터 W3000×H4000', itemType: '제품' },
    { id: 2, itemCode: '방화셔터 W2500×H3000', itemName: '방화셔터 W2500×H3000', itemType: '제품' },
    { id: 3, itemCode: '방연셔터 W3500×H4000', itemName: '방연셔터 W3500×H4000', itemType: '제품' },
    { id: 4, itemCode: '스틸셔터 W2500×H3000', itemName: '스틸셔터 W2500×H3000', itemType: '제품' },
    { id: 5, itemCode: '방화셔터 W5000×H5000', itemName: '방화셔터 W5000×H5000', itemType: '제품' },
  ];

  // 다른 공정에 이미 배정된 품목 ID 목록 계산 (현재 공정 제외)
  const getAssignedItemIds = () => {
    const assignedIds = new Set();
    // sampleProcesses에서 현재 공정이 아닌 모든 공정의 배정된 품목 수집
    sampleProcesses.forEach(proc => {
      if (proc.id !== process?.id && proc.autoClassifyRules) {
        proc.autoClassifyRules.forEach(rule => {
          if (rule.matchedItems) {
            rule.matchedItems.forEach(item => assignedIds.add(item.id));
          }
          // savedItems도 확인 (선별 저장된 품목)
          if (rule.savedItems) {
            rule.savedItems.forEach(item => assignedIds.add(item.id));
          }
        });
      }
      // 공정에 직접 배정된 품목도 확인
      if (proc.id !== process?.id && proc.assignedItems) {
        proc.assignedItems.forEach(item => assignedIds.add(item.id));
      }
    });
    return assignedIds;
  };

  // 선별된 품목 상태 (체크박스로 선택)
  const [selectedItemIds, setSelectedItemIds] = useState(new Set());
  // 이미 다른 공정에 배정된 품목 표시 여부
  const [showAssignedWarning, setShowAssignedWarning] = useState(false);
  // 개별 품목 선택 모드용 검색어
  const [individualSearchTerm, setIndividualSearchTerm] = useState('');
  // 개별 품목 선택 모드용 품목 유형 필터
  const [individualTypeFilter, setIndividualTypeFilter] = useState('all');

  // 패턴 매칭으로 품목 검색 (다른 공정에 배정된 품목 제외)
  const searchMatchingItems = () => {
    if (!ruleForm.value.trim()) {
      alert('조건 값을 입력해주세요.');
      return;
    }

    setIsSearching(true);

    // 다른 공정에 이미 배정된 품목 ID 집합
    const assignedIds = getAssignedItemIds();

    // 패턴 매칭 로직
    const searchValue = ruleForm.value.toLowerCase();
    const fieldKey = ruleForm.field === 'itemCode' ? 'itemCode' : 'itemName';

    // 전체 매칭된 품목
    const allMatchedItems = sampleItemsData.filter(item => {
      const fieldValue = (item[fieldKey] || '').toLowerCase();

      switch (ruleForm.operator) {
        case 'startsWith':
          return fieldValue.startsWith(searchValue);
        case 'endsWith':
          return fieldValue.endsWith(searchValue);
        case 'contains':
          return fieldValue.includes(searchValue);
        case 'equals':
          return fieldValue === searchValue;
        default:
          return false;
      }
    });

    // 다른 공정에 배정된 품목은 제외하고, isAssigned 플래그 추가
    const matchedItems = allMatchedItems
      .filter(item => !assignedIds.has(item.id))  // 다른 공정에 배정된 품목 제외
      .map(item => ({
        ...item,
        isAssigned: false,
      }));

    // 제외된 품목이 있으면 경고 표시
    const excludedCount = allMatchedItems.length - matchedItems.length;
    if (excludedCount > 0) {
      setShowAssignedWarning(true);
    } else {
      setShowAssignedWarning(false);
    }

    // 검색 결과가 있으면 모두 선택 상태로 초기화
    setSelectedItemIds(new Set(matchedItems.map(item => item.id)));

    setRuleForm(prev => ({ ...prev, matchedItems, excludedCount }));
    setIsSearching(false);
  };

  // 규칙 추가 다이얼로그 열기
  const openRuleModal = (rule = null) => {
    if (rule) {
      setEditingRule(rule);
      setRuleForm({
        registrationMethod: rule.registrationMethod || 'pattern',
        field: rule.field || 'itemCode',
        operator: rule.operator || 'startsWith',
        value: rule.value || '',
        priority: rule.priority || 10,
        description: rule.description || '',
        matchedItems: rule.matchedItems || [],
      });
      // 개별 품목 선택 모드인 경우 기존 선택된 품목 로드
      if (rule.registrationMethod === 'individual' && rule.savedItems) {
        setSelectedItemIds(new Set(rule.savedItems.map(item => item.id)));
      } else if (rule.matchedItems) {
        // 패턴 규칙 모드인 경우 매칭된 품목 로드
        setSelectedItemIds(new Set(rule.savedItems?.map(item => item.id) || rule.matchedItems.map(item => item.id)));
      } else {
        setSelectedItemIds(new Set());
      }
      // 개별 품목 검색/필터 초기화
      setIndividualSearchTerm('');
      setIndividualTypeFilter('all');
    } else {
      setEditingRule(null);
      setRuleForm({
        registrationMethod: 'pattern',
        field: 'itemCode',
        operator: 'startsWith',
        value: '',
        priority: 10,
        description: '',
        matchedItems: [],
      });
      setSelectedItemIds(new Set());
      setIndividualSearchTerm('');
      setIndividualTypeFilter('all');
    }
    setShowRuleModal(true);
  };

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

  // 전체 선택/해제
  const toggleSelectAll = () => {
    if (selectedItemIds.size === ruleForm.matchedItems.length) {
      // 전체 해제
      setSelectedItemIds(new Set());
    } else {
      // 전체 선택
      setSelectedItemIds(new Set(ruleForm.matchedItems.map(item => item.id)));
    }
  };

  // 개별 품목 선택 모드: 필터링된 품목 리스트
  const getFilteredItemsForIndividual = () => {
    const assignedIds = getAssignedItemIds();

    return sampleItemsData
      .filter(item => !assignedIds.has(item.id)) // 다른 공정에 배정된 품목 제외
      .filter(item => {
        // 품목 유형 필터
        if (individualTypeFilter !== 'all' && item.itemType !== individualTypeFilter) {
          return false;
        }
        // 검색어 필터
        if (individualSearchTerm) {
          const searchLower = individualSearchTerm.toLowerCase();
          return (
            item.itemCode.toLowerCase().includes(searchLower) ||
            item.itemName.toLowerCase().includes(searchLower)
          );
        }
        return true;
      });
  };

  // 개별 품목 선택 모드: 전체 선택/해제
  const toggleSelectAllIndividual = () => {
    const filteredItems = getFilteredItemsForIndividual();
    if (selectedItemIds.size === filteredItems.length && filteredItems.length > 0) {
      // 전체 해제
      setSelectedItemIds(new Set());
    } else {
      // 전체 선택
      setSelectedItemIds(new Set(filteredItems.map(item => item.id)));
    }
  };

  // 품목 유형 목록
  const itemTypes = ['제품', '부품', '부자재', '원자재'];

  // 규칙 저장 (선별된 품목만 저장)
  const saveRule = () => {
    // 개별 품목 선택 모드인 경우
    if (ruleForm.registrationMethod === 'individual') {
      if (selectedItemIds.size === 0) {
        alert('최소 1개 이상의 품목을 선택해주세요.');
        return;
      }

      // 선택된 품목 정보 가져오기
      const selectedItems = sampleItemsData.filter(item => selectedItemIds.has(item.id));

      const ruleData = {
        id: editingRule?.id || Date.now(),
        registrationMethod: 'individual',
        field: 'individual',
        operator: 'manual',
        value: `개별 품목 ${selectedItems.length}개 선택`,
        priority: ruleForm.priority,
        description: ruleForm.description || `직접 선택한 품목 ${selectedItems.length}개`,
        // 선별된 품목 저장
        savedItems: selectedItems.map(item => ({
          id: item.id,
          itemCode: item.itemCode,
          itemName: item.itemName,
          itemType: item.itemType,
        })),
        matchedItems: selectedItems.map(item => ({
          id: item.id,
          itemCode: item.itemCode,
          itemName: item.itemName,
          itemType: item.itemType,
        })),
        savedCount: selectedItems.length,
        matchedCount: selectedItems.length,
        createdAt: editingRule?.createdAt || new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      if (editingRule) {
        setFormData(prev => ({
          ...prev,
          autoClassifyRules: prev.autoClassifyRules.map(r =>
            r.id === editingRule.id ? ruleData : r
          )
        }));
      } else {
        setFormData(prev => ({
          ...prev,
          autoClassifyRules: [...prev.autoClassifyRules, ruleData]
        }));
      }
      setShowRuleModal(false);
      setEditingRule(null);
      setSelectedItemIds(new Set());
      setIndividualSearchTerm('');
      setIndividualTypeFilter('all');
      setRuleForm({
        registrationMethod: 'pattern',
        field: 'itemCode',
        operator: 'startsWith',
        value: '',
        priority: 10,
        description: '',
        matchedItems: [],
      });
      return;
    }

    // 패턴 규칙 모드
    if (!ruleForm.value.trim()) {
      alert('조건 값을 입력해주세요.');
      return;
    }

    // 선별된 품목만 필터링
    const selectedItems = ruleForm.matchedItems.filter(item => selectedItemIds.has(item.id));

    // 패턴 규칙인 경우 선별된 품목이 없으면 경고
    if (selectedItems.length === 0) {
      if (!confirm('선택된 품목이 없습니다. 그래도 규칙을 저장하시겠습니까?')) {
        return;
      }
    }

    const ruleData = {
      id: editingRule?.id || Date.now(),
      registrationMethod: ruleForm.registrationMethod,
      field: ruleForm.field,
      operator: ruleForm.operator,
      value: ruleForm.value,
      priority: ruleForm.priority,
      description: ruleForm.description,
      // 선별된 품목만 savedItems로 저장
      savedItems: selectedItems.map(item => ({
        id: item.id,
        itemCode: item.itemCode,
        itemName: item.itemName,
        itemType: item.itemType,
      })),
      // 전체 매칭된 품목도 참조용으로 저장
      matchedItems: ruleForm.matchedItems.map(item => ({
        id: item.id,
        itemCode: item.itemCode,
        itemName: item.itemName,
        itemType: item.itemType,
      })),
      savedCount: selectedItems.length,
      matchedCount: ruleForm.matchedItems.length,
      createdAt: editingRule?.createdAt || new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };

    if (editingRule) {
      // 수정
      setFormData(prev => ({
        ...prev,
        autoClassifyRules: prev.autoClassifyRules.map(r =>
          r.id === editingRule.id ? ruleData : r
        )
      }));
    } else {
      // 추가
      setFormData(prev => ({
        ...prev,
        autoClassifyRules: [...prev.autoClassifyRules, ruleData]
      }));
    }
    setShowRuleModal(false);
    setEditingRule(null);
    setRuleForm({
      registrationMethod: 'pattern',
      field: 'itemCode',
      operator: 'startsWith',
      value: '',
      priority: 10,
      description: '',
      matchedItems: [],
    });
  };

  // 규칙 삭제
  const removeRule = (ruleId) => {
    setFormData(prev => ({
      ...prev,
      autoClassifyRules: prev.autoClassifyRules.filter(r => r.id !== ruleId)
    }));
  };

  const handleSubmit = () => {
    if (!formData.processName || !formData.department) {
      alert('공정명, 담당부서는 필수입니다.');
      return;
    }
    onSave({
      ...formData,
      workSteps: formData.workSteps.split(',').map(s => s.trim()).filter(s => s),
    });
  };

  return (
    <div className="space-y-4">
      {/* 상단 헤더 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="flex items-center justify-between px-6 py-4">
          <h1 className="text-xl font-bold text-gray-900">{process ? '공정 수정' : '공정 등록'}</h1>
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={onBack}>
              <X className="w-4 h-4" /> 취소
            </Button>
            <Button variant="primary" onClick={handleSubmit}>
              <Save className="w-4 h-4" /> {process ? '수정' : '등록'}
            </Button>
          </div>
        </div>
      </div>

      {/* 기본 정보 섹션 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="px-6 py-3 bg-gray-50 border-b">
          <h3 className="text-sm font-semibold text-gray-700">기본 정보</h3>
        </div>
        <div className="p-6">
          <div className="grid grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">공정명 <span className="text-red-500">*</span></label>
              <input
                type="text"
                value={formData.processName}
                onChange={(e) => setFormData(prev => ({ ...prev, processName: e.target.value }))}
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="예: 스크린"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">공정구분</label>
              <select
                value={formData.processType}
                onChange={(e) => setFormData(prev => ({ ...prev, processType: e.target.value }))}
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="생산">생산</option>
                <option value="검사">검사</option>
                <option value="포장">포장</option>
                <option value="조립">조립</option>
              </select>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-6 mt-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">담당부서 <span className="text-red-500">*</span></label>
              <select
                value={formData.department}
                onChange={(e) => setFormData(prev => ({ ...prev, department: e.target.value }))}
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="">선택하세요</option>
                {departments.map(dept => (
                  <option key={dept.code} value={dept.name}>{dept.name}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">작업일지 양식</label>
              <select
                value={formData.workSheetType}
                onChange={(e) => setFormData(prev => ({ ...prev, workSheetType: e.target.value }))}
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="">선택하세요</option>
                {workSheetTemplates.map(tpl => (
                  <option key={tpl.code} value={tpl.code}>{tpl.name}</option>
                ))}
              </select>
            </div>
          </div>
        </div>
      </div>

      {/* 자동 분류 규칙 섹션 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="px-6 py-3 bg-gray-50 border-b flex items-center justify-between">
          <div>
            <h3 className="text-sm font-semibold text-gray-700">자동 분류 규칙</h3>
            <p className="text-xs text-gray-500 mt-0.5">품목이 이 공정에 이동으로 분류되는 규칙을 생성합니다.</p>
          </div>
          <button
            type="button"
            onClick={() => openRuleModal()}
            className="flex items-center gap-1 px-3 py-1.5 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
          >
            <Plus className="w-4 h-4" />
            규칙 추가
          </button>
        </div>
        <div className="p-6">
          {formData.autoClassifyRules.length === 0 ? (
            <div className="border-2 border-dashed border-gray-200 rounded-lg py-16 text-center">
              <GitBranch className="w-12 h-12 text-gray-300 mx-auto mb-3" />
              <p className="text-sm text-gray-400">품목별 규칙이 없습니다</p>
              <p className="text-xs text-gray-400 mt-1">규칙을 추가하면 해당 패턴의 품목이 이 공정으로 분류됩니다</p>
            </div>
          ) : (
            <div className="space-y-2">
              {formData.autoClassifyRules.map((rule, index) => (
                <div key={rule.id} className="p-3 bg-gray-50 rounded-lg border hover:bg-gray-100 transition-colors">
                  <div className="flex items-center gap-3">
                    <span className="text-xs text-gray-500 w-6">{index + 1}.</span>
                    <div className="flex-1">
                      {/* 개별 품목 선택 방식인 경우 */}
                      {rule.registrationMethod === 'individual' ? (
                        <div className="flex items-center gap-2 text-sm flex-wrap">
                          <span className="px-2 py-1 bg-orange-100 text-orange-700 rounded font-medium">
                            개별 품목 지정
                          </span>
                          <span className="text-gray-500">-</span>
                          <span className="px-2 py-1 bg-green-100 text-green-700 rounded font-medium">
                            {rule.savedCount || rule.matchedCount || 0}개 품목
                          </span>
                        </div>
                      ) : (
                        /* 패턴 규칙 방식인 경우 */
                        <div className="flex items-center gap-2 text-sm flex-wrap">
                          <span className="px-2 py-1 bg-blue-100 text-blue-700 rounded font-medium">
                            {ruleTypes.find(t => t.value === rule.field)?.label || rule.field}
                          </span>
                          <span className="text-gray-500">이(가)</span>
                          <span className="px-2 py-1 bg-green-100 text-green-700 rounded font-medium">
                            {rule.value}
                          </span>
                          <span className="px-2 py-1 bg-purple-100 text-purple-700 rounded font-medium">
                            {ruleConditionOperators.find(op => op.value === rule.operator)?.label || rule.operator}
                          </span>
                        </div>
                      )}
                      {/* 저장된/매칭된 품목 수 표시 */}
                      {(rule.savedCount > 0 || rule.matchedCount > 0) && (
                        <div className="mt-2 flex items-center gap-2">
                          {rule.savedCount > 0 ? (
                            <span className="px-2 py-0.5 bg-green-500 text-white text-xs rounded-full font-medium">
                              {rule.savedCount}개 품목 배정됨
                            </span>
                          ) : rule.matchedCount > 0 ? (
                            <span className="px-2 py-0.5 bg-blue-500 text-white text-xs rounded-full font-medium">
                              {rule.matchedCount}개 품목 매칭
                            </span>
                          ) : null}
                          <span className="text-xs text-gray-500">
                            우선순위: {rule.priority || 10}
                          </span>
                        </div>
                      )}
                      {rule.description && (
                        <p className="text-xs text-gray-500 mt-1">{rule.description}</p>
                      )}
                    </div>
                    <div className="flex items-center gap-1">
                      <button
                        type="button"
                        onClick={() => openRuleModal(rule)}
                        className="p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded"
                        title="수정"
                      >
                        <Edit className="w-4 h-4" />
                      </button>
                      <button
                        type="button"
                        onClick={() => removeRule(rule.id)}
                        className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded"
                        title="삭제"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* 규칙 추가/수정 다이얼로그 */}
      {showRuleModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between px-6 py-4 border-b">
              <h3 className="text-lg font-bold text-gray-900">
                {editingRule ? '규칙 수정' : '규칙 추가'}
              </h3>
              <button
                onClick={() => setShowRuleModal(false)}
                className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-6 space-y-4 overflow-y-auto flex-1">
              {/* 등록 방식 선택 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">등록 방식 <span className="text-red-500">*</span></label>
                <div className="space-y-2">
                  {registrationMethods.map(method => (
                    <label key={method.value} className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="radio"
                        name="registrationMethod"
                        value={method.value}
                        checked={ruleForm.registrationMethod === method.value}
                        onChange={(e) => setRuleForm(prev => ({ ...prev, registrationMethod: e.target.value, matchedItems: [] }))}
                        className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="text-sm text-gray-700">{method.label}</span>
                    </label>
                  ))}
                </div>
              </div>

              {/* 패턴 규칙 모드일 때만 표시 */}
              {ruleForm.registrationMethod === 'pattern' && (
                <>
                  {/* 규칙 유형 선택 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">규칙 유형 <span className="text-red-500">*</span></label>
                    <select
                      value={ruleForm.field}
                      onChange={(e) => setRuleForm(prev => ({ ...prev, field: e.target.value, matchedItems: [] }))}
                      className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    >
                      {ruleTypes.map(type => (
                        <option key={type.value} value={type.value}>{type.label}</option>
                      ))}
                    </select>
                  </div>

                  {/* 매칭 방식 선택 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">매칭 방식 <span className="text-red-500">*</span></label>
                    <select
                      value={ruleForm.operator}
                      onChange={(e) => setRuleForm(prev => ({ ...prev, operator: e.target.value, matchedItems: [] }))}
                      className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    >
                      {ruleConditionOperators.map(op => (
                        <option key={op.value} value={op.value}>{op.label}</option>
                      ))}
                    </select>
                  </div>

                  {/* 조건 값 입력 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">조건 값 <span className="text-red-500">*</span></label>
                    <div className="flex gap-2">
                      <input
                        type="text"
                        value={ruleForm.value}
                        onChange={(e) => setRuleForm(prev => ({ ...prev, value: e.target.value, matchedItems: [] }))}
                        onKeyDown={(e) => e.key === 'Enter' && searchMatchingItems()}
                        className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        placeholder={ruleForm.field === 'itemCode' ? '예: SCR-, E-, STEEL-' : '예: 스크린, 개폐기'}
                      />
                      <button
                        type="button"
                        onClick={searchMatchingItems}
                        disabled={isSearching || !ruleForm.value.trim()}
                        className="px-4 py-2 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600 disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-1"
                      >
                        <Search className="w-4 h-4" />
                        {isSearching ? '검색 중...' : '검색'}
                      </button>
                    </div>
                    <p className="text-xs text-gray-500 mt-1">Enter 키를 누르거나 검색 버튼을 클릭하세요</p>
                  </div>

                  {/* 우선순위 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">우선순위</label>
                    <input
                      type="number"
                      value={ruleForm.priority}
                      onChange={(e) => setRuleForm(prev => ({ ...prev, priority: parseInt(e.target.value) || 10 }))}
                      className="w-32 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      min="1"
                      max="100"
                    />
                    <p className="text-xs text-blue-500 mt-1">낮을수록 먼저 적용됩니다</p>
                  </div>

                  {/* 설명 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">설명</label>
                    <input
                      type="text"
                      value={ruleForm.description}
                      onChange={(e) => setRuleForm(prev => ({ ...prev, description: e.target.value }))}
                      className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      placeholder="규칙에 대한 설명"
                    />
                  </div>

                  {/* 활성 상태 */}
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-700">활성 상태</span>
                    <button
                      type="button"
                      onClick={() => setRuleForm(prev => ({ ...prev, isActive: !prev.isActive }))}
                      className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${ruleForm.isActive !== false ? 'bg-blue-500' : 'bg-gray-300'
                        }`}
                    >
                      <span
                        className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${ruleForm.isActive !== false ? 'translate-x-6' : 'translate-x-1'
                          }`}
                      />
                    </button>
                  </div>

                  {/* 다른 공정 배정 품목 제외 경고 */}
                  {showAssignedWarning && ruleForm.excludedCount > 0 && (
                    <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 flex items-start gap-2">
                      <AlertTriangle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
                      <div>
                        <p className="text-sm font-medium text-amber-800">
                          {ruleForm.excludedCount}개 품목이 다른 공정에 이미 배정되어 제외되었습니다
                        </p>
                        <p className="text-xs text-amber-600 mt-1">
                          하나의 품목은 하나의 공정에만 배정할 수 있습니다.
                        </p>
                      </div>
                    </div>
                  )}

                  {/* 매칭된 품목 리스트 (선별 가능) */}
                  {ruleForm.matchedItems.length > 0 && (
                    <div className="border rounded-lg overflow-hidden">
                      <div className="bg-green-50 px-4 py-2 border-b flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <CheckCircle className="w-4 h-4 text-green-600" />
                          <span className="text-sm font-medium text-green-800">
                            매칭된 품목 ({ruleForm.matchedItems.length}개) | 선택됨 ({selectedItemIds.size}개)
                          </span>
                        </div>
                        <div className="flex items-center gap-2">
                          <button
                            type="button"
                            onClick={toggleSelectAll}
                            className="text-xs text-blue-600 hover:text-blue-800 font-medium"
                          >
                            {selectedItemIds.size === ruleForm.matchedItems.length ? '전체 해제' : '전체 선택'}
                          </button>
                          <span className="text-gray-300">|</span>
                          <button
                            type="button"
                            onClick={() => {
                              setRuleForm(prev => ({ ...prev, matchedItems: [], excludedCount: 0 }));
                              setSelectedItemIds(new Set());
                              setShowAssignedWarning(false);
                            }}
                            className="text-xs text-gray-500 hover:text-red-500"
                          >
                            초기화
                          </button>
                        </div>
                      </div>
                      <div className="max-h-48 overflow-y-auto">
                        <table className="w-full text-sm">
                          <thead className="bg-gray-50 sticky top-0">
                            <tr>
                              <th className="px-3 py-2 text-center w-10">
                                <input
                                  type="checkbox"
                                  checked={selectedItemIds.size === ruleForm.matchedItems.length && ruleForm.matchedItems.length > 0}
                                  onChange={toggleSelectAll}
                                  className="rounded"
                                />
                              </th>
                              <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">품목코드</th>
                              <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">품목명</th>
                              <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">품목유형</th>
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-gray-100">
                            {ruleForm.matchedItems.map(item => (
                              <tr
                                key={item.id}
                                className={`hover:bg-gray-50 cursor-pointer ${selectedItemIds.has(item.id) ? 'bg-blue-50' : ''}`}
                                onClick={() => toggleItemSelection(item.id)}
                              >
                                <td className="px-3 py-2 text-center" onClick={(e) => e.stopPropagation()}>
                                  <input
                                    type="checkbox"
                                    checked={selectedItemIds.has(item.id)}
                                    onChange={() => toggleItemSelection(item.id)}
                                    className="rounded"
                                  />
                                </td>
                                <td className="px-3 py-2 font-mono text-blue-600">{item.itemCode}</td>
                                <td className="px-3 py-2 text-gray-900">{item.itemName}</td>
                                <td className="px-3 py-2">
                                  <span className={`px-2 py-0.5 rounded text-xs font-medium ${item.itemType === '제품' ? 'bg-blue-100 text-blue-700' :
                                      item.itemType === '부품' ? 'bg-green-100 text-green-700' :
                                        item.itemType === '부자재' ? 'bg-purple-100 text-purple-700' :
                                          item.itemType === '원자재' ? 'bg-orange-100 text-orange-700' :
                                            'bg-gray-100 text-gray-700'
                                    }`}>
                                    {item.itemType}
                                  </span>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                      <div className="bg-gray-50 px-4 py-2 border-t text-xs text-gray-600">
                        체크박스로 이 공정에 배정할 품목을 선별하세요. 선택된 품목만 저장됩니다.
                      </div>
                    </div>
                  )}

                  {/* 검색 후 결과 없음 */}
                  {ruleForm.value && ruleForm.matchedItems.length === 0 && (
                    <div className="border-2 border-dashed border-gray-200 rounded-lg p-4 text-center">
                      <Search className="w-8 h-8 text-gray-300 mx-auto mb-2" />
                      <p className="text-sm text-gray-500">매칭된 품목이 없습니다</p>
                      <p className="text-xs text-gray-400 mt-1">검색 버튼을 클릭하여 품목을 검색하세요</p>
                    </div>
                  )}
                </>
              )}

              {/* 개별 품목 선택 모드 */}
              {ruleForm.registrationMethod === 'individual' && (
                <>
                  {/* 설명 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">설명 (선택)</label>
                    <input
                      type="text"
                      value={ruleForm.description}
                      onChange={(e) => setRuleForm(prev => ({ ...prev, description: e.target.value }))}
                      className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      placeholder="이 품목 그룹에 대한 설명"
                    />
                  </div>

                  {/* 품목 검색 및 필터 */}
                  <div className="flex gap-2">
                    <div className="flex-1">
                      <label className="block text-sm font-medium text-gray-700 mb-1">품목 검색</label>
                      <div className="relative">
                        <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                        <input
                          type="text"
                          value={individualSearchTerm}
                          onChange={(e) => setIndividualSearchTerm(e.target.value)}
                          className="w-full border border-gray-300 rounded-lg pl-9 pr-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                          placeholder="품목코드 또는 품목명으로 검색..."
                        />
                      </div>
                    </div>
                    <div className="w-40">
                      <label className="block text-sm font-medium text-gray-700 mb-1">품목 유형</label>
                      <select
                        value={individualTypeFilter}
                        onChange={(e) => setIndividualTypeFilter(e.target.value)}
                        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      >
                        <option value="all">전체</option>
                        {itemTypes.map(type => (
                          <option key={type} value={type}>{type}</option>
                        ))}
                      </select>
                    </div>
                  </div>

                  {/* 품목 리스트 */}
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-blue-50 px-4 py-2 border-b flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Package className="w-4 h-4 text-blue-600" />
                        <span className="text-sm font-medium text-blue-800">
                          품목 목록 ({getFilteredItemsForIndividual().length}개) | 선택됨 ({selectedItemIds.size}개)
                        </span>
                      </div>
                      <div className="flex items-center gap-2">
                        <button
                          type="button"
                          onClick={toggleSelectAllIndividual}
                          className="text-xs text-blue-600 hover:text-blue-800 font-medium"
                        >
                          {selectedItemIds.size === getFilteredItemsForIndividual().length && getFilteredItemsForIndividual().length > 0 ? '전체 해제' : '전체 선택'}
                        </button>
                        <span className="text-gray-300">|</span>
                        <button
                          type="button"
                          onClick={() => {
                            setSelectedItemIds(new Set());
                            setIndividualSearchTerm('');
                            setIndividualTypeFilter('all');
                          }}
                          className="text-xs text-gray-500 hover:text-red-500"
                        >
                          초기화
                        </button>
                      </div>
                    </div>
                    <div className="max-h-64 overflow-y-auto">
                      <table className="w-full text-sm">
                        <thead className="bg-gray-50 sticky top-0">
                          <tr>
                            <th className="px-3 py-2 text-center w-10">
                              <input
                                type="checkbox"
                                checked={selectedItemIds.size === getFilteredItemsForIndividual().length && getFilteredItemsForIndividual().length > 0}
                                onChange={toggleSelectAllIndividual}
                                className="rounded"
                              />
                            </th>
                            <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">품목코드</th>
                            <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">품목명</th>
                            <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">품목유형</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-100">
                          {getFilteredItemsForIndividual().map(item => (
                            <tr
                              key={item.id}
                              className={`hover:bg-gray-50 cursor-pointer ${selectedItemIds.has(item.id) ? 'bg-blue-50' : ''}`}
                              onClick={() => toggleItemSelection(item.id)}
                            >
                              <td className="px-3 py-2 text-center" onClick={(e) => e.stopPropagation()}>
                                <input
                                  type="checkbox"
                                  checked={selectedItemIds.has(item.id)}
                                  onChange={() => toggleItemSelection(item.id)}
                                  className="rounded"
                                />
                              </td>
                              <td className="px-3 py-2 font-mono text-blue-600">{item.itemCode}</td>
                              <td className="px-3 py-2 text-gray-900">{item.itemName}</td>
                              <td className="px-3 py-2">
                                <span className={`px-2 py-0.5 rounded text-xs font-medium ${item.itemType === '제품' ? 'bg-blue-100 text-blue-700' :
                                    item.itemType === '부품' ? 'bg-green-100 text-green-700' :
                                      item.itemType === '부자재' ? 'bg-purple-100 text-purple-700' :
                                        item.itemType === '원자재' ? 'bg-orange-100 text-orange-700' :
                                          'bg-gray-100 text-gray-700'
                                  }`}>
                                  {item.itemType}
                                </span>
                              </td>
                            </tr>
                          ))}
                          {getFilteredItemsForIndividual().length === 0 && (
                            <tr>
                              <td colSpan="4" className="px-3 py-8 text-center text-gray-500">
                                <Package className="w-8 h-8 text-gray-300 mx-auto mb-2" />
                                <p className="text-sm">검색 결과가 없습니다</p>
                              </td>
                            </tr>
                          )}
                        </tbody>
                      </table>
                    </div>
                    <div className="bg-gray-50 px-4 py-2 border-t text-xs text-gray-600">
                      이 공정에 배정할 품목을 선택하세요. 다른 공정에 이미 배정된 품목은 표시되지 않습니다.
                    </div>
                  </div>

                  {/* 선택된 품목 요약 */}
                  {selectedItemIds.size > 0 && (
                    <div className="bg-green-50 border border-green-200 rounded-lg p-3">
                      <div className="flex items-center gap-2 mb-2">
                        <CheckCircle className="w-4 h-4 text-green-600" />
                        <span className="text-sm font-medium text-green-800">
                          선택된 품목 ({selectedItemIds.size}개)
                        </span>
                      </div>
                      <div className="flex flex-wrap gap-1">
                        {Array.from(selectedItemIds).slice(0, 10).map(id => {
                          const item = sampleItemsData.find(i => i.id === id);
                          return item ? (
                            <span
                              key={id}
                              className="inline-flex items-center gap-1 px-2 py-0.5 bg-white border border-green-200 rounded text-xs"
                            >
                              {item.itemCode}
                              <button
                                type="button"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  toggleItemSelection(id);
                                }}
                                className="text-gray-400 hover:text-red-500"
                              >
                                <X className="w-3 h-3" />
                              </button>
                            </span>
                          ) : null;
                        })}
                        {selectedItemIds.size > 10 && (
                          <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">
                            +{selectedItemIds.size - 10}개 더
                          </span>
                        )}
                      </div>
                    </div>
                  )}
                </>
              )}
            </div>
            <div className="flex justify-end gap-2 px-6 py-4 border-t bg-gray-50">
              <Button variant="outline" onClick={() => setShowRuleModal(false)}>
                취소
              </Button>
              <Button variant="primary" onClick={saveRule}>
                {editingRule ? '수정' : '추가'}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 작업 정보 섹션 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="px-6 py-3 bg-gray-50 border-b">
          <h3 className="text-sm font-semibold text-gray-700">작업 정보</h3>
        </div>
        <div className="p-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">필요인원</label>
            <input
              type="text"
              value={formData.requiredWorkers}
              onChange={(e) => setFormData(prev => ({ ...prev, requiredWorkers: e.target.value }))}
              className="w-full max-w-xs border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="1"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">설비정보</label>
            <input
              type="text"
              value={formData.equipmentInfo}
              onChange={(e) => setFormData(prev => ({ ...prev, equipmentInfo: e.target.value }))}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="예: 미싱기 3대, 절단기 1대"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">세부 작업단계 (쉼표로 구분)</label>
            <input
              type="text"
              value={formData.workSteps}
              onChange={(e) => setFormData(prev => ({ ...prev, workSteps: e.target.value }))}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="예: 원단절단, 미싱, 앤드락작업, 중간검사, 포장"
            />
          </div>
        </div>
      </div>

      {/* 설명 섹션 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="px-6 py-3 bg-gray-50 border-b">
          <h3 className="text-sm font-semibold text-gray-700">설명</h3>
        </div>
        <div className="p-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">설명</label>
            <textarea
              value={formData.description}
              onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm h-24 resize-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="공정에 대한 설명"
            />
          </div>
          <div className="flex items-center gap-2 mt-4">
            <input
              type="checkbox"
              id="isActive"
              checked={formData.isActive}
              onChange={(e) => setFormData(prev => ({ ...prev, isActive: e.target.checked }))}
              className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <label htmlFor="isActive" className="text-sm text-gray-700">사용함</label>
          </div>
        </div>
      </div>
    </div>
  );
};

// 문서양식 미리보기 모달 컴포넌트
const DocumentTemplatePreviewModal = ({ docCode, onClose }) => {
  // 문서양식 템플릿 가져오기
  const template = documentTemplateConfig.documentTemplates?.[docCode];
  const docType = (documentTemplateConfig.documentTypes || []).find(d => d.code === docCode);

  if (!template && !docType) {
    return (
      <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
        <div className="bg-white rounded-xl p-8 max-w-md text-center">
          <AlertCircle className="w-16 h-16 text-red-400 mx-auto mb-4" />
          <h3 className="text-lg font-bold mb-2">양식을 찾을 수 없습니다</h3>
          <p className="text-gray-500 mb-4">문서코드: {docCode}</p>
          <button onClick={onClose} className="px-4 py-2 bg-gray-100 rounded hover:bg-gray-200">닫기</button>
        </div>
      </div>
    );
  }

  // 블록 정보 가져오기 헬퍼
  const getBlockInfo = (blockId) => {
    const allBlocks = [
      ...(documentTemplateConfig.blockLibrary?.headers || []),
      ...(documentTemplateConfig.blockLibrary?.sections || []),
      ...(documentTemplateConfig.blockLibrary?.tables || []),
      ...(documentTemplateConfig.blockLibrary?.approvals || []),
      ...(documentTemplateConfig.blockLibrary?.footers || []),
    ];
    return allBlocks.find(b => b.id === blockId);
  };

  // 샘플 데이터 생성
  const getSampleData = (code) => {
    const samples = {
      'WL-SCR': {
        orderDate: '2025-12-17',
        siteName: '송도 오피스텔 A동',
        customerName: '(주)인천건설',
        workDate: '2025-12-17',
        managerName: '김담당',
        lotNo: 'KD-TS-251217-01-01',
        productCode: 'SH3040',
        productName: '방화셔터 W3000×H4000',
        finishType: '스크린',
        finishSpec: '그레이',
      },
      'WL-FLD': {
        orderDate: '2025-12-17',
        siteName: '강남 주상복합 B동',
        customerName: '(주)서울건설',
        workDate: '2025-12-17',
        managerName: '박담당',
        lotNo: 'KD-BD-251217-01-01',
        productCode: 'CB2430',
        productName: '커버박스 W2400×H3000',
        finishType: '절곡',
        finishSpec: 'SUS',
      },
      'WL-SLT': {
        orderDate: '2025-12-17',
        siteName: '대전 물류센터',
        customerName: '(주)중부건설',
        workDate: '2025-12-17',
        managerName: '이담당',
        lotNo: 'KD-SL-251217-01-01',
        productCode: 'SL3040',
        productName: '슬랫조립체 W3000×H4000',
        finishType: '슬랫',
        finishSpec: '백색',
      },
      'TS': {
        requestDate: '2025-12-17',
        requestCompany: '(주)인천건설',
        requestManager: '김담당',
        requestPhone: '010-1234-5678',
        siteName: '송도 오피스텔 A동',
        siteCode: 'S-001',
        deliveryDate: '2025-12-18',
        deliveryAddress: '인천시 연수구 송도동 123-45',
        deliveryPhone: '032-123-4567',
        productName: '방화셔터 W3000×H4000',
        productCode: 'SH3040',
        quantity: 5,
      },
      'IQC': {
        itemName: '전기 아연도금 강판\n(KS D 3528, SECC) "EGI 절곡판"',
        itemSpec: '1.55 * 1218 * 480',
        materialNo: 'PE02RB',
        lotSize: 200,
        supplier: '지오TNS\n(KG스틸)',
        lotNo: '250715-02',
        inspectionDate: '2025-07-15',
        inspector: '노완호',
        inboundDate: '2025-07-15',
        inspectionItems: [
          {
            no: 1,
            name: '겉모양',
            standard: '사용상 해로울\n결함이 없을 것',
            method: '육안검사',
            frequency: '',
            measurements: [{ result: 'OK' }, { result: 'OK' }, { result: 'OK' }],
            judgment: '적'
          },
          {
            no: 2,
            name: '치수',
            subItems: [
              {
                name: '두께', value: '1.55', ranges: [
                  { range: '0.8 이상 ~ 1.0 미만', tolerance: '± 0.07', checked: false },
                  { range: '1.0 이상 ~ 1.25 미만', tolerance: '± 0.08', checked: false },
                  { range: '1.25 이상 ~ 1.6 미만', tolerance: '± 0.10', checked: true },
                  { range: '1.6 이상 ~ 2.0 미만', tolerance: '± 0.12', checked: false },
                ], measurements: ['1.528', '1.533', '1.521']
              },
              {
                name: '너비', value: '1219', ranges: [
                  { range: '1250 미만', tolerance: '+7/-0', checked: true },
                ], measurements: ['1222', '1222', '1222']
              },
              {
                name: '길이', value: '480', ranges: [
                  { range: '1250 미만', tolerance: '+10/-0', checked: false },
                  { range: '2000 이상 ~ 4000 미만', tolerance: '+15/-0', checked: false },
                  { range: '4000 이상 ~ 6000 미만', tolerance: '+20/-0', checked: false },
                ], measurements: ['480', '480', '480']
              },
            ],
            method: '체크검사',
            frequency: 'n=3\nc=0',
            judgment: '적'
          },
          {
            no: 3,
            name: '인장강도 (N/mm²)',
            standard: '270 이상',
            method: '',
            frequency: '',
            measurements: ['313.8', '', ''],
            judgment: '적'
          },
          {
            no: 4,
            name: '연신율\n%',
            subItems: [
              { range: '두께 0.6 이상 ~ 1.0 미만', value: '36 이상', checked: false },
              { range: '두께 1.0 이상 ~ 1.6 미만', value: '37 이상', checked: true },
              { range: '두께 1.6 이상 ~ 2.3 미만', value: '38 이상', checked: false },
            ],
            method: '공급업체\n밀시트',
            frequency: '입고시',
            measurements: ['46.5', '', ''],
            judgment: '적'
          },
          {
            no: 5,
            name: '아연의 최소\n부착량 (g/m²)',
            standard: '한면 17 이상',
            method: '',
            frequency: '',
            measurements: ['17.21 / 17.17', '', ''],
            judgment: '적'
          },
        ],
        notes: [
          '1.55mm의 경우 KS F 4510에 따른 MIN 15의 기준에 따름',
          '두께의 경우 너비 1000 이상 ~ 1250 미만 기준에 따름',
        ],
        finalJudgment: '합격',
      },
      'PQC-SCR': {
        productName: '방화스크린(60분)',
        productSpec: 'W3000 * H4000',
        siteName: '인천 송도 오피스텔 신축공사',
        workOrderNo: 'WO-SCR-251216-01',
        deliveryDate: '2025-12-20',
        inspectionDate: '2025-12-18',
        inspector: '노완호',
        inspectionItems: [
          // 겉모양 검사
          {
            category: '겉모양',
            items: [
              { name: '가공상태', standard: '사용상 해로운 결함이 없을 것', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
              { name: '재봉상태', standard: '내화실에 의해 견고하게 접합되어야 함', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
              { name: '조립상태', standard: '앤드락이 견고하게 조립되어야 함', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
              { name: '연기차단재', standard: '연기차단재 설치여부\n(케이스 W80, 가이드레일 W50(양측설치))', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
              { name: '하단마감재', standard: '내부 무게평철 설치 유무', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
            ]
          },
          // 모터 검사
          {
            category: '모터',
            items: [
              { name: '모터', standard: '인정제품과 동일사양', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
            ]
          },
          // 재질 검사
          {
            category: '재질',
            items: [
              { name: '재질', standard: 'WY-SC780 인쇄상태 확인', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
            ]
          },
          // 치수 검사 (오픈사이즈)
          {
            category: '치수\n(오픈사이즈)',
            items: [
              { name: '가로', standard: 'W ± 10', method: '줄자', frequency: 'n=1\nc=0', measurements: ['3002', '', '', '', ''], judgment: '적', checked: true },
              { name: '세로', standard: 'H ± 10', method: '줄자', frequency: 'n=1\nc=0', measurements: ['4005', '', '', '', ''], judgment: '적', checked: true },
            ]
          },
          // 치수 검사 (케이스)
          {
            category: '치수\n(케이스)',
            items: [
              { name: '좌우길이', standard: 'W ± 3', method: '줄자', frequency: 'n=1\nc=0', measurements: ['3001', '', '', '', ''], judgment: '적', checked: true },
              { name: '폭', standard: '250 ± 5', method: '줄자', frequency: 'n=1\nc=0', measurements: ['252', '', '', '', ''], judgment: '적', checked: true },
              { name: '높이', standard: '350 ± 5', method: '줄자', frequency: 'n=1\nc=0', measurements: ['348', '', '', '', ''], judgment: '적', checked: true },
            ]
          },
          // 치수 검사 (가이드레일)
          {
            category: '치수\n(가이드레일)',
            items: [
              { name: '길이', standard: 'H ± 5', method: '줄자', frequency: 'n=1\nc=0', measurements: ['4003', '', '', '', ''], judgment: '적', checked: true },
              { name: '기능단차', standard: '10 ~ 15', method: '버니어', frequency: 'n=1\nc=0', measurements: ['12', '', '', '', ''], judgment: '적' },
            ]
          },
          // 치수 검사 (스크린)
          {
            category: '치수\n(스크린)',
            items: [
              { name: '폭', standard: 'W ± 10', method: '줄자', frequency: 'n=1\nc=0', measurements: ['2998', '', '', '', ''], judgment: '적', checked: true },
              { name: '높이', standard: 'H + 300 ± 10', method: '줄자', frequency: 'n=1\nc=0', measurements: ['4295', '', '', '', ''], judgment: '적', checked: true },
            ]
          },
          // 치수 검사 (하단마감재)
          {
            category: '치수\n(하단마감재)',
            items: [
              { name: '길이', standard: 'W - 3.5 ± 2', method: '줄자', frequency: 'n=1\nc=0', measurements: ['2996', '', '', '', ''], judgment: '적', checked: true },
            ]
          },
        ],
        defectContent: '',
        finalJudgment: '합격',
      },
      'PQC-BND': {
        productName: '절곡품 (가이드레일)',
        productSpec: 'H4000 * W50',
        siteName: '인천 송도 오피스텔 신축공사',
        workOrderNo: 'WO-FLD-251216-01',
        deliveryDate: '2025-12-20',
        inspectionDate: '2025-12-18',
        inspector: '노완호',
        inspectionItems: [
          {
            category: '겉모양',
            items: [
              { name: '절곡상태', standard: '사용상 해로운 결함이 없을 것', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
              { name: '도장상태', standard: '도장 박리, 긁힘 없을 것', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
            ]
          },
          {
            category: '치수\n(길이)',
            items: [
              { name: '길이', standard: 'H ± 4', method: '줄자', frequency: 'n=1\nc=0', measurements: ['4002', '', '', '', ''], judgment: '적', checked: true },
            ]
          },
          {
            category: '치수\n(너비)',
            items: [
              { name: 'W50', standard: '50 ± 5', method: '버니어', frequency: 'n=3\nc=0', measurements: ['50.2', '49.8', '50.1', '', ''], judgment: '적', checked: true },
              { name: 'W80', standard: '80 ± 5', method: '버니어', frequency: 'n=3\nc=0', measurements: ['', '', '', '', ''], judgment: '-' },
            ]
          },
          {
            category: '치수\n(간격)',
            items: [
              { name: '홀 간격', standard: '도면치수 ± 2', method: '버니어', frequency: 'n=3\nc=0', measurements: ['250.1', '249.9', '250.0', '', ''], judgment: '적', checked: true },
            ]
          },
        ],
        defectContent: '',
        finalJudgment: '합격',
      },
      'PQC-SLT': {
        productName: '슬랫 커튼',
        productSpec: 'W3000 * H4000',
        siteName: '인천 송도 오피스텔 신축공사',
        workOrderNo: 'WO-SLT-251216-01',
        deliveryDate: '2025-12-20',
        inspectionDate: '2025-12-18',
        inspector: '노완호',
        inspectionItems: [
          // 겉모양 검사
          {
            category: '겉모양',
            items: [
              { name: '가공상태', standard: '사용상 해로운 결함이 없을 것', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
              { name: '슬랫 연결', standard: '슬랫 간 결합이 견고할 것', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
              { name: '도장상태', standard: '도장 박리, 긁힘 없을 것', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
            ]
          },
          // 모터 검사
          {
            category: '모터',
            items: [
              { name: '모터', standard: '인정제품과 동일사양', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
            ]
          },
          // 치수 검사 (슬랫)
          {
            category: '치수\n(슬랫)',
            items: [
              { name: '폭', standard: 'W ± 5', method: '줄자', frequency: 'n=1\nc=0', measurements: ['3002', '', '', '', ''], judgment: '적', checked: true },
              { name: '슬랫 높이', standard: '110 ± 2', method: '버니어', frequency: 'n=3\nc=0', measurements: ['110.5', '110.2', '110.3', '', ''], judgment: '적', checked: true },
              { name: '슬랫 매수', standard: '도면규격', method: '계수', frequency: 'n=1\nc=0', measurements: ['36', '', '', '', ''], judgment: '적' },
            ]
          },
          // 치수 검사 (케이스)
          {
            category: '치수\n(케이스)',
            items: [
              { name: '좌우길이', standard: 'W ± 3', method: '줄자', frequency: 'n=1\nc=0', measurements: ['3001', '', '', '', ''], judgment: '적', checked: true },
              { name: '폭', standard: '280 ± 5', method: '줄자', frequency: 'n=1\nc=0', measurements: ['278', '', '', '', ''], judgment: '적', checked: true },
              { name: '높이', standard: '300 ± 5', method: '줄자', frequency: 'n=1\nc=0', measurements: ['298', '', '', '', ''], judgment: '적', checked: true },
            ]
          },
          // 치수 검사 (가이드레일)
          {
            category: '치수\n(가이드레일)',
            items: [
              { name: '길이', standard: 'H ± 5', method: '줄자', frequency: 'n=1\nc=0', measurements: ['4003', '', '', '', ''], judgment: '적', checked: true },
              { name: '홈 너비', standard: '90 ± 2', method: '버니어', frequency: 'n=1\nc=0', measurements: ['90.5', '', '', '', ''], judgment: '적', checked: true },
            ]
          },
          // 작동검사
          {
            category: '작동검사',
            items: [
              { name: '개폐동작', standard: '원활한 개폐', method: '실동작', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
              { name: '소음', standard: '이상 소음 없음', method: '청음검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
            ]
          },
        ],
        defectContent: '',
        finalJudgment: '합격',
      },
      'PQC-JB': {
        productName: '조인트바',
        productSpec: 'L300 * W30 * T2.0',
        siteName: '인천 송도 오피스텔 신축공사',
        workOrderNo: 'WO-JB-251216-01',
        deliveryDate: '2025-12-20',
        inspectionDate: '2025-12-18',
        inspector: '노완호',
        inspectionItems: [
          // 겉모양 검사
          {
            category: '겉모양',
            items: [
              { name: '가공상태', standard: '사용상 해로운 결함이 없을 것', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
              { name: '도금상태', standard: '도금 박리, 녹 발생 없을 것', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
              { name: '홀 가공', standard: '버 없이 깨끗한 홀 가공', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
            ]
          },
          // 재질 검사
          {
            category: '재질',
            items: [
              { name: '재질', standard: 'EGI (전기아연도금강판)', method: '육안검사', frequency: '전수검사', measurements: ['OK', 'OK', 'OK', 'OK', 'OK'], judgment: '적' },
            ]
          },
          // 치수 검사
          {
            category: '치수',
            items: [
              { name: '길이(L)', standard: '300 ± 2', method: '버니어', frequency: 'n=5\nc=0', measurements: ['300.2', '299.8', '300.1', '300.0', '299.9'], judgment: '적', checked: true },
              { name: '너비(W)', standard: '30 ± 1', method: '버니어', frequency: 'n=5\nc=0', measurements: ['30.1', '30.0', '29.9', '30.0', '30.1'], judgment: '적', checked: true },
              { name: '두께(T)', standard: '2.0 ± 0.1', method: '버니어', frequency: 'n=5\nc=0', measurements: ['2.01', '2.00', '1.99', '2.00', '2.01'], judgment: '적', checked: true },
            ]
          },
          // 홀 검사
          {
            category: '홀 검사',
            items: [
              { name: '홀 직경', standard: 'Φ5.5 ± 0.2', method: '버니어', frequency: 'n=3\nc=0', measurements: ['5.52', '5.48', '5.50', '', ''], judgment: '적', checked: true },
              { name: '홀 간격', standard: '250 ± 1', method: '버니어', frequency: 'n=3\nc=0', measurements: ['250.1', '249.9', '250.0', '', ''], judgment: '적', checked: true },
              { name: '홀 위치', standard: '중심선 기준 ± 0.5', method: '버니어', frequency: 'n=3\nc=0', measurements: ['0.2', '0.1', '0.3', '', ''], judgment: '적', checked: true },
            ]
          },
          // 직진도 검사
          {
            category: '직진도',
            items: [
              { name: '직진도', standard: '1mm/m 이하', method: '직진자', frequency: 'n=5\nc=0', measurements: ['0.5', '0.3', '0.4', '0.6', '0.4'], judgment: '적' },
            ]
          },
        ],
        defectContent: '',
        finalJudgment: '합격',
      },
    };
    return samples[code] || samples['WL-SCR'];
  };

  const sampleData = getSampleData(docCode);

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-[900px] max-h-[95vh] overflow-hidden">
        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b">
          <div className="flex items-center gap-3">
            <FileText className="w-5 h-5 text-blue-500" />
            <h3 className="font-semibold">{template?.name || docType?.name || docCode} 미리보기</h3>
            <span className="text-sm text-gray-500 font-mono">({docCode})</span>
          </div>
          <div className="flex items-center gap-2">
            <button className="px-3 py-1.5 border rounded text-sm flex items-center gap-1 hover:bg-gray-50">
              <Printer className="w-4 h-4" />
              인쇄
            </button>
            <button onClick={onClose} className="p-1.5 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
              ✕
            </button>
          </div>
        </div>

        {/* 미리보기 본문 */}
        <div className="p-6 overflow-y-auto max-h-[calc(95vh-70px)] bg-gray-100">
          {/* A4 용지 프레임 */}
          <div
            className="bg-white shadow-lg mx-auto"
            style={{
              width: template?.orientation === 'landscape' ? '297mm' : '210mm',
              minHeight: template?.orientation === 'landscape' ? '210mm' : '297mm',
              padding: '15mm',
              transform: 'scale(0.7)',
              transformOrigin: 'top center',
            }}
          >
            {/* 출고증 (TS) 렌더링 */}
            {docCode === 'TS' ? (
              <>
                {/* KD 로고 헤더 - 출고증 */}
                <table className="w-full border-collapse mb-2" style={{ border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td rowSpan="4" className="text-center align-middle p-2" style={{ width: '100px', borderRight: '1px solid black' }}>
                        <div className="text-2xl font-black text-blue-700">KD</div>
                        <div className="text-xs font-bold">경동기업</div>
                        <div style={{ fontSize: '8px' }} className="text-gray-500">KYUNGDONG COMPANY</div>
                      </td>
                      <td rowSpan="2" className="text-center align-middle" style={{ width: '45%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                        <div className="text-2xl font-black tracking-widest">출 고 증</div>
                      </td>
                      <td rowSpan="4" className="text-center align-middle" style={{ width: '30px', borderRight: '1px solid black' }}>
                        <div className="text-xs font-bold">결</div>
                        <div className="text-xs font-bold mt-4">재</div>
                      </td>
                      <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>작성</td>
                      <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검토</td>
                      <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderBottom: '1px solid black' }}>승인</td>
                    </tr>
                    <tr>
                      <td className="text-center py-1" style={{ height: '50px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                        <div className="text-base font-bold text-blue-600">홍길동</div>
                        <div className="text-xs text-gray-500 mt-1">12/17</div>
                      </td>
                      <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                      <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}></td>
                    </tr>
                    <tr>
                      <td rowSpan="2" className="text-center py-2 font-bold align-middle" style={{ borderRight: '1px solid black', backgroundColor: '#E0F2FE' }}>
                        출하 관리
                      </td>
                      <td className="text-center py-1 text-xs" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>판매/전진</td>
                      <td className="text-center py-1 text-xs" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>출하</td>
                      <td className="text-center py-1 text-xs font-semibold" style={{ borderBottom: '1px solid black' }}>생산관리</td>
                    </tr>
                  </tbody>
                </table>

                {/* 신청업체/신청내용/납품정보 - 3단 구조 */}
                <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '33%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>신 청 업 체</td>
                      <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '33%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>신 청 내 용</td>
                      <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '34%', borderBottom: '1px solid black' }}>납 품 정 보</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>신청일자</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.requestDate}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>현장명</td>
                      <td className="px-2 py-1.5 font-bold text-red-600" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.siteName}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>납품일자</td>
                      <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}>{sampleData.deliveryDate}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>업체명</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.requestCompany}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>현장코드</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.siteCode}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>납품주소</td>
                      <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}>{sampleData.deliveryAddress}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black' }}>담당자</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black' }}>{sampleData.requestManager}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black' }}>제품명</td>
                      <td className="px-2 py-1.5 font-bold" style={{ borderRight: '1px solid black' }}>{sampleData.productName}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black' }}>연락처</td>
                      <td className="px-2 py-1.5" style={{}}>{sampleData.deliveryPhone}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 부자재 섹션 */}
                <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <thead>
                    <tr>
                      <th colSpan="7" className="bg-blue-100 py-1 font-bold text-sm border border-black">부 자 재</th>
                    </tr>
                    <tr className="bg-gray-100">
                      <th className="border border-black py-1 px-2" style={{ width: '40px' }}>순번</th>
                      <th className="border border-black py-1 px-2">품명</th>
                      <th className="border border-black py-1 px-2">규격</th>
                      <th className="border border-black py-1 px-2 bg-yellow-200" style={{ width: '60px' }}>수량</th>
                      <th className="border border-black py-1 px-2" style={{ width: '40px' }}>단위</th>
                      <th className="border border-black py-1 px-2">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {[1, 2, 3].map(i => (
                      <tr key={i}>
                        <td className="border border-black py-1.5 px-2 text-center">{i}</td>
                        <td className="border border-black py-1.5 px-2">{i === 1 ? '가이드레일' : i === 2 ? '브라켓' : '볼트세트'}</td>
                        <td className="border border-black py-1.5 px-2 text-center">{i === 1 ? 'W50*H4000' : i === 2 ? 'L형 100mm' : 'M10*30'}</td>
                        <td className="border border-black py-1.5 px-2 text-center bg-yellow-50">{i * 2}</td>
                        <td className="border border-black py-1.5 px-2 text-center">EA</td>
                        <td className="border border-black py-1.5 px-2"></td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* 모터 섹션 */}
                <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <thead>
                    <tr>
                      <th colSpan="7" className="bg-green-100 py-1 font-bold text-sm border border-black">모 터</th>
                    </tr>
                    <tr className="bg-gray-100">
                      <th className="border border-black py-1 px-2" style={{ width: '40px' }}>순번</th>
                      <th className="border border-black py-1 px-2">품명</th>
                      <th className="border border-black py-1 px-2">규격</th>
                      <th className="border border-black py-1 px-2 bg-yellow-200" style={{ width: '60px' }}>수량</th>
                      <th className="border border-black py-1 px-2" style={{ width: '40px' }}>단위</th>
                      <th className="border border-black py-1 px-2">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {[1, 2].map(i => (
                      <tr key={i}>
                        <td className="border border-black py-1.5 px-2 text-center">{i}</td>
                        <td className="border border-black py-1.5 px-2">{i === 1 ? '전동개폐기' : '연동제어기'}</td>
                        <td className="border border-black py-1.5 px-2 text-center">{i === 1 ? '220V-300KG' : '4CH'}</td>
                        <td className="border border-black py-1.5 px-2 text-center bg-yellow-50">{i}</td>
                        <td className="border border-black py-1.5 px-2 text-center">EA</td>
                        <td className="border border-black py-1.5 px-2"></td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* 슬랫 섹션 */}
                <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <thead>
                    <tr>
                      <th colSpan="7" className="bg-yellow-100 py-1 font-bold text-sm border border-black">슬 랫</th>
                    </tr>
                    <tr className="bg-gray-100">
                      <th className="border border-black py-1 px-2" style={{ width: '40px' }}>순번</th>
                      <th className="border border-black py-1 px-2">품명</th>
                      <th className="border border-black py-1 px-2">규격</th>
                      <th className="border border-black py-1 px-2 bg-yellow-200" style={{ width: '60px' }}>수량</th>
                      <th className="border border-black py-1 px-2" style={{ width: '40px' }}>단위</th>
                      <th className="border border-black py-1 px-2">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {[1, 2].map(i => (
                      <tr key={i}>
                        <td className="border border-black py-1.5 px-2 text-center">{i}</td>
                        <td className="border border-black py-1.5 px-2">{i === 1 ? '슬랫조립체' : '엔드락'}</td>
                        <td className="border border-black py-1.5 px-2 text-center">{i === 1 ? 'W3000*65T' : 'W3000'}</td>
                        <td className="border border-black py-1.5 px-2 text-center bg-yellow-50">{i === 1 ? 60 : 2}</td>
                        <td className="border border-black py-1.5 px-2 text-center">EA</td>
                        <td className="border border-black py-1.5 px-2"></td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* 절곡품 섹션 + LOT NO 기록란 */}
                <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <thead>
                    <tr>
                      <th colSpan="7" className="bg-orange-100 py-1 font-bold text-sm border border-black">절 곡 품</th>
                    </tr>
                    <tr className="bg-gray-100">
                      <th className="border border-black py-1 px-2" style={{ width: '40px' }}>순번</th>
                      <th className="border border-black py-1 px-2">품명</th>
                      <th className="border border-black py-1 px-2">규격</th>
                      <th className="border border-black py-1 px-2 bg-yellow-200" style={{ width: '60px' }}>수량</th>
                      <th className="border border-black py-1 px-2" style={{ width: '40px' }}>단위</th>
                      <th className="border border-black py-1 px-2 bg-yellow-300">LOT NO</th>
                    </tr>
                  </thead>
                  <tbody>
                    {[1, 2, 3].map(i => (
                      <tr key={i}>
                        <td className="border border-black py-1.5 px-2 text-center">{i}</td>
                        <td className="border border-black py-1.5 px-2">{i === 1 ? '커버박스' : i === 2 ? '가이드레일' : '바텀바'}</td>
                        <td className="border border-black py-1.5 px-2 text-center">{i === 1 ? 'W3000*H300' : i === 2 ? 'W50*H4000' : 'W3000'}</td>
                        <td className="border border-black py-1.5 px-2 text-center bg-yellow-50">{i}</td>
                        <td className="border border-black py-1.5 px-2 text-center">EA</td>
                        <td className="border border-black py-1.5 px-2 text-center font-mono text-xs">{`KD-BD-251217-0${i}`}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* 소모품 섹션 */}
                <table className="w-full border-collapse" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <thead>
                    <tr>
                      <th colSpan="6" className="bg-purple-100 py-1 font-bold text-sm border border-black">소 모 품</th>
                    </tr>
                    <tr className="bg-gray-100">
                      <th className="border border-black py-1 px-2" style={{ width: '40px' }}>순번</th>
                      <th className="border border-black py-1 px-2">품명</th>
                      <th className="border border-black py-1 px-2">규격</th>
                      <th className="border border-black py-1 px-2 bg-yellow-200" style={{ width: '60px' }}>수량</th>
                      <th className="border border-black py-1 px-2" style={{ width: '40px' }}>단위</th>
                      <th className="border border-black py-1 px-2">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {[1, 2].map(i => (
                      <tr key={i}>
                        <td className="border border-black py-1.5 px-2 text-center">{i}</td>
                        <td className="border border-black py-1.5 px-2">{i === 1 ? '리벳' : '실리콘'}</td>
                        <td className="border border-black py-1.5 px-2 text-center">{i === 1 ? '4.8*12' : '투명'}</td>
                        <td className="border border-black py-1.5 px-2 text-center bg-yellow-50">{i === 1 ? 200 : 3}</td>
                        <td className="border border-black py-1.5 px-2 text-center">{i === 1 ? 'EA' : '개'}</td>
                        <td className="border border-black py-1.5 px-2"></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </>
            ) : docCode === 'IQC' ? (
              <>
                {/* 수입검사성적서 (IQC) 렌더링 */}
                {/* KD 로고 헤더 - 수입검사성적서 */}
                <table className="w-full border-collapse mb-4" style={{ border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td rowSpan="3" className="text-center align-middle p-2" style={{ width: '100px', borderRight: '1px solid black' }}>
                        <div className="text-2xl font-black text-blue-700">KD</div>
                        <div className="text-xs font-bold">경동기업</div>
                        <div style={{ fontSize: '8px' }} className="text-gray-500">KYUNGDONG COMPANY</div>
                      </td>
                      <td rowSpan="3" className="text-center align-middle" style={{ width: '50%', borderRight: '1px solid black' }}>
                        <div className="text-2xl font-black tracking-widest">수 입 검 사 성 적 서</div>
                      </td>
                      <td className="text-center text-xs font-semibold py-1 bg-gray-100" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>담당</td>
                      <td className="text-center text-xs font-semibold py-1 bg-gray-100" style={{ width: '60px', borderBottom: '1px solid black' }}>부서장</td>
                    </tr>
                    <tr>
                      <td rowSpan="2" className="text-center py-1" style={{ height: '50px', borderRight: '1px solid black' }}>
                        <div className="text-sm font-bold">{sampleData.inspector}</div>
                        <div className="text-xs text-gray-500 mt-1">07/15</div>
                      </td>
                      <td rowSpan="2" className="text-center py-1" style={{}}></td>
                    </tr>
                    <tr>
                    </tr>
                  </tbody>
                </table>

                {/* 입고일자 */}
                <div className="text-right mb-2" style={{ fontSize: '10px' }}>
                  <span className="font-bold">입고일자 : </span>
                  <span>{sampleData.inboundDate}</span>
                </div>

                {/* 품목정보 테이블 */}
                <table className="w-full border-collapse mb-4" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '80px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>품 명</td>
                      <td className="px-2 py-1.5 whitespace-pre-line" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.itemName}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '80px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>납품업체<br />제조업체</td>
                      <td className="px-2 py-1.5 text-cyan-600 font-bold whitespace-pre-line" style={{ borderBottom: '1px solid black' }}>{sampleData.supplier}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>규 격<br />(두께*너비*길이)</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.itemSpec}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>로트번호</td>
                      <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}>{sampleData.lotNo}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>자재번호</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.materialNo}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사일자</td>
                      <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}>{sampleData.inspectionDate}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black' }}>로트크기</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black' }}>{sampleData.lotSize}<span className="ml-8">매</span></td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black' }}>검사자</td>
                      <td className="px-2 py-1.5">{sampleData.inspector}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 검사항목 테이블 */}
                <table className="w-full border-collapse mb-4" style={{ fontSize: '8px', border: '2px solid black' }}>
                  <thead>
                    <tr className="bg-yellow-50">
                      <th rowSpan="2" className="border border-black py-1 px-1 font-bold" style={{ width: '30px' }}>NO</th>
                      <th rowSpan="2" className="border border-black py-1 px-1 font-bold" style={{ width: '70px' }}>검사항목</th>
                      <th colSpan="2" rowSpan="2" className="border border-black py-1 px-1 font-bold">검사기준</th>
                      <th rowSpan="2" className="border border-black py-1 px-1 font-bold" style={{ width: '50px' }}>검사방식</th>
                      <th rowSpan="2" className="border border-black py-1 px-1 font-bold" style={{ width: '40px' }}>검사주기</th>
                      <th colSpan="3" className="border border-black py-1 px-1 font-bold">측정치</th>
                      <th rowSpan="2" className="border border-black py-1 px-1 font-bold" style={{ width: '35px' }}>판정<br />(적/부)</th>
                    </tr>
                    <tr className="bg-yellow-50">
                      <th className="border border-black py-1 px-1 font-bold" style={{ width: '55px' }}>n1<br />양호/불량</th>
                      <th className="border border-black py-1 px-1 font-bold" style={{ width: '55px' }}>n2<br />양호/불량</th>
                      <th className="border border-black py-1 px-1 font-bold" style={{ width: '55px' }}>n3<br />양호/불량</th>
                    </tr>
                  </thead>
                  <tbody>
                    {/* 1. 겉모양 */}
                    <tr>
                      <td className="border border-black py-1 px-1 text-center">1</td>
                      <td className="border border-black py-1 px-1 text-center">겉모양</td>
                      <td colSpan="2" className="border border-black py-1 px-1 text-center whitespace-pre-line">사용상 해로울<br />결함이 없을 것</td>
                      <td className="border border-black py-1 px-1 text-center">육안검사</td>
                      <td className="border border-black py-1 px-1 text-center"></td>
                      <td className="border border-black py-1 px-1 text-center">
                        <span className="inline-flex items-center"><span className="text-green-600">☑</span>OK<span className="ml-1">☐</span>NG</span>
                      </td>
                      <td className="border border-black py-1 px-1 text-center">
                        <span className="inline-flex items-center"><span className="text-green-600">☑</span>OK<span className="ml-1">☐</span>NG</span>
                      </td>
                      <td className="border border-black py-1 px-1 text-center">
                        <span className="inline-flex items-center"><span className="text-green-600">☑</span>OK<span className="ml-1">☐</span>NG</span>
                      </td>
                      <td className="border border-black py-1 px-1 text-center font-bold">적</td>
                    </tr>
                    {/* 2. 치수 - 두께 */}
                    <tr>
                      <td rowSpan="9" className="border border-black py-1 px-1 text-center align-middle">2</td>
                      <td rowSpan="9" className="border border-black py-1 px-1 text-center align-middle">치수</td>
                      <td rowSpan="4" className="border border-black py-1 px-1 text-center align-middle">두께<br />1.55</td>
                      <td className="border border-black py-0.5 px-1"><span>☐</span> 0.8 이상 ~ 1.0 미만</td>
                      <td className="border border-black py-0.5 px-1 text-center">± 0.07</td>
                      <td rowSpan="9" className="border border-black py-1 px-1 text-center align-middle whitespace-pre-line">n=3<br />c=0</td>
                      <td rowSpan="4" className="border border-black py-1 px-1 text-center align-middle">1.528</td>
                      <td rowSpan="4" className="border border-black py-1 px-1 text-center align-middle">1.533</td>
                      <td rowSpan="4" className="border border-black py-1 px-1 text-center align-middle">1.521</td>
                      <td rowSpan="4" className="border border-black py-1 px-1 text-center align-middle font-bold">적</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-0.5 px-1"><span>☐</span> 1.0 이상 ~ 1.25 미만</td>
                      <td className="border border-black py-0.5 px-1 text-center">± 0.08</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-0.5 px-1 bg-green-100"><span className="text-green-600">☑</span> 1.25 이상 ~ 1.6 미만</td>
                      <td className="border border-black py-0.5 px-1 text-center bg-green-100">± 0.10</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-0.5 px-1 font-bold"><span>☐</span> 1.6 이상 ~ 2.0 미만</td>
                      <td className="border border-black py-0.5 px-1 text-center font-bold">± 0.12</td>
                    </tr>
                    {/* 치수 - 너비 */}
                    <tr>
                      <td rowSpan="2" className="border border-black py-1 px-1 text-center align-middle">너비<br />1219</td>
                      <td className="border border-black py-0.5 px-1 bg-green-100"><span className="text-green-600">☑</span> 1250 미만</td>
                      <td className="border border-black py-0.5 px-1 text-center bg-green-100">+7<br />-0</td>
                      <td rowSpan="2" className="border border-black py-1 px-1 text-center align-middle">1222</td>
                      <td rowSpan="2" className="border border-black py-1 px-1 text-center align-middle">1222</td>
                      <td rowSpan="2" className="border border-black py-1 px-1 text-center align-middle">1222</td>
                      <td rowSpan="2" className="border border-black py-1 px-1 text-center align-middle font-bold">적</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-0.5 px-1"><span>☐</span> 1250 미만</td>
                      <td className="border border-black py-0.5 px-1 text-center">+10<br />-0</td>
                    </tr>
                    {/* 치수 - 길이 */}
                    <tr>
                      <td rowSpan="3" className="border border-black py-1 px-1 text-center align-middle">길이<br />480</td>
                      <td className="border border-black py-0.5 px-1"><span>☐</span> 2000 이상 ~ 4000 미만</td>
                      <td className="border border-black py-0.5 px-1 text-center">+15<br />-0</td>
                      <td rowSpan="3" className="border border-black py-1 px-1 text-center align-middle">480</td>
                      <td rowSpan="3" className="border border-black py-1 px-1 text-center align-middle">480</td>
                      <td rowSpan="3" className="border border-black py-1 px-1 text-center align-middle">480</td>
                      <td rowSpan="3" className="border border-black py-1 px-1 text-center align-middle font-bold">적</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-0.5 px-1"><span>☐</span> 4000 이상 ~ 6000 미만</td>
                      <td className="border border-black py-0.5 px-1 text-center">+20<br />-0</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-0.5 px-1"></td>
                      <td className="border border-black py-0.5 px-1 text-center"></td>
                    </tr>
                    {/* 3. 인장강도 */}
                    <tr>
                      <td className="border border-black py-1 px-1 text-center">3</td>
                      <td className="border border-black py-1 px-1 text-center">인장강도<br />(N/mm²)</td>
                      <td colSpan="2" className="border border-black py-1 px-1 text-center">270 이상</td>
                      <td className="border border-black py-1 px-1 text-center"></td>
                      <td className="border border-black py-1 px-1 text-center"></td>
                      <td colSpan="3" className="border border-black py-1 px-1 text-center">313.8</td>
                      <td className="border border-black py-1 px-1 text-center font-bold">적</td>
                    </tr>
                    {/* 4. 연신율 */}
                    <tr>
                      <td rowSpan="3" className="border border-black py-1 px-1 text-center align-middle">4</td>
                      <td rowSpan="3" className="border border-black py-1 px-1 text-center align-middle">연신율<br />%</td>
                      <td className="border border-black py-0.5 px-1"><span>☐</span> 두께 0.6 이상 ~ 1.0 미만</td>
                      <td className="border border-black py-0.5 px-1 text-center">36 이상</td>
                      <td rowSpan="3" className="border border-black py-1 px-1 text-center align-middle whitespace-pre-line">공급업체<br />밀시트</td>
                      <td rowSpan="3" className="border border-black py-1 px-1 text-center align-middle">입고시</td>
                      <td rowSpan="3" colSpan="3" className="border border-black py-1 px-1 text-center align-middle">46.5</td>
                      <td rowSpan="3" className="border border-black py-1 px-1 text-center align-middle font-bold">적</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-0.5 px-1 bg-green-100"><span className="text-green-600">☑</span> 두께 1.0 이상 ~ 1.6 미만</td>
                      <td className="border border-black py-0.5 px-1 text-center bg-green-100">37 이상</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-0.5 px-1 font-bold"><span>☐</span> 두께 1.6 이상 ~ 2.3 미만</td>
                      <td className="border border-black py-0.5 px-1 text-center font-bold">38 이상</td>
                    </tr>
                    {/* 5. 아연 부착량 */}
                    <tr>
                      <td className="border border-black py-1 px-1 text-center">5</td>
                      <td className="border border-black py-1 px-1 text-center whitespace-pre-line">아연의 최소<br />부착량 (g/m²)</td>
                      <td colSpan="2" className="border border-black py-1 px-1 text-center">한면 17 이상</td>
                      <td className="border border-black py-1 px-1 text-center"></td>
                      <td className="border border-black py-1 px-1 text-center"></td>
                      <td colSpan="3" className="border border-black py-1 px-1 text-center">17.21 / 17.17</td>
                      <td className="border border-black py-1 px-1 text-center font-bold">적</td>
                    </tr>
                  </tbody>
                </table>

                {/* 하단 참고사항 및 종합판정 */}
                <table className="w-full border-collapse" style={{ fontSize: '8px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td className="border border-black p-2 align-top" style={{ width: '70%' }}>
                        <div className="font-bold mb-1"># 1.55mm의 경우 KS F 4510에 따른 MIN 15의 기준에 따름</div>
                        <div className="font-bold"># 두께의 경우 너비 1000 이상 ~ 1250 미만 기준에 따름</div>
                        <div className="mt-2 font-bold">[부적합 내용]</div>
                      </td>
                      <td className="border border-black p-2 text-center align-top" style={{ width: '30%' }}>
                        <div className="bg-gray-100 py-1 font-bold mb-2">종합판정</div>
                        <div className="text-3xl font-black text-blue-600">합격</div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </>
            ) : ['PQC-SCR', 'PQC-BND', 'PQC-SLT', 'PQC-JB'].includes(docCode) ? (
              <>
                {/* 통합 중간검사성적서 (PQC-SCR/BND/SLT/JB) 렌더링 */}
                {/* KD 로고 헤더 */}
                <table className="w-full table-fixed border-collapse mb-1" style={{ border: '2px solid black' }}>
                  <colgroup>
                    <col style={{ width: '18%' }} />
                    <col style={{ width: '52%' }} />
                    <col style={{ width: '15%' }} />
                    <col style={{ width: '15%' }} />
                  </colgroup>
                  <tbody>
                    <tr>
                      <td rowSpan="2" className="text-center align-middle p-1 border-r border-black">
                        <div className="text-lg font-black text-blue-700">KD</div>
                        <div style={{ fontSize: '8px' }} className="font-bold">경동기업</div>
                        <div style={{ fontSize: '6px' }} className="text-gray-500">KYUNGDONG</div>
                      </td>
                      <td rowSpan="2" className="text-center align-middle border-r border-black">
                        <div style={{ fontSize: '14px' }} className="font-black tracking-wider">중 간 검 사 성 적 서</div>
                        <div style={{ fontSize: '9px' }} className="mt-0.5">
                          ({docCode === 'PQC-SCR' ? '스크린' : docCode === 'PQC-BND' ? '절곡품' : docCode === 'PQC-SLT' ? '슬랫' : '조인트바'})
                        </div>
                      </td>
                      <td className="text-center font-semibold py-0.5 bg-gray-100 border-r border-b border-black" style={{ fontSize: '8px' }}>담당</td>
                      <td className="text-center font-semibold py-0.5 bg-gray-100 border-b border-black" style={{ fontSize: '8px' }}>부서장</td>
                    </tr>
                    <tr>
                      <td className="text-center py-1 border-r border-black" style={{ height: '28px' }}>
                        <div style={{ fontSize: '9px' }} className="font-bold">{sampleData.inspector}</div>
                        <div style={{ fontSize: '7px' }} className="text-gray-500">12/18</div>
                      </td>
                      <td className="text-center py-1"></td>
                    </tr>
                  </tbody>
                </table>

                {/* 품목정보 테이블 */}
                <table className="w-full table-fixed border-collapse mb-1" style={{ fontSize: '8px', border: '2px solid black' }}>
                  <colgroup>
                    <col style={{ width: '13%' }} />
                    <col style={{ width: '37%' }} />
                    <col style={{ width: '13%' }} />
                    <col style={{ width: '37%' }} />
                  </colgroup>
                  <tbody>
                    <tr>
                      <td className="text-center bg-gray-100 py-0.5 font-semibold border-r border-b border-black">품명</td>
                      <td className="px-1 py-0.5 border-r border-b border-black truncate">{sampleData.productName}</td>
                      <td className="text-center bg-gray-100 py-0.5 font-semibold border-r border-b border-black">현장명</td>
                      <td className="px-1 py-0.5 border-b border-black truncate">{sampleData.siteName}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-0.5 font-semibold border-r border-b border-black">규격</td>
                      <td className="px-1 py-0.5 border-r border-b border-black">{sampleData.productSpec}</td>
                      <td className="text-center bg-gray-100 py-0.5 font-semibold border-r border-b border-black">작업지시번호</td>
                      <td className="px-1 py-0.5 font-mono border-b border-black" style={{ fontSize: '7px' }}>{sampleData.workOrderNo}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-0.5 font-semibold border-r border-b border-black">납품일자</td>
                      <td className="px-1 py-0.5 border-r border-b border-black">{sampleData.deliveryDate}</td>
                      <td className="text-center bg-gray-100 py-0.5 font-semibold border-r border-b border-black">검사일자</td>
                      <td className="px-1 py-0.5 border-b border-black">{sampleData.inspectionDate}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-0.5 font-semibold border-r border-black">검사자</td>
                      <td colSpan="3" className="px-1 py-0.5">{sampleData.inspector}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 검사항목 테이블 */}
                <table className="w-full table-fixed border-collapse mb-1" style={{ fontSize: '7px', border: '2px solid black' }}>
                  <colgroup>
                    <col style={{ width: '10%' }} />
                    <col style={{ width: '10%' }} />
                    <col style={{ width: '28%' }} />
                    <col style={{ width: '10%' }} />
                    <col style={{ width: '8%' }} />
                    <col style={{ width: '6%' }} />
                    <col style={{ width: '6%' }} />
                    <col style={{ width: '6%' }} />
                    <col style={{ width: '6%' }} />
                    <col style={{ width: '6%' }} />
                    <col style={{ width: '4%' }} />
                  </colgroup>
                  <thead>
                    <tr className="bg-yellow-50">
                      <th className="border border-black py-0.5 font-bold">항목</th>
                      <th className="border border-black py-0.5 font-bold">세부</th>
                      <th className="border border-black py-0.5 font-bold">검사기준</th>
                      <th className="border border-black py-0.5 font-bold">방법</th>
                      <th className="border border-black py-0.5 font-bold">주기</th>
                      <th className="border border-black py-0.5 font-bold">n1</th>
                      <th className="border border-black py-0.5 font-bold">n2</th>
                      <th className="border border-black py-0.5 font-bold">n3</th>
                      <th className="border border-black py-0.5 font-bold">n4</th>
                      <th className="border border-black py-0.5 font-bold">n5</th>
                      <th className="border border-black py-0.5 font-bold">적</th>
                    </tr>
                  </thead>
                  <tbody>
                    {sampleData.inspectionItems?.map((category, catIdx) => (
                      category.items.map((item, itemIdx) => (
                        <tr key={`${catIdx}-${itemIdx}`}>
                          {itemIdx === 0 && (
                            <td rowSpan={category.items.length} className="border border-black py-0.5 text-center align-middle whitespace-pre-line bg-gray-50 font-semibold" style={{ fontSize: '6px' }}>
                              {category.category}
                            </td>
                          )}
                          <td className="border border-black py-0.5 text-center" style={{ fontSize: '6px' }}>{item.name}</td>
                          <td className="border border-black py-0.5 px-0.5 whitespace-pre-line overflow-hidden" style={{ fontSize: '6px' }}>
                            {item.checked && <span className="text-green-600">☑</span>}
                            {!item.checked && item.standard?.includes('±') && <span>☐</span>}
                            {item.standard}
                          </td>
                          <td className="border border-black py-0.5 text-center" style={{ fontSize: '6px' }}>{item.method}</td>
                          <td className="border border-black py-0.5 text-center whitespace-pre-line" style={{ fontSize: '5px' }}>{item.frequency}</td>
                          {item.measurements?.map((m, mIdx) => (
                            <td key={mIdx} className="border border-black py-0.5 text-center" style={{ fontSize: '6px' }}>
                              {m === 'OK' ? <span className="text-green-600 font-bold">O</span> : m}
                            </td>
                          ))}
                          <td className="border border-black py-0.5 text-center font-bold">{item.judgment}</td>
                        </tr>
                      ))
                    ))}
                  </tbody>
                </table>

                {/* 하단 비고 및 종합판정 */}
                <table className="w-full table-fixed border-collapse" style={{ fontSize: '7px', border: '2px solid black' }}>
                  <colgroup>
                    <col style={{ width: '70%' }} />
                    <col style={{ width: '30%' }} />
                  </colgroup>
                  <tbody>
                    <tr>
                      <td className="border border-black p-1 align-top">
                        <div className="font-bold mb-0.5">[비고 / 부적합 내용]</div>
                        <div className="min-h-[20px]">{sampleData.defectContent}</div>
                      </td>
                      <td className="border border-black p-1 text-center align-top">
                        <div className="bg-gray-100 py-0.5 font-bold mb-0.5">종합판정</div>
                        <div className="text-xl font-black text-blue-600">{sampleData.finalJudgment}</div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </>
            ) : (
              <>
                {/* KD 로고 헤더 - 작업일지 */}
                <table className="w-full border-collapse mb-2" style={{ border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td rowSpan="4" className="text-center align-middle p-2" style={{ width: '100px', borderRight: '1px solid black' }}>
                        <div className="text-2xl font-black text-blue-700">KD</div>
                        <div className="text-xs font-bold">경동기업</div>
                        <div style={{ fontSize: '8px' }} className="text-gray-500">KYUNGDONG COMPANY</div>
                      </td>
                      <td rowSpan="2" className="text-center align-middle" style={{ width: '45%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                        <div className="text-2xl font-black tracking-widest">작 업 일 지</div>
                      </td>
                      <td rowSpan="4" className="text-center align-middle" style={{ width: '30px', borderRight: '1px solid black' }}>
                        <div className="text-xs font-bold">결</div>
                        <div className="text-xs font-bold mt-4">재</div>
                      </td>
                      <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>작성</td>
                      <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검토</td>
                      <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderBottom: '1px solid black' }}>승인</td>
                    </tr>
                    <tr>
                      <td className="text-center py-1" style={{ height: '50px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                        <div className="text-base font-bold text-blue-600">홍길동</div>
                        <div className="text-xs text-gray-500 mt-1">12/17</div>
                      </td>
                      <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                      <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}></td>
                    </tr>
                    <tr>
                      <td rowSpan="2" className="text-center py-2 font-bold align-middle" style={{ borderRight: '1px solid black', backgroundColor: docCode === 'WL-SCR' ? '#FFFF00' : docCode === 'WL-SLT' ? '#00FF00' : '#FFA500' }}>
                        {docCode === 'WL-SCR' ? '스크린 생산부서' : docCode === 'WL-SLT' ? '슬랫 생산부서' : '절곡 생산부서'}
                      </td>
                      <td className="text-center py-1 text-xs" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>판매/전진</td>
                      <td className="text-center py-1 text-xs" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>생산</td>
                      <td className="text-center py-1 text-xs font-semibold" style={{ borderBottom: '1px solid black' }}>품질</td>
                    </tr>
                  </tbody>
                </table>

                {/* 신청업체/신청내용 */}
                <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '50%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>신 청 업 체</td>
                      <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '50%', borderBottom: '1px solid black' }}>신 청 내 용</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 일</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.orderDate}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '80px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>현 장 명</td>
                      <td className="px-2 py-1.5 font-bold text-red-600" style={{ borderBottom: '1px solid black' }}>{sampleData.siteName}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>업 체 명</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.customerName}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>작업일자</td>
                      <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}>{sampleData.workDate}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>담 당 자</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.managerName}</td>
                      <td className="text-center bg-yellow-300 py-1.5 font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>제품 LOT NO.</td>
                      <td className="px-2 py-1.5 font-bold" style={{ borderBottom: '1px solid black' }}>{sampleData.lotNo}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-200 py-1.5 font-bold" style={{ borderRight: '1px solid black' }}>제품명</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black' }}>
                        <span className="font-bold">{sampleData.productCode}</span>
                        <span className="ml-4 font-bold">{sampleData.productName}</span>
                      </td>
                      <td className="text-center bg-gray-200 py-1.5 font-bold" style={{ borderRight: '1px solid black' }}>마감유형</td>
                      <td className="px-2 py-1.5">
                        <span className="font-bold text-red-600">{sampleData.finishType}</span>
                        <span className="ml-4 font-bold text-red-600">{sampleData.finishSpec}</span>
                      </td>
                    </tr>
                  </tbody>
                </table>

                {/* 작업내역 테이블 샘플 */}
                <table className="w-full border-collapse" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <thead>
                    <tr className="bg-blue-100">
                      <th className="border border-black py-1 px-2">순번</th>
                      <th className="border border-black py-1 px-2">작업항목</th>
                      <th className="border border-black py-1 px-2">규격</th>
                      <th className="border border-black py-1 px-2 bg-yellow-200">수량</th>
                      <th className="border border-black py-1 px-2">단위</th>
                      <th className="border border-black py-1 px-2">작업자</th>
                      <th className="border border-black py-1 px-2">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {[1, 2, 3, 4, 5].map(i => (
                      <tr key={i}>
                        <td className="border border-black py-2 px-2 text-center">{i}</td>
                        <td className="border border-black py-2 px-2">{i === 1 ? '원단 재단' : i === 2 ? '미싱 작업' : i === 3 ? '앤드락 조립' : i === 4 ? '검수' : '포장'}</td>
                        <td className="border border-black py-2 px-2 text-center">W{3000 - i * 100} × H{4000 - i * 100}</td>
                        <td className="border border-black py-2 px-2 text-center bg-yellow-50">{10 - i}</td>
                        <td className="border border-black py-2 px-2 text-center">EA</td>
                        <td className="border border-black py-2 px-2 text-center">{i % 2 === 0 ? '김작업' : '이작업'}</td>
                        <td className="border border-black py-2 px-2"></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </>
            )}

            {/* 블록 구성 정보 */}
            {template?.blocks && (
              <div className="mt-6 p-4 bg-gray-50 rounded border">
                <h4 className="font-bold text-sm mb-2 text-gray-700">문서 구성 블록</h4>
                <div className="flex flex-wrap gap-2">
                  {template.blocks.map((block, idx) => {
                    const blockInfo = getBlockInfo(block.blockId);
                    return (
                      <span key={idx} className="px-2 py-1 bg-white border rounded text-xs">
                        {blockInfo?.name || block.blockId}
                      </span>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// 데이터 연동 작업일지 프리뷰 모달
// ============================================================
const WorkLogDataPreviewModal = ({ workOrder, workResults = [], order, onClose }) => {
  if (!workOrder) return null;

  // 공정 유형에 따른 문서 코드 결정
  const getDocCode = (processType) => {
    if (processType?.includes('스크린') || processType?.includes('방화') || processType?.includes('SCR')) return 'WL-SCR';
    if (processType?.includes('슬랫') || processType?.includes('SLT')) return 'WL-SLT';
    if (processType?.includes('절곡') || processType?.includes('FLD') || processType?.includes('BD')) return 'WL-FLD';
    return 'WL-SCR'; // 기본값
  };

  const docCode = getDocCode(workOrder.processType || workOrder.orderNo);

  // 색상 결정
  const getProcessColor = () => {
    switch (docCode) {
      case 'WL-SCR': return '#FFFF00'; // 노랑
      case 'WL-SLT': return '#90EE90'; // 연두
      case 'WL-FLD': return '#FFA500'; // 주황
      default: return '#FFFF00';
    }
  };

  const getProcessName = () => {
    switch (docCode) {
      case 'WL-SCR': return '스크린 생산부서';
      case 'WL-SLT': return '슬랫 생산부서';
      case 'WL-FLD': return '절곡 생산부서';
      default: return '생산부서';
    }
  };

  // 날짜 포맷
  const formatDate = (dateStr) => {
    if (!dateStr) return new Date().toISOString().slice(0, 10);
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  };

  const getShortDate = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  };

  // 작업 품목 목록 (workOrder.items에서 가져옴)
  const workItems = workOrder.items || [];

  // 절곡 공정 전개도 데이터
  const bendingParts = [
    { itemCode: 'SD30', itemName: '엘바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 4, weight: 0.9, dimensions: '75', svgType: 'rect' },
    { itemCode: 'SD31', itemName: '하장바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 1.158, dimensions: '67→126→165→178→193', svgType: 'hajang' },
    { itemCode: 'SD32', itemName: '짜부가스켓', material: 'E.G.I 0.8T', totalWidth: 500, length: 3000, qty: 4, weight: 0.576, dimensions: '48', svgType: 'thin' },
    { itemCode: 'SD33', itemName: '50평철', material: 'E.G.I 1.2T', totalWidth: 500, length: 3000, qty: 2, weight: 0.3, dimensions: '50', svgType: 'flat' },
    { itemCode: 'SD34', itemName: '전면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.764, dimensions: '120→499→553→588', svgType: 'front' },
    { itemCode: 'SD35', itemName: '린텔박스', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 0.504, dimensions: '84→138→168', svgType: 'lintel' },
  ];

  // SVG 전개도 렌더링
  const renderBendingSvg = (svgType) => {
    switch (svgType) {
      case 'rect':
        return <><rect x="10" y="20" width="80" height="20" fill="none" stroke="#333" strokeWidth="1" /><line x1="10" y1="30" x2="90" y2="30" stroke="#666" strokeWidth="0.5" strokeDasharray="2,2" /></>;
      case 'hajang':
        return <path d="M10,40 L20,40 L20,20 L40,20 L40,30 L60,30 L60,20 L80,20 L80,40 L90,40" fill="none" stroke="#333" strokeWidth="1" />;
      case 'thin':
        return <rect x="10" y="25" width="80" height="10" fill="none" stroke="#333" strokeWidth="1" />;
      case 'flat':
        return <rect x="10" y="22" width="80" height="16" fill="none" stroke="#333" strokeWidth="1" />;
      case 'front':
        return <path d="M10,45 L10,15 L25,15 L25,25 L75,25 L75,15 L90,15 L90,45 Z" fill="none" stroke="#333" strokeWidth="1" />;
      case 'lintel':
        return <path d="M15,40 L15,20 L35,20 L35,30 L65,30 L65,20 L85,20 L85,40" fill="none" stroke="#333" strokeWidth="1" />;
      default:
        return <rect x="10" y="20" width="80" height="20" fill="none" stroke="#333" strokeWidth="1" />;
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-[900px] max-h-[95vh] overflow-hidden">
        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b">
          <div className="flex items-center gap-3">
            <FileText className="w-5 h-5 text-blue-500" />
            <h3 className="font-semibold">작업일지</h3>
            <span className={`text-xs px-2 py-0.5 rounded ${docCode === 'WL-SCR' ? 'bg-yellow-100 text-yellow-700' :
                docCode === 'WL-SLT' ? 'bg-green-100 text-green-700' :
                  'bg-orange-100 text-orange-700'
              }`}>{getProcessName()}</span>
            <span className="text-sm text-gray-500 font-mono">({workOrder.workOrderNo})</span>
          </div>
          <div className="flex items-center gap-2">
            <button className="px-3 py-1.5 border rounded text-sm flex items-center gap-1 hover:bg-gray-50">
              <Printer className="w-4 h-4" /> 인쇄
            </button>
            <button onClick={onClose} className="p-1.5 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">✕</button>
          </div>
        </div>

        {/* 미리보기 본문 */}
        <div className="p-6 overflow-y-auto max-h-[calc(95vh-70px)] bg-gray-100">
          {/* A4 용지 프레임 */}
          <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '12mm', transform: 'scale(0.72)', transformOrigin: 'top center' }}>
            {/* KD 로고 헤더 */}
            <table className="w-full border-collapse mb-2" style={{ border: '2px solid black' }}>
              <tbody>
                <tr>
                  <td rowSpan="3" className="text-center align-middle p-2" style={{ width: '90px', borderRight: '1px solid black' }}>
                    <div className="text-2xl font-black text-blue-700">KD</div>
                    <div className="text-xs font-bold">경동기업</div>
                  </td>
                  <td rowSpan="2" className="text-center align-middle" style={{ width: '45%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                    <div className="text-2xl font-black tracking-widest">작 업 일 지</div>
                    <div className="text-xs text-gray-500 mt-1">{docCode}</div>
                  </td>
                  <td rowSpan="3" className="text-center align-middle" style={{ width: '25px', borderRight: '1px solid black' }}>
                    <div className="text-xs font-bold">결</div><div className="text-xs font-bold mt-3">재</div>
                  </td>
                  <td className="text-center text-xs py-1" style={{ width: '55px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>작성</td>
                  <td className="text-center text-xs py-1" style={{ width: '55px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검토</td>
                  <td className="text-center text-xs py-1" style={{ width: '55px', borderBottom: '1px solid black' }}>승인</td>
                </tr>
                <tr>
                  <td className="text-center py-2" style={{ height: '40px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                    <div className="text-sm font-bold text-blue-600">{workOrder.assignee || '-'}</div>
                  </td>
                  <td className="text-center py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                  <td className="text-center py-2" style={{ borderBottom: '1px solid black' }}></td>
                </tr>
                <tr>
                  <td className="text-center py-2 font-bold" style={{ borderRight: '1px solid black', backgroundColor: getProcessColor() }}>
                    {getProcessName()}
                  </td>
                  <td className="text-center text-xs py-1" style={{ borderRight: '1px solid black' }}>판매</td>
                  <td className="text-center text-xs py-1" style={{ borderRight: '1px solid black' }}>생산</td>
                  <td className="text-center text-xs py-1">품질</td>
                </tr>
              </tbody>
            </table>

            {/* 기본정보 */}
            <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
              <tbody>
                <tr>
                  <td className="text-center bg-gray-100 py-1 font-semibold" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 처</td>
                  <td className="px-2 py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{workOrder.customerName || '-'}</td>
                  <td className="text-center bg-gray-100 py-1 font-semibold" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>현 장 명</td>
                  <td className="px-2 py-1 font-bold text-red-600" style={{ borderBottom: '1px solid black' }}>{workOrder.siteName || '-'}</td>
                </tr>
                <tr>
                  <td className="text-center bg-gray-100 py-1 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>작업일자</td>
                  <td className="px-2 py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{formatDate(workOrder.instructionDate)}</td>
                  <td className="text-center bg-yellow-200 py-1 font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>LOT NO.</td>
                  <td className="px-2 py-1 font-bold" style={{ borderBottom: '1px solid black' }}>{workOrder.lotNo || workOrder.workOrderNo}</td>
                </tr>
                <tr>
                  <td className="text-center bg-gray-100 py-1 font-semibold" style={{ borderRight: '1px solid black' }}>납 기 일</td>
                  <td className="px-2 py-1" style={{ borderRight: '1px solid black' }}>{formatDate(workOrder.dueDate)}</td>
                  <td className="text-center bg-gray-100 py-1 font-semibold" style={{ borderRight: '1px solid black' }}>규 격</td>
                  <td className="px-2 py-1 font-bold text-red-600">{workOrder.spec || `W${workOrder.width || '-'} × H${workOrder.height || '-'}`}</td>
                </tr>
              </tbody>
            </table>

            {/* 작업품목 목록 */}
            {workItems.length > 0 && (
              <table className="w-full border-collapse mb-2" style={{ fontSize: '8px', border: '2px solid black' }}>
                <thead>
                  <tr className="bg-blue-50">
                    <th className="border border-black py-1 px-1" style={{ width: '25px' }}>No</th>
                    <th className="border border-black py-1 px-1">품목명</th>
                    <th className="border border-black py-1 px-1">층/부호</th>
                    <th className="border border-black py-1 px-1">규격</th>
                    <th className="border border-black py-1 px-1 bg-yellow-100" style={{ width: '40px' }}>수량</th>
                    <th className="border border-black py-1 px-1" style={{ width: '50px' }}>상태</th>
                  </tr>
                </thead>
                <tbody>
                  {workItems.slice(0, 8).map((item, idx) => (
                    <tr key={item.id || idx}>
                      <td className="border border-black py-1 px-1 text-center">{idx + 1}</td>
                      <td className="border border-black py-1 px-1">{item.productName}</td>
                      <td className="border border-black py-1 px-1 text-center">{item.floor}/{item.location}</td>
                      <td className="border border-black py-1 px-1 text-center">{item.spec}</td>
                      <td className="border border-black py-1 px-1 text-center bg-yellow-50 font-bold">{item.qty}</td>
                      <td className="border border-black py-1 px-1 text-center">
                        <span className={`text-xs ${item.itemStatus === '완료' ? 'text-green-600' : item.itemStatus === '진행중' ? 'text-blue-600' : 'text-gray-500'}`}>
                          {item.itemStatus || '대기'}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}

            {/* 절곡 공정: 전개도 상세 */}
            {docCode === 'WL-FLD' && (
              <>
                <div className="text-sm font-bold mb-1 mt-3 px-1" style={{ backgroundColor: '#FFA500' }}>전개도 상세정보</div>
                <table className="w-full border-collapse mb-2" style={{ fontSize: '8px', border: '2px solid black' }}>
                  <thead>
                    <tr className="bg-orange-50">
                      <th className="border border-black py-1 px-1" style={{ width: '50px' }}>품목코드</th>
                      <th className="border border-black py-1 px-1">품목명</th>
                      <th className="border border-black py-1 px-1">재질</th>
                      <th className="border border-black py-1 px-1" style={{ width: '50px' }}>전개폭</th>
                      <th className="border border-black py-1 px-1" style={{ width: '50px' }}>길이</th>
                      <th className="border border-black py-1 px-1" style={{ width: '35px' }}>수량</th>
                      <th className="border border-black py-1 px-1" style={{ width: '40px' }}>중량</th>
                      <th className="border border-black py-1 px-1">전개치수</th>
                      <th className="border border-black py-1 px-1" style={{ width: '70px' }}>전개도</th>
                    </tr>
                  </thead>
                  <tbody>
                    {bendingParts.map((part, idx) => (
                      <tr key={idx}>
                        <td className="border border-black py-1 px-1 font-mono text-blue-600">{part.itemCode}</td>
                        <td className="border border-black py-1 px-1 font-medium">{part.itemName}</td>
                        <td className="border border-black py-1 px-1 text-center">{part.material}</td>
                        <td className="border border-black py-1 px-1 text-center">{part.totalWidth}</td>
                        <td className="border border-black py-1 px-1 text-center">{part.length}</td>
                        <td className="border border-black py-1 px-1 text-center font-bold bg-yellow-50">{part.qty}</td>
                        <td className="border border-black py-1 px-1 text-center">{part.weight}kg</td>
                        <td className="border border-black py-1 px-1 font-mono text-xs">{part.dimensions}</td>
                        <td className="border border-black py-0.5 px-0.5">
                          <svg viewBox="0 0 100 50" className="w-full h-6">{renderBendingSvg(part.svgType)}</svg>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* 절곡 상세 입력값 */}
                <div className="text-sm font-bold mb-1 px-1" style={{ backgroundColor: '#FFA500' }}>절곡 작업 상세</div>
                <table className="w-full border-collapse mb-2" style={{ fontSize: '8px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold" style={{ width: '20%' }}>가이드레일 (벽면형)</td>
                      <td className="border border-black py-1 px-2" style={{ width: '30%' }}>120·70 / 수량: {workOrder.guideRailQty || 4}개</td>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold" style={{ width: '20%' }}>가이드레일 (측면형)</td>
                      <td className="border border-black py-1 px-2">80·70 / 수량: {workOrder.sideGuideQty || 2}개</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">하단마감재 (스크린)</td>
                      <td className="border border-black py-1 px-2">SUS: {workOrder.bottomSusQty || 2}EA / EGI: {workOrder.bottomEgiQty || 2}EA</td>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">하단마감재 (철재)</td>
                      <td className="border border-black py-1 px-2">SUS: {workOrder.steelSusQty || 0}EA / EGI: {workOrder.steelEgiQty || 2}EA</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">케이스</td>
                      <td className="border border-black py-1 px-2">수량: {workOrder.caseQty || 1}EA / 규격: W{workOrder.caseWidth || 3000}</td>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">연기차단재</td>
                      <td className="border border-black py-1 px-2">수량: {workOrder.smokeBlockQty || 4}EA</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-1 px-2 bg-orange-100 font-bold">생산량 합계</td>
                      <td colSpan="3" className="border border-black py-1 px-2">
                        <span className="font-bold">SUS: {workOrder.totalSus || 15}kg</span>
                        <span className="mx-4">|</span>
                        <span className="font-bold text-green-700">EGI: {workOrder.totalEgi || 28}kg</span>
                        <span className="mx-4">|</span>
                        <span className="font-bold text-blue-700">총계: {(workOrder.totalSus || 15) + (workOrder.totalEgi || 28)}kg</span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </>
            )}

            {/* 스크린 공정: 작업내역 */}
            {docCode === 'WL-SCR' && (
              <>
                <div className="text-sm font-bold mb-1 mt-2 px-1" style={{ backgroundColor: '#FFFF00' }}>스크린 작업내역</div>
                <table className="w-full border-collapse mb-2" style={{ fontSize: '8px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold" style={{ width: '20%' }}>원단 유형</td>
                      <td className="border border-black py-1 px-2">{workOrder.fabricType || '방화 스크린'}</td>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold" style={{ width: '15%' }}>원단 폭</td>
                      <td className="border border-black py-1 px-2">{workOrder.fabricWidth || 1016}mm</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">원단절단</td>
                      <td className="border border-black py-1 px-2">{workOrder.cuttingQty || workOrder.totalQty || 0} EA</td>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">미싱</td>
                      <td className="border border-black py-1 px-2">{workOrder.sewingQty || workOrder.totalQty || 0} EA</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">앤드락 작업</td>
                      <td className="border border-black py-1 px-2">{workOrder.endlockQty || workOrder.totalQty || 0} EA</td>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">포장</td>
                      <td className="border border-black py-1 px-2">{workOrder.packingQty || workOrder.completedQty || 0} EA</td>
                    </tr>
                  </tbody>
                </table>
              </>
            )}

            {/* 슬랫 공정: 작업내역 */}
            {docCode === 'WL-SLT' && (
              <>
                <div className="text-sm font-bold mb-1 mt-2 px-1" style={{ backgroundColor: '#90EE90' }}>슬랫 작업내역</div>
                <table className="w-full border-collapse mb-2" style={{ fontSize: '8px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold" style={{ width: '20%' }}>코일 유형</td>
                      <td className="border border-black py-1 px-2">{workOrder.coilType || '슬랫 코일'}</td>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold" style={{ width: '15%' }}>색상</td>
                      <td className="border border-black py-1 px-2">{workOrder.coilColor || '백색'}</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">코일절단</td>
                      <td className="border border-black py-1 px-2">{workOrder.coilCuttingQty || workOrder.totalQty || 0} EA</td>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">미미작업</td>
                      <td className="border border-black py-1 px-2">{workOrder.mimiQty || workOrder.totalQty || 0} EA</td>
                    </tr>
                    <tr>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">총 중량</td>
                      <td className="border border-black py-1 px-2 font-bold">{workOrder.totalWeight || 0} kg</td>
                      <td className="border border-black py-1 px-2 bg-gray-100 font-semibold">양품</td>
                      <td className="border border-black py-1 px-2 font-bold text-green-600">{workOrder.goodQty || workOrder.completedQty || 0} EA</td>
                    </tr>
                  </tbody>
                </table>
              </>
            )}

            {/* 하단 요약 */}
            <table className="w-full border-collapse mt-2" style={{ fontSize: '9px', border: '2px solid black' }}>
              <tbody>
                <tr>
                  <td className="text-center bg-gray-200 py-1.5 font-bold" style={{ width: '15%', borderRight: '1px solid black' }}>지시수량</td>
                  <td className="px-2 py-1.5 text-center font-bold text-blue-600" style={{ width: '18%', borderRight: '1px solid black' }}>{workOrder.totalQty || workItems.length} EA</td>
                  <td className="text-center bg-gray-200 py-1.5 font-bold" style={{ width: '15%', borderRight: '1px solid black' }}>완료수량</td>
                  <td className="px-2 py-1.5 text-center font-bold text-green-600" style={{ width: '18%', borderRight: '1px solid black' }}>{workOrder.completedQty || 0} EA</td>
                  <td className="text-center bg-gray-200 py-1.5 font-bold" style={{ width: '12%', borderRight: '1px solid black' }}>진행률</td>
                  <td className="px-2 py-1.5 text-center font-bold" style={{ width: '22%' }}>
                    {workOrder.totalQty > 0 ? Math.round((workOrder.completedQty || 0) / workOrder.totalQty * 100) : 0}%
                  </td>
                </tr>
              </tbody>
            </table>

            {/* 특이사항 */}
            <table className="w-full border-collapse mt-1" style={{ fontSize: '9px', border: '2px solid black' }}>
              <tbody>
                <tr>
                  <td className="text-center bg-gray-200 py-1 font-bold" style={{ width: '12%', borderRight: '1px solid black' }}>특이사항</td>
                  <td className="px-2 py-2" style={{ minHeight: '40px' }}>{workOrder.note || workOrder.remarks || '-'}</td>
                </tr>
              </tbody>
            </table>

            {/* 투입자재 정보 */}
            {(workOrder.materials?.length > 0 || workOrder.materialInputs?.length > 0) && (
              <table className="w-full border-collapse mt-2" style={{ fontSize: '8px', border: '2px solid black' }}>
                <thead>
                  <tr className="bg-green-100">
                    <th colSpan="5" className="border border-black py-1 px-2 text-center font-bold">투입자재</th>
                  </tr>
                  <tr className="bg-gray-50">
                    <th className="border border-black py-1 px-1">자재코드</th>
                    <th className="border border-black py-1 px-1">자재명</th>
                    <th className="border border-black py-1 px-1">LOT번호</th>
                    <th className="border border-black py-1 px-1">수량</th>
                    <th className="border border-black py-1 px-1">단위</th>
                  </tr>
                </thead>
                <tbody>
                  {(workOrder.materials || workOrder.materialInputs || []).map((mat, idx) => (
                    <tr key={idx}>
                      <td className="border border-black py-1 px-1 font-mono">{mat.materialCode || mat.code || '-'}</td>
                      <td className="border border-black py-1 px-1">{mat.materialName || mat.name}</td>
                      <td className="border border-black py-1 px-1 font-mono">{mat.lotNo || '-'}</td>
                      <td className="border border-black py-1 px-1 text-center">{mat.usedQty || mat.qty}</td>
                      <td className="border border-black py-1 px-1 text-center">{mat.unit || 'EA'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

// 공정 상세
const ProcessDetail = ({ process, workOrders = [], onNavigate, onBack }) => {
  // 문서양식 미리보기 모달 상태
  const [showTemplatePreview, setShowTemplatePreview] = useState(false);

  if (!process) return null;

  // 작업일지 양식 코드 → 이름 매핑 (문서양식관리에서 동적 생성)
  const workSheetNameMap = (documentTemplateConfig.documentTypes || [])
    .filter(doc => doc.code && doc.code.startsWith('WL-'))
    .reduce((acc, doc) => {
      acc[doc.code] = doc.name;
      return acc;
    }, {});

  return (
    <div className="space-y-6">
      {/* 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <GitBranch className="w-6 h-6 text-blue-500" />
          공정 상세
        </h1>
        <div className="flex items-center justify-end gap-2">
          <button onClick={onBack} className="flex items-center gap-1 px-4 py-2 border rounded hover:bg-gray-50">
            <List className="w-4 h-4" /> 목록
          </button>
          <button onClick={() => onNavigate('process-edit', process)} className="flex items-center gap-1 px-4 py-2 bg-blue-600 text-white rounded">
            <Edit className="w-4 h-4" /> 수정
          </button>
        </div>
      </div>

      {/* 기본 정보 */}
      <Card title="기본 정보">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div>
            <label className="text-sm text-gray-500">공정코드</label>
            <p className="font-mono font-medium">{process.processCode}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">공정명</label>
            <p className="font-medium">{process.processName}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">공정구분</label>
            <p><StatusBadge status={process.processType} /></p>
          </div>
          <div>
            <label className="text-sm text-gray-500">담당부서</label>
            <p className="font-medium">{process.department}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">작업일지 양식</label>
            <div className="flex items-center gap-2">
              <p className="font-medium">{workSheetNameMap[process.workSheetType] || process.workSheetType || '-'}</p>
              {process.workSheetType && (
                <button
                  onClick={() => setShowTemplatePreview(true)}
                  className="px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded hover:bg-blue-200"
                >
                  양식 보기
                </button>
              )}
            </div>
          </div>
        </div>
      </Card>

      {/* 등록 정보 */}
      <Card title="등록 정보">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div>
            <label className="text-sm text-gray-500">등록일</label>
            <p className="font-medium">{process.createdAt}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">최종수정일</label>
            <p className="font-medium">{process.updatedAt}</p>
          </div>
        </div>
      </Card>

      {/* 자동 분류 규칙 */}
      <Card title={
        <div className="flex items-center gap-2">
          <span>자동 분류 규칙</span>
          {(process.autoClassifyRules?.length || 0) > 0 && (
            <span className="px-2 py-0.5 bg-purple-100 text-purple-700 rounded-full text-xs font-medium">
              {process.autoClassifyRules.length}개
            </span>
          )}
        </div>
      }>
        {process.autoClassifyRules && process.autoClassifyRules.length > 0 ? (
          <div className="space-y-2">
            {process.autoClassifyRules.map((rule, idx) => {
              const fieldNames = {
                itemName: '품목명',
                itemCode: '품목코드',
                category: '품목분류',
                material: '원자재',
                size: '규격',
              };
              const operatorNames = {
                contains: '포함',
                equals: '같음',
                startsWith: '시작',
                endsWith: '끝남',
              };
              return (
                <div key={rule.id || idx} className="flex items-center gap-2 p-3 bg-purple-50 rounded-lg border border-purple-100">
                  <span className="w-6 h-6 bg-purple-500 text-white rounded-full flex items-center justify-center text-xs font-bold">{idx + 1}</span>
                  <span className="text-sm">
                    <span className="font-medium text-purple-700">{fieldNames[rule.field] || rule.field}</span>
                    <span className="text-gray-500"> 이(가) </span>
                    <span className="font-medium text-purple-700">"{rule.value}"</span>
                    <span className="text-gray-500"> 을(를) </span>
                    <span className="font-medium text-purple-700">{operatorNames[rule.operator] || rule.operator}</span>
                  </span>
                </div>
              );
            })}
            <p className="text-xs text-gray-500 mt-2">
              위 조건을 만족하는 품목은 자동으로 이 공정에 분류됩니다.
            </p>
          </div>
        ) : (
          <div className="text-center py-8 text-gray-400">
            <GitBranch className="w-10 h-10 mx-auto mb-2 opacity-30" />
            <p className="text-sm">등록된 자동 분류 규칙이 없습니다</p>
          </div>
        )}
      </Card>

      {/* 세부 작업단계 */}
      <Card title="세부 작업단계">
        {process.workSteps && process.workSteps.length > 0 ? (
          <div className="flex flex-wrap gap-2">
            {process.workSteps.map((step, idx) => (
              <div key={idx} className={`flex items-center gap-2 px-3 py-2 rounded-lg ${step === '중간검사' ? 'bg-amber-100' : 'bg-gray-100'}`}>
                <span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-medium ${step === '중간검사' ? 'bg-amber-500 text-white' : 'bg-blue-500 text-white'}`}>
                  {idx + 1}
                </span>
                <span className="font-medium">{step}</span>
                {step === '중간검사' && <CheckCircle className="w-4 h-4 text-amber-600" />}
                {idx < process.workSteps.length - 1 && <ChevronRight className="w-4 h-4 text-gray-400 ml-2" />}
              </div>
            ))}
          </div>
        ) : (
          <p className="text-gray-500">등록된 작업단계가 없습니다</p>
        )}
      </Card>

      {/* 작업 정보 */}
      {(process.requiredWorkers || process.equipmentInfo || process.description) && (
        <Card title="작업 정보">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {process.requiredWorkers && (
              <div>
                <label className="text-sm text-gray-500">필요인원</label>
                <p className="font-medium">{process.requiredWorkers}명</p>
              </div>
            )}
            {process.equipmentInfo && (
              <div>
                <label className="text-sm text-gray-500">설비정보</label>
                <p className="font-medium">{process.equipmentInfo}</p>
              </div>
            )}
            {process.description && (
              <div>
                <label className="text-sm text-gray-500">설명</label>
                <p className="text-gray-700">{process.description}</p>
              </div>
            )}
          </div>
        </Card>
      )}

      {/* 문서양식 미리보기 모달 */}
      {showTemplatePreview && process.workSheetType && (
        <DocumentTemplatePreviewModal
          docCode={process.workSheetType}
          onClose={() => setShowTemplatePreview(false)}
        />
      )}
    </div>
  );
};

// ============ 품질기준관리 ============

// 품질기준 샘플 데이터
const initialInspectionStandards = [
  // 입고검사 기준
  {
    id: 1,
    code: 'QS-INC-001',
    name: '스크린 원단 입고검사',
    inspectionType: '입고검사',
    targetType: '자재',
    targetCode: 'SCR-MAT-001',
    targetName: '스크린 원단 (백색)',
    inspectionItems: [
      { id: 1, item: '외관검사', method: '육안검사', standard: '오염, 찢어짐, 변색 없을 것', unit: '-', min: null, max: null, critical: true },
      { id: 2, item: '폭 치수', method: '줄자 측정', standard: '규격 ±5mm 이내', unit: 'mm', min: 2395, max: 2405, critical: true },
      { id: 3, item: '두께', method: '두께게이지', standard: '0.3±0.02mm', unit: 'mm', min: 0.28, max: 0.32, critical: false },
      { id: 4, item: '인장강도', method: '인장시험기', standard: '≥15 N/cm', unit: 'N/cm', min: 15, max: null, critical: true },
    ],
    samplingRule: 'AQL 2.5, 일반검사 Level II',
    samplingQty: '로트당 5개 샘플',
    frequency: '입고시 전수',
    responsibleTeam: '품질팀',
    status: '사용',
    createdAt: '2025-01-15',
    updatedAt: '2025-02-01',
  },
  {
    id: 2,
    code: 'QS-INC-002',
    name: '슬랫 코일 입고검사',
    inspectionType: '입고검사',
    targetType: '자재',
    targetCode: 'SLT-MAT-001',
    targetName: '슬랫 코일',
    inspectionItems: [
      { id: 1, item: '외관검사', method: '육안검사', standard: '스크래치, 녹, 변형 없을 것', unit: '-', min: null, max: null, critical: true },
      { id: 2, item: '폭 치수', method: '버니어캘리퍼스', standard: '규격 ±0.5mm 이내', unit: 'mm', min: 79.5, max: 80.5, critical: true },
      { id: 3, item: '두께', method: '마이크로미터', standard: '0.5±0.05mm', unit: 'mm', min: 0.45, max: 0.55, critical: true },
      { id: 4, item: '도장상태', method: '접착테스트', standard: '박리 없을 것', unit: '-', min: null, max: null, critical: false },
    ],
    samplingRule: 'AQL 1.0, 일반검사 Level II',
    samplingQty: '로트당 3개 샘플',
    frequency: '입고시 전수',
    responsibleTeam: '품질팀',
    status: '사용',
    createdAt: '2025-01-15',
    updatedAt: '2025-02-01',
  },
  // 중간검사 기준
  {
    id: 3,
    code: 'QS-PRC-001',
    name: '스크린 공정 중간검사',
    inspectionType: '중간검사',
    targetType: '공정',
    targetCode: 'PROC-SCR',
    targetName: '스크린 공정',
    inspectionItems: [
      { id: 1, item: '재단 치수', method: '줄자 측정', standard: '도면 치수 ±10mm', unit: 'mm', min: -10, max: 10, critical: true },
      { id: 2, item: '미싱 상태', method: '육안검사', standard: '스티치 간격 균일, 풀림 없음', unit: '-', min: null, max: null, critical: true },
      { id: 3, item: '앤드락 결합', method: '손검사', standard: '확실한 체결, 유격 없음', unit: '-', min: null, max: null, critical: true },
      { id: 4, item: '작동검사', method: '수동 작동', standard: '부드러운 승하강', unit: '-', min: null, max: null, critical: true },
    ],
    samplingRule: '전수검사',
    samplingQty: '생산품 전량',
    frequency: '포장 전',
    responsibleTeam: '품질팀',
    status: '사용',
    createdAt: '2025-01-15',
    updatedAt: '2025-02-01',
  },
  {
    id: 4,
    code: 'QS-PRC-002',
    name: '슬랫 공정 중간검사',
    inspectionType: '중간검사',
    targetType: '공정',
    targetCode: 'PROC-SLT',
    targetName: '슬랫 공정',
    inspectionItems: [
      { id: 1, item: '절단 치수', method: '버니어캘리퍼스', standard: '도면 치수 ±1mm', unit: 'mm', min: -1, max: 1, critical: true },
      { id: 2, item: '성형 상태', method: '육안검사', standard: '곡률 균일, 변형 없음', unit: '-', min: null, max: null, critical: true },
      { id: 3, item: '미미 결합', method: '손검사', standard: '확실한 체결', unit: '-', min: null, max: null, critical: true },
      { id: 4, item: '표면 상태', method: '육안검사', standard: '스크래치, 찍힘 없음', unit: '-', min: null, max: null, critical: false },
    ],
    samplingRule: '전수검사',
    samplingQty: '생산품 전량',
    frequency: '포장 전',
    responsibleTeam: '품질팀',
    status: '사용',
    createdAt: '2025-01-15',
    updatedAt: '2025-02-01',
  },
  {
    id: 5,
    code: 'QS-PRC-003',
    name: '절곡 공정 중간검사',
    inspectionType: '중간검사',
    targetType: '공정',
    targetCode: 'PROC-BND',
    targetName: '절곡 공정',
    inspectionItems: [
      { id: 1, item: '절단 치수', method: '줄자/버니어', standard: '도면 치수 ±2mm', unit: 'mm', min: -2, max: 2, critical: true },
      { id: 2, item: '절곡 각도', method: '각도기', standard: '90° ±1°', unit: '°', min: 89, max: 91, critical: true },
      { id: 3, item: '용접 상태', method: '육안검사', standard: '기공, 균열 없음', unit: '-', min: null, max: null, critical: true },
      { id: 4, item: '도장 상태', method: '접착테스트', standard: '박리 없음, 두께 균일', unit: '-', min: null, max: null, critical: false },
    ],
    samplingRule: '전수검사',
    samplingQty: '생산품 전량',
    frequency: '포장 전',
    responsibleTeam: '품질팀',
    status: '사용',
    createdAt: '2025-01-15',
    updatedAt: '2025-02-01',
  },
  // 제품검사 기준
  {
    id: 6,
    code: 'QS-FIN-001',
    name: '스크린 셔터 제품검사',
    inspectionType: '제품검사',
    targetType: '품목',
    targetCode: 'SCR-001',
    targetName: '스크린 셔터 (표준형)',
    inspectionItems: [
      { id: 1, item: '외관검사', method: '육안검사', standard: '오염, 손상, 변형 없음', unit: '-', min: null, max: null, critical: true },
      { id: 2, item: '완제품 치수', method: '줄자 측정', standard: '주문 치수 ±15mm', unit: 'mm', min: -15, max: 15, critical: true },
      { id: 3, item: '작동검사', method: '수동 작동', standard: '승하강 원활, 이음 없음', unit: '-', min: null, max: null, critical: true },
      { id: 4, item: '부속품 확인', method: '체크리스트', standard: '부속품 전량 포함', unit: '-', min: null, max: null, critical: true },
      { id: 5, item: '포장상태', method: '육안검사', standard: '포장 완전, 라벨 부착', unit: '-', min: null, max: null, critical: false },
    ],
    samplingRule: '전수검사',
    samplingQty: '출하품 전량',
    frequency: '출하 전',
    responsibleTeam: '품질팀',
    status: '사용',
    createdAt: '2025-01-15',
    updatedAt: '2025-02-01',
  },
  {
    id: 7,
    code: 'QS-FIN-002',
    name: '슬랫 셔터 제품검사',
    inspectionType: '제품검사',
    targetType: '품목',
    targetCode: 'SLT-001',
    targetName: '슬랫 셔터',
    inspectionItems: [
      { id: 1, item: '외관검사', method: '육안검사', standard: '오염, 손상, 변형 없음', unit: '-', min: null, max: null, critical: true },
      { id: 2, item: '완제품 치수', method: '줄자 측정', standard: '주문 치수 ±10mm', unit: 'mm', min: -10, max: 10, critical: true },
      { id: 3, item: '작동검사', method: '수동 작동', standard: '승하강 원활, 소음 없음', unit: '-', min: null, max: null, critical: true },
      { id: 4, item: '잠금장치', method: '잠금 테스트', standard: '확실한 잠금', unit: '-', min: null, max: null, critical: true },
      { id: 5, item: '부속품 확인', method: '체크리스트', standard: '부속품 전량 포함', unit: '-', min: null, max: null, critical: true },
    ],
    samplingRule: '전수검사',
    samplingQty: '출하품 전량',
    frequency: '출하 전',
    responsibleTeam: '품질팀',
    status: '사용',
    createdAt: '2025-01-15',
    updatedAt: '2025-02-01',
  },
];

// 품질기준 목록
const InspectionStandardList = ({ standards = initialInspectionStandards, onNavigate }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [showPanel, setShowPanel] = useState(false);
  const [panelMode, setPanelMode] = useState('create');
  const [selectedStandard, setSelectedStandard] = useState(null);
  const [localStandards, setLocalStandards] = useState(standards);

  const tabs = [
    { id: 'all', label: '전체', count: localStandards.length },
    { id: '입고검사', label: '입고검사', count: localStandards.filter(s => s.inspectionType === '입고검사').length },
    { id: '중간검사', label: '중간검사', count: localStandards.filter(s => s.inspectionType === '중간검사').length },
    { id: '제품검사', label: '제품검사', count: localStandards.filter(s => s.inspectionType === '제품검사').length },
  ];

  const filteredStandards = localStandards.filter(s => {
    const matchesSearch = s.name.includes(search) || s.code.includes(search) || s.targetName.includes(search);
    const matchesTab = activeTab === 'all' || s.inspectionType === activeTab;
    return matchesSearch && matchesTab;
  });

  const handleOpenDetail = (standard) => {
    setSelectedStandard(standard);
    setPanelMode('detail');
    setShowPanel(true);
  };

  const handleCreate = () => {
    setSelectedStandard(null);
    setPanelMode('create');
    setShowPanel(true);
  };

  const getInspectionTypeBadge = (type) => {
    const styles = {
      '입고검사': 'bg-blue-100 text-blue-700',
      '중간검사': 'bg-yellow-100 text-yellow-700',
      '제품검사': 'bg-green-100 text-green-700',
    };
    return styles[type] || 'bg-gray-100 text-gray-700';
  };

  return (
    <div className="space-y-6">
      {/* 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <ShieldCheck className="w-6 h-6 text-blue-500" />
          검사기준 목록
        </h1>
        <div className="flex items-center justify-end">
          <Button variant="primary" onClick={handleCreate}>
            <Plus className="w-4 h-4" /> 검사기준 등록
          </Button>
        </div>
      </div>

      {/* 검색 및 필터 */}
      <div className="flex items-center gap-4">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder="기준명, 코드, 대상 검색..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>
      </div>

      {/* 탭 */}
      <div className="flex gap-2 border-b">
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${activeTab === tab.id
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
          >
            {tab.label} ({tab.count})
          </button>
        ))}
      </div>

      {/* 목록 */}
      <Card>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">기준코드</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">기준명</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">검사유형</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">대상</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">검사항목</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">샘플링</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {filteredStandards.map(standard => (
                <tr
                  key={standard.id}
                  onClick={() => handleOpenDetail(standard)}
                  className="hover:bg-gray-50 cursor-pointer"
                >
                  <td className="px-4 py-3 text-sm font-mono text-blue-600">{standard.code}</td>
                  <td className="px-4 py-3 text-sm font-medium text-gray-900">{standard.name}</td>
                  <td className="px-4 py-3 text-sm">
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${getInspectionTypeBadge(standard.inspectionType)}`}>
                      {standard.inspectionType}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-600">
                    <div>
                      <p className="font-medium">{standard.targetName}</p>
                      <p className="text-xs text-gray-400 font-mono">{standard.targetCode}</p>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-sm text-center">
                    <span className="inline-flex items-center px-2 py-1 rounded bg-gray-100 text-gray-700 text-xs font-medium">
                      {standard.inspectionItems.length}개 항목
                    </span>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-600">{standard.samplingQty}</td>
                  <td className="px-4 py-3 text-center">
                    <StatusBadge status={standard.status} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      {/* 통계 카드 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card>
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-lg bg-blue-100 flex items-center justify-center">
              <Clipboard className="w-6 h-6 text-blue-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">입고검사 기준</p>
              <p className="text-2xl font-bold">{localStandards.filter(s => s.inspectionType === '입고검사').length}건</p>
            </div>
          </div>
        </Card>
        <Card>
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-lg bg-yellow-100 flex items-center justify-center">
              <Settings className="w-6 h-6 text-yellow-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">중간검사 기준</p>
              <p className="text-2xl font-bold">{localStandards.filter(s => s.inspectionType === '중간검사').length}건</p>
            </div>
          </div>
        </Card>
        <Card>
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-lg bg-green-100 flex items-center justify-center">
              <CheckCircle className="w-6 h-6 text-green-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">제품검사 기준</p>
              <p className="text-2xl font-bold">{localStandards.filter(s => s.inspectionType === '제품검사').length}건</p>
            </div>
          </div>
        </Card>
        <Card>
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-lg bg-purple-100 flex items-center justify-center">
              <AlertCircle className="w-6 h-6 text-purple-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">치명적 검사항목</p>
              <p className="text-2xl font-bold">
                {localStandards.reduce((sum, s) => sum + s.inspectionItems.filter(i => i.critical).length, 0)}개
              </p>
            </div>
          </div>
        </Card>
      </div>

      {/* 상세/등록 패널 */}
      {showPanel && (
        <InspectionStandardPanel
          mode={panelMode}
          standard={selectedStandard}
          onClose={() => setShowPanel(false)}
          onSave={(data) => {
            if (panelMode === 'create') {
              setLocalStandards(prev => [...prev, {
                ...data,
                id: Date.now(),
                createdAt: new Date().toISOString().split('T')[0],
                updatedAt: new Date().toISOString().split('T')[0],
              }]);
            } else if (panelMode === 'edit') {
              setLocalStandards(prev => prev.map(s => s.id === data.id ? { ...s, ...data, updatedAt: new Date().toISOString().split('T')[0] } : s));
            }
            setShowPanel(false);
          }}
          onEdit={() => setPanelMode('edit')}
        />
      )}
    </div>
  );
};

// ============================================================
// 생산기준관리 컴포넌트 (MasterConfigurationManager 기반)
// ============================================================
const ProductionMasterManagement = ({ onNavigate }) => {
  return <MasterConfigurationManager configId="production" onNavigate={onNavigate} />;
};

// ============================================================
// 출고기준관리 컴포넌트 (MasterConfigurationManager 기반)
// ============================================================
const OutboundMasterManagement = ({ onNavigate }) => {
  return <MasterConfigurationManager configId="outbound" onNavigate={onNavigate} />;
};

// ============================================================
// 생산기준관리 컴포넌트 (구버전 - 레거시 참조용)
// ============================================================
const ProductionMasterManagementLegacy = ({ onNavigate }) => {
  const [activeTab, setActiveTab] = useState('work-order');
  const [searchTerm, setSearchTerm] = useState('');

  // 탭 정의
  const tabs = [
    { id: 'work-order', label: '작업지시 기준', icon: ClipboardList },
    { id: 'worker-screen', label: '작업자화면 기준', icon: User },
    { id: 'equipment', label: '설비 기준', icon: Settings },
    { id: 'work-line', label: '라인/작업장 기준', icon: Factory },
    { id: 'bom', label: 'BOM 기준', icon: Layers },
  ];

  // 샘플 데이터: 작업지시 유형
  const workOrderTypes = [
    { id: 1, code: 'WO-STD', name: '표준 작업지시', description: '일반적인 생산 작업지시', autoCreate: true, status: '활성' },
    { id: 2, code: 'WO-URG', name: '긴급 작업지시', description: '긴급 생산 요청 시 사용', autoCreate: false, status: '활성' },
    { id: 3, code: 'WO-RPR', name: '재작업 지시', description: '불량 재작업 시 사용', autoCreate: false, status: '활성' },
    { id: 4, code: 'WO-SMP', name: '샘플 작업지시', description: '샘플 제작 시 사용', autoCreate: true, status: '활성' },
  ];

  // 샘플 데이터: 작업자화면 기준
  const workerScreenSettings = [
    { id: 1, code: 'WS-001', name: '기본 작업화면', description: '일반 작업자용 기본 화면', showProgress: true, showQuality: true, status: '활성' },
    { id: 2, code: 'WS-002', name: '검사원 화면', description: '검사원용 품질 중심 화면', showProgress: false, showQuality: true, status: '활성' },
    { id: 3, code: 'WS-003', name: '조장 화면', description: '조장용 관리 화면', showProgress: true, showQuality: true, status: '활성' },
  ];

  // 샘플 데이터: 설비 기준
  const equipmentMasters = [
    { id: 1, code: 'EQ-001', name: '포밍기 #1', type: '성형설비', location: 'A동 1라인', capacity: '200ea/h', status: '가동중' },
    { id: 2, code: 'EQ-002', name: '포밍기 #2', type: '성형설비', location: 'A동 1라인', capacity: '180ea/h', status: '가동중' },
    { id: 3, code: 'EQ-003', name: '절곡기 #1', type: '절곡설비', location: 'B동 2라인', capacity: '150ea/h', status: '점검중' },
    { id: 4, code: 'EQ-004', name: '용접기 #1', type: '용접설비', location: 'C동 3라인', capacity: '100ea/h', status: '가동중' },
    { id: 5, code: 'EQ-005', name: '도장기 #1', type: '도장설비', location: 'D동 4라인', capacity: '50ea/h', status: '가동중' },
  ];

  // 샘플 데이터: 라인/작업장 기준
  const workLineMasters = [
    { id: 1, code: 'LN-001', name: '1라인 (스크린)', type: '생산라인', location: 'A동', capacity: '50ea/일', workers: 5, status: '활성' },
    { id: 2, code: 'LN-002', name: '2라인 (슬랫)', type: '생산라인', location: 'B동', capacity: '40ea/일', workers: 4, status: '활성' },
    { id: 3, code: 'LN-003', name: '3라인 (절곡)', type: '생산라인', location: 'C동', capacity: '60ea/일', workers: 6, status: '활성' },
    { id: 4, code: 'WS-001', name: '조립작업장', type: '작업장', location: 'D동', capacity: '30ea/일', workers: 3, status: '활성' },
    { id: 5, code: 'WS-002', name: '검사작업장', type: '작업장', location: 'D동', capacity: '-', workers: 2, status: '활성' },
  ];

  // 샘플 데이터: BOM 기준
  const bomMasters = [
    { id: 1, code: 'BOM-SH3040', name: '방화셔터 3000×4000', productCode: 'SH3040', revision: 'R1.0', parts: 15, status: '승인' },
    { id: 2, code: 'BOM-SH2530', name: '방화셔터 2500×3000', productCode: 'SH2530', revision: 'R1.0', parts: 12, status: '승인' },
    { id: 3, code: 'BOM-DR2010', name: '방화문 2000×1000', productCode: 'DR2010', revision: 'R2.0', parts: 8, status: '승인' },
    { id: 4, code: 'BOM-SS3535', name: '방연셔터 3500×3500', productCode: 'SS3535', revision: 'R1.1', parts: 18, status: '검토중' },
  ];

  // 현재 탭에 따른 컨텐츠 렌더링
  const renderContent = () => {
    switch (activeTab) {
      case 'work-order':
        return (
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <h3 className="font-medium">작업지시 유형 목록</h3>
              <button className="flex items-center gap-1 px-3 py-1.5 bg-black text-white rounded text-sm">
                <Plus className="w-4 h-4" /> 유형 추가
              </button>
            </div>
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="p-2 text-left border">코드</th>
                  <th className="p-2 text-left border">유형명</th>
                  <th className="p-2 text-left border">설명</th>
                  <th className="p-2 text-center border">자동생성</th>
                  <th className="p-2 text-center border">상태</th>
                </tr>
              </thead>
              <tbody>
                {workOrderTypes.map(item => (
                  <tr key={item.id} className="hover:bg-gray-50">
                    <td className="p-2 border font-mono">{item.code}</td>
                    <td className="p-2 border">{item.name}</td>
                    <td className="p-2 border text-gray-600">{item.description}</td>
                    <td className="p-2 border text-center">{item.autoCreate ? '예' : '아니오'}</td>
                    <td className="p-2 border text-center">
                      <span className="px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs">{item.status}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        );

      case 'worker-screen':
        return (
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <h3 className="font-medium">작업자화면 설정 목록</h3>
              <button className="flex items-center gap-1 px-3 py-1.5 bg-black text-white rounded text-sm">
                <Plus className="w-4 h-4" /> 설정 추가
              </button>
            </div>
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="p-2 text-left border">코드</th>
                  <th className="p-2 text-left border">화면명</th>
                  <th className="p-2 text-left border">설명</th>
                  <th className="p-2 text-center border">진행률표시</th>
                  <th className="p-2 text-center border">품질표시</th>
                  <th className="p-2 text-center border">상태</th>
                </tr>
              </thead>
              <tbody>
                {workerScreenSettings.map(item => (
                  <tr key={item.id} className="hover:bg-gray-50">
                    <td className="p-2 border font-mono">{item.code}</td>
                    <td className="p-2 border">{item.name}</td>
                    <td className="p-2 border text-gray-600">{item.description}</td>
                    <td className="p-2 border text-center">{item.showProgress ? 'O' : 'X'}</td>
                    <td className="p-2 border text-center">{item.showQuality ? 'O' : 'X'}</td>
                    <td className="p-2 border text-center">
                      <span className="px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs">{item.status}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        );

      case 'equipment':
        return (
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <h3 className="font-medium">설비 기준 목록</h3>
              <button className="flex items-center gap-1 px-3 py-1.5 bg-black text-white rounded text-sm">
                <Plus className="w-4 h-4" /> 설비 추가
              </button>
            </div>
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="p-2 text-left border">설비코드</th>
                  <th className="p-2 text-left border">설비명</th>
                  <th className="p-2 text-left border">설비유형</th>
                  <th className="p-2 text-left border">위치</th>
                  <th className="p-2 text-left border">생산능력</th>
                  <th className="p-2 text-center border">상태</th>
                </tr>
              </thead>
              <tbody>
                {equipmentMasters.map(item => (
                  <tr key={item.id} className="hover:bg-gray-50">
                    <td className="p-2 border font-mono">{item.code}</td>
                    <td className="p-2 border">{item.name}</td>
                    <td className="p-2 border">{item.type}</td>
                    <td className="p-2 border">{item.location}</td>
                    <td className="p-2 border">{item.capacity}</td>
                    <td className="p-2 border text-center">
                      <span className={`px-2 py-0.5 rounded text-xs ${item.status === '가동중' ? 'bg-green-100 text-green-800' :
                          item.status === '점검중' ? 'bg-yellow-100 text-yellow-800' :
                            'bg-gray-100 text-gray-800'
                        }`}>{item.status}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        );

      case 'work-line':
        return (
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <h3 className="font-medium">라인/작업장 기준 목록</h3>
              <button className="flex items-center gap-1 px-3 py-1.5 bg-black text-white rounded text-sm">
                <Plus className="w-4 h-4" /> 라인 추가
              </button>
            </div>
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="p-2 text-left border">코드</th>
                  <th className="p-2 text-left border">명칭</th>
                  <th className="p-2 text-left border">유형</th>
                  <th className="p-2 text-left border">위치</th>
                  <th className="p-2 text-left border">생산능력</th>
                  <th className="p-2 text-center border">작업자수</th>
                  <th className="p-2 text-center border">상태</th>
                </tr>
              </thead>
              <tbody>
                {workLineMasters.map(item => (
                  <tr key={item.id} className="hover:bg-gray-50">
                    <td className="p-2 border font-mono">{item.code}</td>
                    <td className="p-2 border">{item.name}</td>
                    <td className="p-2 border">{item.type}</td>
                    <td className="p-2 border">{item.location}</td>
                    <td className="p-2 border">{item.capacity}</td>
                    <td className="p-2 border text-center">{item.workers}명</td>
                    <td className="p-2 border text-center">
                      <span className="px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs">{item.status}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        );

      case 'bom':
        return (
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <h3 className="font-medium">BOM 기준 목록</h3>
              <button className="flex items-center gap-1 px-3 py-1.5 bg-black text-white rounded text-sm">
                <Plus className="w-4 h-4" /> BOM 추가
              </button>
            </div>
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="p-2 text-left border">BOM코드</th>
                  <th className="p-2 text-left border">BOM명</th>
                  <th className="p-2 text-left border">제품코드</th>
                  <th className="p-2 text-left border">리비전</th>
                  <th className="p-2 text-center border">부품수</th>
                  <th className="p-2 text-center border">상태</th>
                </tr>
              </thead>
              <tbody>
                {bomMasters.map(item => (
                  <tr key={item.id} className="hover:bg-gray-50">
                    <td className="p-2 border font-mono">{item.code}</td>
                    <td className="p-2 border">{item.name}</td>
                    <td className="p-2 border font-mono">{item.productCode}</td>
                    <td className="p-2 border">{item.revision}</td>
                    <td className="p-2 border text-center">{item.parts}개</td>
                    <td className="p-2 border text-center">
                      <span className={`px-2 py-0.5 rounded text-xs ${item.status === '승인' ? 'bg-green-100 text-green-800' :
                          item.status === '검토중' ? 'bg-yellow-100 text-yellow-800' :
                            'bg-gray-100 text-gray-800'
                        }`}>{item.status}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <Factory className="w-6 h-6 text-blue-500" />
          생산기준관리
        </h1>
        <div className="flex items-center justify-end">
          <button
            onClick={() => onNavigate('master')}
            className="px-4 py-2 border rounded hover:bg-gray-50"
          >
            목록으로
          </button>
        </div>
      </div>

      {/* 탭 네비게이션 */}
      <div className="flex border-b">
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`flex items-center gap-2 px-4 py-2 border-b-2 -mb-px ${activeTab === tab.id
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
          >
            <tab.icon className="w-4 h-4" />
            {tab.label}
          </button>
        ))}
      </div>

      {/* 검색 */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
        <input
          type="text"
          placeholder="검색어를 입력하세요..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="w-full pl-10 pr-4 py-2 border rounded-lg"
        />
      </div>

      {/* 컨텐츠 */}
      <div className="bg-white rounded-lg border p-4">
        {renderContent()}
      </div>
    </div>
  );
};

// ============================================================
// 번호기준 관리 컴포넌트
// ============================================================
const NumberRuleManagement = ({ onNavigate }) => {
  const [showHelp, setShowHelp] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');

  // 번호기준 목록 - localStorage에서 불러오기 (없으면 기본값 사용)
  const [numberRules, setNumberRules] = useState(() => loadNumberRules());

  // 규칙 변경 시 localStorage에 자동 저장
  useEffect(() => {
    saveNumberRules(numberRules);
  }, [numberRules]);

  const [showModal, setShowModal] = useState(false);
  const [editingRule, setEditingRule] = useState(null);
  const [formData, setFormData] = useState({
    name: '',
    target: '',
    prefix: 'KD-',
    dateFormat: 'YYMMDD',
    seqDigits: 2,
    separator: '-',
    resetCycle: 'daily',
    status: '활성',
    description: '',
  });

  // 적용대상 목록 및 템플릿 - numberRuleConfig에서 import
  const targetTemplates = numberTargetTemplates;

  // 날짜 형식 옵션 - numberRuleConfig에서 import
  const dateFormats = numberDateFormats;

  // 순번 자릿수 옵션
  const seqDigitOptions = [
    { value: 2, label: '2자리 (01~99)' },
    { value: 3, label: '3자리 (001~999)' },
    { value: 4, label: '4자리 (0001~9999)' },
  ];

  // 리셋 주기 옵션 - numberRuleConfig에서 import한 것 사용
  // (resetCycleOptions는 이미 import됨)

  // 구분자 옵션
  const separatorOptions = [
    { value: '-', label: '하이픈 (-)' },
    { value: '_', label: '언더스코어 (_)' },
    { value: '', label: '없음' },
  ];

  // 번호 미리보기 생성 - formatDateCode 함수 사용
  const generatePreview = (data) => {
    const dateStr = formatDateCode(new Date(), data.dateFormat);
    const seq = '01'.padStart(data.seqDigits, '0');
    const sep = data.separator;

    if (data.dateFormat === 'NONE' || !dateStr) {
      return data.prefix ? `${data.prefix}${sep}${seq}` : seq;
    }
    return data.prefix ? `${data.prefix}${sep}${dateStr}${sep}${seq}` : `${dateStr}${sep}${seq}`;
  };

  // 적용대상 선택 시 템플릿 자동 적용
  const handleTargetChange = (target) => {
    const template = targetTemplates.find(t => t.value === target);
    if (template) {
      setFormData(prev => ({
        ...prev,
        target,
        name: `${target} 기준`,
        prefix: template.prefix,
      }));
    }
  };

  // 신규 등록 모달 열기
  const openCreateModal = () => {
    setEditingRule(null);
    setFormData({
      name: '',
      target: '',
      prefix: 'KD-',
      dateFormat: 'YYMMDD',
      seqDigits: 2,
      separator: '-',
      resetCycle: 'daily',
      status: '활성',
      description: '',
    });
    setShowModal(true);
  };

  // 수정 모달 열기
  const openEditModal = (rule) => {
    setEditingRule(rule);
    setFormData({
      name: rule.name,
      target: rule.target,
      prefix: rule.prefix,
      dateFormat: rule.dateFormat,
      seqDigits: rule.seqDigits,
      separator: rule.separator,
      resetCycle: rule.resetCycle,
      status: rule.status,
      description: rule.description || '',
    });
    setShowModal(true);
  };

  // 저장
  const handleSave = () => {
    const example = generatePreview(formData);
    if (editingRule) {
      setNumberRules(prev => prev.map(r =>
        r.id === editingRule.id ? { ...r, ...formData, example } : r
      ));
    } else {
      setNumberRules(prev => [...prev, {
        id: Math.max(...prev.map(r => r.id)) + 1,
        ...formData,
        example,
      }]);
    }
    setShowModal(false);
  };

  // 삭제
  const handleDelete = (id) => {
    if (confirm('이 번호기준을 삭제하시겠습니까?')) {
      setNumberRules(prev => prev.filter(r => r.id !== id));
    }
  };

  // 상태 토글
  const toggleStatus = (id) => {
    setNumberRules(prev => prev.map(r =>
      r.id === id ? { ...r, status: r.status === '활성' ? '비활성' : '활성' } : r
    ));
  };

  // 검색 필터링 및 정렬 (ID 내림차순)
  const filteredRules = [...numberRules]
    .sort((a, b) => b.id - a.id)
    .filter(rule => {
      if (!searchTerm) return true;
      const term = searchTerm.toLowerCase();
      return (
        rule.name.toLowerCase().includes(term) ||
        rule.target.toLowerCase().includes(term) ||
        rule.prefix.toLowerCase().includes(term) ||
        rule.example.toLowerCase().includes(term)
      );
    });

  // 체크박스 선택 관리
  const { selectedIds, handleSelect, handleSelectAll, clearSelection, isAllSelected, hasSelection, isMultiSelect, isSelected } = useListSelection(filteredRules);

  // 리포트 카드 데이터
  const activeCount = numberRules.filter(r => r.status === '활성').length;
  const docTypeCount = numberRules.filter(r => ['견적번호', '수주번호(스크린)', '수주번호(슬랫)', '수주번호(절곡)', '발주번호'].includes(r.target)).length;
  const lotTypeCount = numberRules.filter(r => r.target.includes('LOT')).length;

  return (
    <div className="space-y-6">
      {/* 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <Hash className="w-6 h-6 text-blue-500" />
          채번 목록
        </h1>
        <div className="flex items-center justify-end gap-2">
          <button
            onClick={() => setShowHelp(true)}
            className="w-8 h-8 rounded-full bg-gray-100 text-gray-600 hover:bg-gray-200 flex items-center justify-center text-sm font-bold"
            title="번호기준 vs 코드기준 차이점"
          >
            ?
          </button>
          <Button variant="primary" onClick={openCreateModal}>
            <Plus className="w-4 h-4" /> 채번 등록
          </Button>
        </div>
      </div>

      {/* 리포트 카드 4개 */}
      <div className="grid grid-cols-4 gap-4 mb-6">
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">전체 채번규칙</p>
          <p className="text-2xl font-bold">{numberRules.length}개</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">활성 규칙</p>
          <p className="text-2xl font-bold text-green-600">{activeCount}개</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">문서번호 규칙</p>
          <p className="text-2xl font-bold">{docTypeCount}개</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">LOT번호 규칙</p>
          <p className="text-2xl font-bold">{lotTypeCount}개</p>
        </div>
      </div>

      {/* 검색바 */}
      <div className="mb-6">
        <div className="relative">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder="번호기준 이름, 적용대상, 접두사, 예시 검색..."
            className="w-full pl-12 pr-4 py-3 border rounded-xl"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
      </div>

      {/* 도움말 모달 */}
      {showHelp && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl max-w-lg w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b flex justify-between items-center sticky top-0 bg-white z-10">
              <h3 className="font-bold text-lg">번호기준 vs 코드기준 차이점</h3>
              <button onClick={() => setShowHelp(false)} className="text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <h4 className="font-medium text-blue-900 flex items-center gap-2 mb-2">
                    <span className="text-xl">🔢</span> 번호기준 (문서용)
                  </h4>
                  <p className="text-sm text-blue-700 mb-2">
                    <strong>문서</strong>에 부여하는 일련번호
                  </p>
                  <ul className="text-sm text-blue-600 space-y-1">
                    <li>• 견적번호, 수주번호</li>
                    <li>• 생산지시번호, 출하번호</li>
                    <li>• 발주번호</li>
                  </ul>
                </div>
                <div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
                  <h4 className="font-medium text-orange-900 flex items-center gap-2 mb-2">
                    <span className="text-xl">🏷️</span> 코드기준 (실물용)
                  </h4>
                  <p className="text-sm text-orange-700 mb-2">
                    <strong>실물/마스터</strong>에 부여하는 식별코드
                  </p>
                  <ul className="text-sm text-orange-600 space-y-1">
                    <li>• 품목코드 (RC30, CB24 등)</li>
                    <li>• 입고LOT, 생산LOT</li>
                    <li>• 거래처코드, 현장코드</li>
                  </ul>
                </div>
              </div>
              <div className="bg-gray-50 rounded-lg p-3 text-sm text-gray-600">
                <strong>요약:</strong> 번호기준은 견적서/수주서 등 <u>업무 문서</u>를 식별하고,
                코드기준은 품목/거래처 등 <u>마스터 데이터</u>를 식별합니다.
              </div>
            </div>
            <div className="p-4 border-t bg-gray-50 rounded-b-xl">
              <button
                onClick={() => setShowHelp(false)}
                className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                확인
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 선택 삭제 버튼 (다중 선택 시) */}
      {isMultiSelect && (
        <div className="flex justify-end">
          <Button variant="danger" size="sm" onClick={() => {
            if (confirm(`선택한 ${selectedIds.length}개 항목을 삭제하시겠습니까?`)) {
              setNumberRules(prev => prev.filter(r => !selectedIds.includes(r.id)));
              clearSelection();
            }
          }}>
            <Trash2 className="w-4 h-4" /> 선택 삭제 ({selectedIds.length})
          </Button>
        </div>
      )}

      {/* 번호기준 목록 */}
      <div className="bg-white rounded-lg shadow-sm border overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left">
                <input type="checkbox" checked={isAllSelected} onChange={handleSelectAll} className="rounded" />
              </th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">번호기준 이름</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">적용 대상</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">접두사</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">날짜 형식</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">순번 자릿수</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">리셋 주기</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">예시</th>
              <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
              {hasSelection && <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>}
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {filteredRules.map((rule) => (
              <tr key={rule.id} className={isSelected(rule.id) ? 'bg-blue-50' : 'hover:bg-gray-50'}>
                <td className="px-4 py-3">
                  <input type="checkbox" checked={isSelected(rule.id)} onChange={() => handleSelect(rule.id)} className="rounded" />
                </td>
                <td className="px-4 py-3 text-sm font-medium text-gray-900">{rule.name}</td>
                <td className="px-4 py-3 text-sm text-gray-600">{rule.target}</td>
                <td className="px-4 py-3 text-sm font-mono text-blue-600">{rule.prefix}</td>
                <td className="px-4 py-3 text-sm text-gray-600">{rule.dateFormat}</td>
                <td className="px-4 py-3 text-sm text-gray-600">{rule.seqDigits}자리</td>
                <td className="px-4 py-3 text-sm text-gray-600">
                  {resetCycleOptions.find(o => o.value === rule.resetCycle)?.label.split(' ')[0] || '-'}
                </td>
                <td className="px-4 py-3 text-sm font-mono text-gray-900 bg-gray-50">{rule.example}</td>
                <td className="px-4 py-3 text-center">
                  <button
                    onClick={() => toggleStatus(rule.id)}
                    className={`px-2 py-1 rounded-full text-xs font-medium ${rule.status === '활성'
                        ? 'bg-green-100 text-green-700'
                        : 'bg-gray-100 text-gray-500'
                      }`}
                  >
                    {rule.status}
                  </button>
                </td>
                {hasSelection && (
                  <td className="px-4 py-3 text-center">
                    {isSelected(rule.id) && (
                      <div className="flex justify-center gap-1">
                        <button
                          onClick={() => openEditModal(rule)}
                          className="px-2 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded"
                        >
                          수정
                        </button>
                        <button
                          onClick={() => handleDelete(rule.id)}
                          className="px-2 py-1 text-xs bg-red-50 hover:bg-red-100 text-red-600 rounded"
                        >
                          삭제
                        </button>
                      </div>
                    )}
                  </td>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 등록/수정 모달 */}
      {showModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            {/* 모달 헤더 */}
            <div className="flex justify-between items-center p-4 border-b sticky top-0 bg-white">
              <h3 className="text-lg font-bold">
                {editingRule ? '번호기준 수정' : '번호기준 등록'}
              </h3>
              <button onClick={() => setShowModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>

            {/* 모달 내용 */}
            <div className="p-4 space-y-6">
              {/* 기본 정보 */}
              <div className="space-y-4">
                <h4 className="font-medium text-gray-900">
                  기본 정보
                </h4>

                {/* 적용 대상 선택 (템플릿) */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    적용 대상 선택 <span className="text-red-500">*</span>
                  </label>
                  <div className="grid grid-cols-5 gap-2">
                    {targetTemplates.map(template => (
                      <button
                        key={template.value}
                        onClick={() => handleTargetChange(template.value)}
                        className={`p-3 border rounded-lg text-center transition-all ${formData.target === template.value
                            ? 'border-blue-500 bg-blue-50 ring-2 ring-blue-200'
                            : 'border-gray-200 hover:border-gray-300'
                          }`}
                      >
                        <div className="text-xs font-medium">{template.label}</div>
                      </button>
                    ))}
                  </div>
                </div>

                {/* 번호기준 이름 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    번호기준 이름 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                    className="w-full border rounded-lg px-3 py-2 text-sm"
                    placeholder="예: 견적번호 기준"
                  />
                </div>
              </div>

              {/* 번호 구성 */}
              <div className="space-y-4">
                <h4 className="font-medium text-gray-900">
                  번호 구성
                </h4>

                <div className="grid grid-cols-2 gap-4">
                  {/* 접두사 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      접두사 <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      value={formData.prefix}
                      onChange={(e) => setFormData(prev => ({ ...prev, prefix: e.target.value }))}
                      className="w-full border rounded-lg px-3 py-2 text-sm font-mono"
                      placeholder="예: KD-PR"
                    />
                    <p className="text-xs text-gray-400 mt-1">번호 앞에 붙을 고정 문자열</p>
                  </div>

                  {/* 구분자 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">구분자</label>
                    <select
                      value={formData.separator}
                      onChange={(e) => setFormData(prev => ({ ...prev, separator: e.target.value }))}
                      className="w-full border rounded-lg px-3 py-2 text-sm"
                    >
                      {separatorOptions.map(opt => (
                        <option key={opt.value} value={opt.value}>{opt.label}</option>
                      ))}
                    </select>
                    <p className="text-xs text-gray-400 mt-1">각 요소 사이에 들어갈 구분 문자</p>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  {/* 날짜 형식 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">날짜 형식</label>
                    <select
                      value={formData.dateFormat}
                      onChange={(e) => setFormData(prev => ({ ...prev, dateFormat: e.target.value }))}
                      className="w-full border rounded-lg px-3 py-2 text-sm"
                    >
                      {dateFormats.map(opt => (
                        <option key={opt.value} value={opt.value}>{opt.label}</option>
                      ))}
                    </select>
                  </div>

                  {/* 순번 자릿수 */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">순번 자릿수</label>
                    <select
                      value={formData.seqDigits}
                      onChange={(e) => setFormData(prev => ({ ...prev, seqDigits: Number(e.target.value) }))}
                      className="w-full border rounded-lg px-3 py-2 text-sm"
                    >
                      {seqDigitOptions.map(opt => (
                        <option key={opt.value} value={opt.value}>{opt.label}</option>
                      ))}
                    </select>
                  </div>
                </div>

                {/* 리셋 주기 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">순번 리셋 주기</label>
                  <div className="grid grid-cols-2 gap-2">
                    {resetCycleOptions.map(opt => (
                      <label
                        key={opt.value}
                        className={`flex items-center gap-2 p-3 border rounded-lg cursor-pointer transition-all ${formData.resetCycle === opt.value
                            ? 'border-blue-500 bg-blue-50'
                            : 'border-gray-200 hover:border-gray-300'
                          }`}
                      >
                        <input
                          type="radio"
                          name="resetCycle"
                          value={opt.value}
                          checked={formData.resetCycle === opt.value}
                          onChange={(e) => setFormData(prev => ({ ...prev, resetCycle: e.target.value }))}
                          className="text-blue-600"
                        />
                        <span className="text-sm">{opt.label}</span>
                      </label>
                    ))}
                  </div>
                </div>
              </div>

              {/* 번호 미리보기 */}
              <div className="bg-gray-50 rounded-lg p-4 space-y-3">
                <h4 className="font-medium text-gray-900">
                  생성 번호 미리보기
                </h4>

                {/* 시각적 분해 */}
                <div className="flex items-center gap-1 justify-center py-4">
                  <div className="bg-blue-100 text-blue-700 px-3 py-2 rounded font-mono text-sm">
                    {formData.prefix}
                  </div>
                  {formData.separator && formData.dateFormat !== 'NONE' && (
                    <div className="text-gray-400 text-lg">{formData.separator}</div>
                  )}
                  {formData.dateFormat !== 'NONE' && (
                    <div className="bg-purple-100 text-purple-700 px-3 py-2 rounded font-mono text-sm">
                      {dateFormats.find(d => d.value === formData.dateFormat)?.example}
                    </div>
                  )}
                  {formData.separator && (
                    <div className="text-gray-400 text-lg">{formData.separator}</div>
                  )}
                  <div className="bg-green-100 text-green-700 px-3 py-2 rounded font-mono text-sm">
                    {'0'.repeat(formData.seqDigits - 1)}1
                  </div>
                </div>

                {/* 구성 설명 */}
                <div className="flex justify-center gap-4 text-xs text-gray-500">
                  <span className="flex items-center gap-1">
                    <span className="w-3 h-3 bg-blue-100 rounded"></span> 접두사
                  </span>
                  {formData.dateFormat !== 'NONE' && (
                    <span className="flex items-center gap-1">
                      <span className="w-3 h-3 bg-purple-100 rounded"></span> 날짜 ({formData.dateFormat})
                    </span>
                  )}
                  <span className="flex items-center gap-1">
                    <span className="w-3 h-3 bg-green-100 rounded"></span> 순번 ({formData.seqDigits}자리)
                  </span>
                </div>

                {/* 최종 결과 */}
                <div className="text-center pt-2 border-t">
                  <span className="text-sm text-gray-500">생성될 번호: </span>
                  <span className="text-lg font-mono font-bold text-blue-600">
                    {generatePreview(formData)}
                  </span>
                </div>
              </div>

              {/* 상태 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">상태</label>
                <div className="flex gap-4">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="status"
                      value="활성"
                      checked={formData.status === '활성'}
                      onChange={(e) => setFormData(prev => ({ ...prev, status: e.target.value }))}
                      className="text-blue-600"
                    />
                    <span className="text-sm">활성</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="status"
                      value="비활성"
                      checked={formData.status === '비활성'}
                      onChange={(e) => setFormData(prev => ({ ...prev, status: e.target.value }))}
                      className="text-blue-600"
                    />
                    <span className="text-sm">비활성</span>
                  </label>
                </div>
                <p className="text-xs text-gray-400 mt-1">비활성 시 번호 생성에 사용되지 않음</p>
              </div>
            </div>

            {/* 모달 푸터 */}
            <div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
              <button
                onClick={() => setShowModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleSave}
                disabled={!formData.target || !formData.name || !formData.prefix}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed"
              >
                {editingRule ? '수정' : '등록'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============================================================
// 통합 마스터 기준관리 시스템 (MasterConfigurationManager)
// ============================================================

// 공통 입력 타입 옵션
const commonInputTypeOptions = [
  { value: 'text', label: '텍스트박스' },
  { value: 'textarea', label: '텍스트영역' },
  { value: 'number', label: '숫자' },
  { value: 'select', label: '드롭다운' },
  { value: 'checkbox', label: '체크박스' },
  { value: 'radio', label: '라디오' },
  { value: 'date', label: '날짜' },
  { value: 'datetime', label: '날짜시간' },
  { value: 'file', label: '파일' },
  { value: 'table', label: '테이블' },
];

// 공통 조건 타입 옵션
const commonConditionTypeOptions = [
  { value: 'equals', label: '같음' },
  { value: 'not_equals', label: '같지 않음' },
  { value: 'contains', label: '포함' },
  { value: 'not_contains', label: '포함하지 않음' },
  { value: 'is_empty', label: '비어있음' },
  { value: 'is_not_empty', label: '비어있지 않음' },
];

// ============================================================
// 통합 마스터 기준관리 컴포넌트
// ============================================================
// Config는 ./configs/index.js에서 import됨

// 개별 config 참조 (하위 호환성)
const itemMasterConfig = masterConfigs['item'];
const processMasterConfig = masterConfigs['process'];
const inspectionMasterConfig = masterConfigs['inspection'];
const customerMasterConfig = masterConfigs['customer'];
const siteMasterConfig = masterConfigs['site'];

// 기존 config 정의는 ./configs/ 폴더로 이동됨
// ============================================================

const MasterConfigurationManager = ({ configId, onNavigate }) => {
  const config = masterConfigs[configId] || itemMasterConfig;

  // 탭 상태
  const [activeTab, setActiveTab] = useState('hierarchy');

  // 데이터 상태 (config에서 초기값 로드)
  const [entityTypes, setEntityTypes] = useState(config.entityTypes);
  const [categories, setCategories] = useState(config.categories);
  const [masterFields, setMasterFields] = useState(config.masterFields);
  const [masterSections, setMasterSections] = useState(config.masterSections);
  const [pageTemplates, setPageTemplates] = useState(config.pageTemplates);

  // 모달 상태
  const [showPageModal, setShowPageModal] = useState(false);
  const [showSectionModal, setShowSectionModal] = useState(false);
  const [showFieldModal, setShowFieldModal] = useState(false);
  const [showCategoryModal, setShowCategoryModal] = useState(false);

  // 선택 상태
  const [selectedPage, setSelectedPage] = useState(pageTemplates[0]);
  const [selectedSection, setSelectedSection] = useState(null);
  const [selectedField, setSelectedField] = useState(null);
  const [selectedCategory, setSelectedCategory] = useState(null);

  // 폼 상태
  const [pageForm, setPageForm] = useState({ pageName: '', pagePath: '', itemTypes: [] });
  const [sectionForm, setSectionForm] = useState({ sectionName: '', sectionKey: '', sectionType: 'general', description: '', useMaster: false });
  const [fieldForm, setFieldForm] = useState({ fieldName: '', fieldKey: '', inputType: 'text', isRequired: false, description: '', useMaster: false });
  const [categoryForm, setCategoryForm] = useState({ code: '', name: '', parentId: null });

  // config 변경 시 데이터 리셋
  useEffect(() => {
    setEntityTypes(config.entityTypes);
    setCategories(config.categories);
    setMasterFields(config.masterFields);
    setMasterSections(config.masterSections);
    setPageTemplates(config.pageTemplates);
    setSelectedPage(config.pageTemplates[0]);
    setActiveTab('hierarchy');
  }, [configId]);

  // 아이콘 맵핑
  const iconMap = {
    'GitBranch': GitBranch,
    'Layers': Layers,
    'ClipboardList': ClipboardList,
    'Settings': Settings,
    'Package': Package,
    'Factory': Factory,
    'ShieldCheck': ShieldCheck,
    'Users': Users,
    'MapPin': MapPin,
    'FileText': FileText,
    'BarChart3': BarChart3,
  };

  const getIcon = (iconName) => iconMap[iconName] || Settings;
  const HeaderIcon = getIcon(config.icon);

  // 카테고리 트리 빌드
  const buildCategoryTree = (items, parentId = null) => {
    return items
      .filter(item => item.parentId === parentId)
      .sort((a, b) => a.sortOrder - b.sortOrder)
      .map(item => ({
        ...item,
        children: buildCategoryTree(items, item.id)
      }));
  };

  const categoryTree = buildCategoryTree(categories);

  // 페이지 추가
  const handleAddPage = () => {
    setPageForm({ pageName: '', pagePath: '', itemTypes: [entityTypes[0]?.code || ''] });
    setShowPageModal(true);
  };

  const handleSavePage = () => {
    const newPage = {
      id: pageTemplates.length + 1,
      pageCode: pageForm.pageName.toLowerCase().replace(/\s+/g, '_'),
      ...pageForm,
      sections: [],
      conditions: []
    };
    setPageTemplates([...pageTemplates, newPage]);
    setSelectedPage(newPage);
    setShowPageModal(false);
  };

  // 섹션 추가
  const handleAddSection = (useMaster = false) => {
    if (useMaster) {
      setSectionForm({ ...sectionForm, useMaster: true });
    } else {
      setSectionForm({ sectionName: '', sectionKey: '', sectionType: 'general', description: '', useMaster: false });
    }
    setShowSectionModal(true);
  };

  const handleSaveSection = () => {
    if (!selectedPage) return;

    const newSection = {
      sectionId: Date.now(),
      sectionKey: sectionForm.sectionKey || sectionForm.sectionName.toLowerCase().replace(/\s+/g, '_'),
      sectionName: sectionForm.sectionName,
      sortOrder: selectedPage.sections.length + 1,
      fields: []
    };

    const updatedPage = {
      ...selectedPage,
      sections: [...selectedPage.sections, newSection]
    };

    setPageTemplates(pageTemplates.map(p => p.id === selectedPage.id ? updatedPage : p));
    setSelectedPage(updatedPage);
    setShowSectionModal(false);
  };

  // 필드 추가
  const handleAddField = (sectionId, useMaster = false) => {
    setSelectedSection(selectedPage?.sections.find(s => s.sectionId === sectionId));
    if (useMaster) {
      setFieldForm({ ...fieldForm, useMaster: true });
    } else {
      setFieldForm({ fieldName: '', fieldKey: '', inputType: 'text', isRequired: false, description: '', useMaster: false });
    }
    setShowFieldModal(true);
  };

  const handleSaveField = () => {
    if (!selectedPage || !selectedSection) return;

    const newField = {
      fieldId: Date.now(),
      fieldKey: fieldForm.fieldKey || fieldForm.fieldName.toLowerCase().replace(/\s+/g, '_'),
      fieldName: fieldForm.fieldName,
      inputType: fieldForm.inputType,
      isRequired: fieldForm.isRequired,
    };

    const updatedSections = selectedPage.sections.map(s =>
      s.sectionId === selectedSection.sectionId
        ? { ...s, fields: [...s.fields, newField] }
        : s
    );

    const updatedPage = { ...selectedPage, sections: updatedSections };
    setPageTemplates(pageTemplates.map(p => p.id === selectedPage.id ? updatedPage : p));
    setSelectedPage(updatedPage);
    setShowFieldModal(false);
  };

  // 필드 삭제
  const handleDeleteField = (sectionId, fieldId) => {
    if (!selectedPage) return;

    const updatedSections = selectedPage.sections.map(s =>
      s.sectionId === sectionId
        ? { ...s, fields: s.fields.filter(f => f.fieldId !== fieldId) }
        : s
    );

    const updatedPage = { ...selectedPage, sections: updatedSections };
    setPageTemplates(pageTemplates.map(p => p.id === selectedPage.id ? updatedPage : p));
    setSelectedPage(updatedPage);
  };

  // 섹션 삭제
  const handleDeleteSection = (sectionId) => {
    if (!selectedPage) return;

    const updatedPage = {
      ...selectedPage,
      sections: selectedPage.sections.filter(s => s.sectionId !== sectionId)
    };

    setPageTemplates(pageTemplates.map(p => p.id === selectedPage.id ? updatedPage : p));
    setSelectedPage(updatedPage);
  };

  // 카테고리 추가
  const handleAddCategory = (parentId = null) => {
    setCategoryForm({ code: '', name: '', parentId });
    setShowCategoryModal(true);
  };

  const handleSaveCategory = () => {
    const parent = categories.find(c => c.id === categoryForm.parentId);
    const newCategory = {
      id: categories.length + 10,
      code: categoryForm.code,
      name: categoryForm.name,
      parentId: categoryForm.parentId,
      level: parent ? parent.level + 1 : 1,
      path: parent ? `${parent.path}/${categories.length + 10}` : `/${categories.length + 10}`,
      sortOrder: categories.filter(c => c.parentId === categoryForm.parentId).length + 1
    };

    setCategories([...categories, newCategory]);
    setShowCategoryModal(false);
  };

  // 카테고리 트리 렌더링
  const renderCategoryTree = (nodes, depth = 0) => {
    const CategoryIcon = getIcon(config.tabs.find(t => t.id === 'category')?.icon || 'Package');
    return nodes.map(node => (
      <div key={node.id}>
        <div
          className={`flex items-center justify-between py-2 px-3 hover:bg-gray-50 rounded-lg cursor-pointer ${selectedCategory?.id === node.id ? 'bg-blue-50' : ''}`}
          style={{ paddingLeft: `${depth * 20 + 12}px` }}
          onClick={() => setSelectedCategory(node)}
        >
          <div className="flex items-center gap-2">
            {node.children?.length > 0 ? (
              <ChevronRight className="w-4 h-4 text-gray-400" />
            ) : (
              <div className="w-4" />
            )}
            <CategoryIcon className="w-4 h-4 text-gray-500" />
            <span className="text-sm">{node.name}</span>
            <span className="text-xs text-gray-400">({node.code})</span>
          </div>
          <div className="flex items-center gap-1">
            <button
              onClick={(e) => { e.stopPropagation(); handleAddCategory(node.id); }}
              className="p-1 hover:bg-gray-200 rounded"
            >
              <Plus className="w-3 h-3 text-gray-500" />
            </button>
            <button className="p-1 hover:bg-gray-200 rounded">
              <Edit2 className="w-3 h-3 text-gray-500" />
            </button>
            <button className="p-1 hover:bg-gray-200 rounded">
              <Trash2 className="w-3 h-3 text-red-500" />
            </button>
          </div>
        </div>
        {node.children?.length > 0 && renderCategoryTree(node.children, depth + 1)}
      </div>
    ));
  };

  return (
    <div className="space-y-4">
      {/* 헤더 */}
      <div className="flex items-center gap-3">
        <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
          <HeaderIcon className="w-5 h-5 text-blue-600" />
        </div>
        <div>
          <h1 className="text-xl font-bold text-gray-900">{config.title}</h1>
          <p className="text-sm text-gray-500">{config.description}</p>
        </div>
      </div>

      {/* 탭 */}
      <div className="bg-white rounded-xl border">
        <div className="flex border-b overflow-x-auto">
          {config.tabs.map(tab => {
            const TabIcon = getIcon(tab.icon);
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-2 px-6 py-3 text-sm font-medium whitespace-nowrap border-b-2 transition-colors
                  ${activeTab === tab.id
                    ? 'border-blue-500 text-blue-600 bg-blue-50/50'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'}`}
              >
                <TabIcon className="w-4 h-4" />
                {tab.label}
              </button>
            );
          })}
        </div>

        <div className="p-4">
          {/* 계층구조 탭 - 페이지 빌더 */}
          {activeTab === 'hierarchy' && (
            <div className="flex gap-4">
              {/* 좌측: 페이지 목록 */}
              <div className="w-80 border rounded-lg">
                <div className="flex items-center justify-between p-3 border-b bg-gray-50">
                  <span className="font-medium text-sm">페이지</span>
                  <button
                    onClick={handleAddPage}
                    className="p-1.5 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                  >
                    <Plus className="w-4 h-4" />
                  </button>
                </div>
                <div className="p-2 space-y-1 max-h-96 overflow-y-auto">
                  {pageTemplates.map(page => (
                    <div
                      key={page.id}
                      onClick={() => setSelectedPage(page)}
                      className={`p-3 rounded-lg cursor-pointer border transition-colors
                        ${selectedPage?.id === page.id
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-transparent hover:bg-gray-50'}`}
                    >
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium text-sm">{page.pageName}</p>
                          <p className="text-xs text-gray-500">{page.itemTypes.map(t => {
                            const type = entityTypes.find(it => it.code === t);
                            return type ? `${type.name} (${t})` : t;
                          }).join(', ')}</p>
                        </div>
                        <div className="flex gap-1">
                          <button className="p-1 hover:bg-gray-200 rounded">
                            <Edit2 className="w-3 h-3 text-gray-500" />
                          </button>
                          <button className="p-1 hover:bg-gray-200 rounded">
                            <Trash2 className="w-3 h-3 text-red-500" />
                          </button>
                        </div>
                      </div>
                      <p className="text-xs text-gray-400 mt-1">{page.pagePath}</p>
                    </div>
                  ))}
                </div>
              </div>

              {/* 우측: 페이지 구성 */}
              <div className="flex-1 border rounded-lg">
                <div className="flex items-center justify-between p-3 border-b bg-gray-50">
                  <span className="font-medium text-sm">{selectedPage?.pageName || '페이지 선택'}</span>
                  <button
                    onClick={() => handleAddSection(false)}
                    className="flex items-center gap-1 px-3 py-1.5 bg-blue-500 text-white rounded-lg hover:bg-blue-600 text-sm"
                    disabled={!selectedPage}
                  >
                    <Plus className="w-4 h-4" /> 섹션 추가
                  </button>
                </div>

                {selectedPage ? (
                  <div className="p-4 space-y-4 max-h-[500px] overflow-y-auto">
                    {selectedPage.sections.map((section, sIdx) => (
                      <div key={section.sectionId} className="border border-blue-200 rounded-xl bg-blue-50/30">
                        {/* 섹션 헤더 */}
                        <div className="flex items-center justify-between p-3 border-b border-blue-200 bg-blue-50">
                          <div className="flex items-center gap-2">
                            <GripVertical className="w-4 h-4 text-gray-400 cursor-grab" />
                            <Layers className="w-4 h-4 text-blue-600" />
                            <span className="font-medium text-blue-800">{section.sectionName}</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <button
                              onClick={() => handleAddField(section.sectionId, false)}
                              className="p-1 hover:bg-blue-200 rounded text-blue-600"
                              title="항목 추가"
                            >
                              <Plus className="w-4 h-4" />
                            </button>
                            <button className="p-1 hover:bg-blue-200 rounded">
                              <Edit2 className="w-4 h-4 text-blue-600" />
                            </button>
                            <button
                              onClick={() => handleDeleteSection(section.sectionId)}
                              className="p-1 hover:bg-red-100 rounded"
                            >
                              <X className="w-4 h-4 text-red-500" />
                            </button>
                          </div>
                        </div>

                        {/* 섹션 필드 */}
                        <div className="p-3 space-y-2">
                          {section.fields.length === 0 ? (
                            <div className="text-center py-4 text-gray-400 text-sm">
                              <button
                                onClick={() => handleAddField(section.sectionId, false)}
                                className="text-blue-500 hover:underline"
                              >
                                + 항목 추가
                              </button>
                            </div>
                          ) : (
                            section.fields.map((field, fIdx) => (
                              <div
                                key={field.fieldId}
                                className="flex items-center justify-between p-2 bg-white rounded-lg border"
                              >
                                <div className="flex items-center gap-3">
                                  <GripVertical className="w-4 h-4 text-gray-300 cursor-grab" />
                                  <div>
                                    <div className="flex items-center gap-2">
                                      <span className="text-sm font-medium">{field.fieldName}</span>
                                      <span className="text-xs px-2 py-0.5 bg-gray-100 rounded">{
                                        commonInputTypeOptions.find(o => o.value === field.inputType)?.label || field.inputType
                                      }</span>
                                      {field.isRequired && (
                                        <span className="text-xs px-2 py-0.5 bg-red-100 text-red-600 rounded">필수</span>
                                      )}
                                    </div>
                                    <p className="text-xs text-gray-400">필드키: {field.fieldKey}</p>
                                  </div>
                                </div>
                                <div className="flex items-center gap-1">
                                  <button className="p-1 hover:bg-gray-100 rounded">
                                    <Edit2 className="w-3 h-3 text-gray-500" />
                                  </button>
                                  <button
                                    onClick={() => handleDeleteField(section.sectionId, field.fieldId)}
                                    className="p-1 hover:bg-red-50 rounded"
                                  >
                                    <X className="w-3 h-3 text-red-500" />
                                  </button>
                                </div>
                              </div>
                            ))
                          )}
                        </div>
                      </div>
                    ))}

                    {selectedPage.sections.length === 0 && (
                      <div className="text-center py-12 text-gray-400">
                        <Layers className="w-12 h-12 mx-auto mb-3 opacity-30" />
                        <p>섹션을 추가해주세요</p>
                        <button
                          onClick={() => handleAddSection(false)}
                          className="mt-2 text-blue-500 hover:underline text-sm"
                        >
                          + 새 섹션 추가
                        </button>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="text-center py-12 text-gray-400">
                    <FileText className="w-12 h-12 mx-auto mb-3 opacity-30" />
                    <p>페이지를 선택해주세요</p>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* 섹션 탭 */}
          {activeTab === 'section' && (
            <div>
              <div className="flex items-center justify-between mb-4">
                <div className="flex gap-2">
                  <button className="px-4 py-2 bg-gray-100 rounded-lg text-sm font-medium">일반 섹션</button>
                  <button className="px-4 py-2 text-gray-500 hover:bg-gray-50 rounded-lg text-sm">모듈 섹션</button>
                </div>
                <button
                  onClick={() => setShowSectionModal(true)}
                  className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
                >
                  <Plus className="w-4 h-4" /> 섹션추가
                </button>
              </div>

              <div className="border rounded-xl">
                <div className="p-4 border-b bg-gray-50 text-sm text-gray-600">
                  섹션관리<br />
                  <span className="text-xs text-gray-400">재사용 가능한 섹션 템플릿을 관리합니다</span>
                </div>

                <div className="divide-y">
                  {masterSections.map(section => (
                    <div key={section.id} className="p-4 hover:bg-gray-50">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <FileText className="w-5 h-5 text-gray-400" />
                          <div>
                            <p className="font-medium">{section.sectionName}</p>
                            <p className="text-xs text-gray-500">{section.description}</p>
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          {section.applicableTypes.map(type => (
                            <span key={type} className="px-2 py-1 bg-blue-50 text-blue-600 rounded text-xs">
                              {entityTypes.find(t => t.code === type)?.name || type}
                            </span>
                          ))}
                          <button className="p-1 hover:bg-gray-200 rounded">
                            <Edit2 className="w-4 h-4 text-gray-500" />
                          </button>
                          <button className="p-1 hover:bg-red-50 rounded">
                            <Trash2 className="w-4 h-4 text-red-500" />
                          </button>
                        </div>
                      </div>

                      <div className="mt-3 p-3 bg-gray-50 rounded-lg border border-dashed">
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-xs text-gray-500">포함된 항목</span>
                          <button className="text-xs text-blue-500 hover:underline">+ 항목 추가</button>
                        </div>
                        {section.fields.length > 0 ? (
                          <div className="flex flex-wrap gap-2">
                            {section.fields.map(fieldId => {
                              const field = masterFields.find(f => f.id === fieldId);
                              return field ? (
                                <span key={fieldId} className="px-2 py-1 bg-white border rounded text-xs">
                                  {field.fieldName}
                                </span>
                              ) : null;
                            })}
                          </div>
                        ) : (
                          <p className="text-xs text-gray-400 text-center py-2">항목을 추가해주세요</p>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* 항목 탭 */}
          {activeTab === 'field' && (
            <div>
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-medium">마스터 항목</h3>
                <button
                  onClick={() => setShowFieldModal(true)}
                  className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
                >
                  <Plus className="w-4 h-4" /> 항목 추가
                </button>
              </div>

              <div className="border rounded-xl overflow-hidden">
                <table className="w-full">
                  <thead className="bg-gray-50 border-b">
                    <tr>
                      <th className="text-left px-4 py-3 text-sm font-medium text-gray-600">항목명</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-gray-600">필드키</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-gray-600">입력방식</th>
                      <th className="text-center px-4 py-3 text-sm font-medium text-gray-600">필수</th>
                      <th className="text-left px-4 py-3 text-sm font-medium text-gray-600">설명</th>
                      <th className="text-center px-4 py-3 text-sm font-medium text-gray-600">관리</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {masterFields.map(field => (
                      <tr key={field.id} className="hover:bg-gray-50">
                        <td className="px-4 py-3 text-sm font-medium">{field.fieldName}</td>
                        <td className="px-4 py-3 text-sm text-gray-500 font-mono">{field.fieldKey}</td>
                        <td className="px-4 py-3">
                          <span className="px-2 py-1 bg-gray-100 rounded text-xs">
                            {commonInputTypeOptions.find(o => o.value === field.inputType)?.label || field.inputType}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-center">
                          {field.isRequired ? (
                            <span className="px-2 py-1 bg-red-100 text-red-600 rounded text-xs">필수</span>
                          ) : (
                            <span className="text-gray-300">-</span>
                          )}
                        </td>
                        <td className="px-4 py-3 text-sm text-gray-500">{field.description}</td>
                        <td className="px-4 py-3 text-center">
                          <div className="flex items-center justify-center gap-1">
                            <button className="p-1 hover:bg-gray-200 rounded">
                              <Edit2 className="w-4 h-4 text-gray-500" />
                            </button>
                            <button className="p-1 hover:bg-red-50 rounded">
                              <Trash2 className="w-4 h-4 text-red-500" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* 속성 탭 */}
          {activeTab === 'attribute' && (
            <div>
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-medium">속성 관리</h3>
              </div>

              <div className="grid grid-cols-2 gap-4">
                {/* 입력 타입별 속성 */}
                <div className="border rounded-xl p-4">
                  <h4 className="font-medium mb-3">입력 타입</h4>
                  <div className="space-y-2">
                    {commonInputTypeOptions.map(type => (
                      <div key={type.value} className="flex items-center justify-between p-2 bg-gray-50 rounded-lg">
                        <span className="text-sm">{type.label}</span>
                        <span className="text-xs text-gray-400">{type.value}</span>
                      </div>
                    ))}
                  </div>
                </div>

                {/* 조건 타입 */}
                <div className="border rounded-xl p-4">
                  <h4 className="font-medium mb-3">조건부 표시 타입</h4>
                  <div className="space-y-2">
                    {commonConditionTypeOptions.map(type => (
                      <div key={type.value} className="flex items-center justify-between p-2 bg-gray-50 rounded-lg">
                        <span className="text-sm">{type.label}</span>
                        <span className="text-xs text-gray-400">{type.value}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* 검사 템플릿 탭 (품질기준관리 전용) */}
          {activeTab === 'templates' && configId === 'quality' && <TemplateList onNavigate={onNavigate} />}

          {/* KS규격 탭 (품질기준관리 전용) */}
      {activeTab === 'ks-standards' && configId === 'quality' && (
        <div>
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="font-medium">KS 규격 참조</h3>
              <p className="text-sm text-gray-500">검사항목에 적용되는 KS 규격 정보입니다</p>
                </div>
              </div>

              <div className="space-y-4">
                {config.ksStandards?.map(ks => (
                  <div key={ks.id} className="border rounded-xl">
                    <div className="p-4 border-b bg-gray-50">
                      <div className="flex items-center justify-between">
                        <div>
                          <span className="font-bold text-blue-600">{ks.code}</span>
                          <span className="ml-2 font-medium">{ks.name}</span>
                        </div>
                        <div className="flex gap-1">
                          {ks.applicableTypes.map(type => (
                            <span key={type} className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">
                              {type}
                            </span>
                          ))}
                        </div>
                      </div>
                      <p className="text-sm text-gray-500 mt-1">{ks.description}</p>
                    </div>
                    <div className="overflow-x-auto">
                      <table className="w-full text-sm">
                        <thead className="bg-gray-50 border-b">
                          <tr>
                            <th className="text-left px-4 py-2">검사항목</th>
                            <th className="text-left px-4 py-2">검사방법</th>
                            <th className="text-left px-4 py-2">규격/허용오차</th>
                            <th className="text-left px-4 py-2">단위</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y">
                          {ks.inspectionItems.map((item, idx) => (
                            <tr key={idx} className="hover:bg-gray-50">
                              <td className="px-4 py-2 font-medium">{item.item}</td>
                              <td className="px-4 py-2 text-gray-500">{item.method}</td>
                              <td className="px-4 py-2 text-gray-600">
                                {item.tolerance || item.standard || (item.minValue ? `${item.minValue} 이상` : '-')}
                              </td>
                              <td className="px-4 py-2 text-gray-500">{item.unit || '-'}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 샘플링 기준 탭 (품질기준관리 전용) */}
          {activeTab === 'sampling' && configId === 'quality' && (
            <div>
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h3 className="font-medium">샘플링 기준 (AQL)</h3>
                  <p className="text-sm text-gray-500">검사 샘플링 계획 및 합격 판정 기준입니다</p>
                </div>
              </div>

              <div className="space-y-4">
                {config.samplingPlans?.map(plan => (
                  <div key={plan.id} className="border rounded-xl">
                    <div className="p-4 border-b bg-gray-50">
                      <span className="font-bold">{plan.name}</span>
                      <p className="text-sm text-gray-500 mt-1">{plan.description}</p>
                    </div>

                    {plan.levels && (
                      <div className="overflow-x-auto">
                        <table className="w-full text-sm">
                          <thead className="bg-gray-50 border-b">
                            <tr>
                              <th className="text-left px-4 py-2">로트 크기</th>
                              <th className="text-center px-4 py-2">샘플 수량</th>
                              <th className="text-center px-4 py-2">합격판정개수 (Ac)</th>
                              <th className="text-center px-4 py-2">불합격판정개수 (Re)</th>
                            </tr>
                          </thead>
                          <tbody className="divide-y">
                            {plan.levels.map((level, idx) => (
                              <tr key={idx} className="hover:bg-gray-50">
                                <td className="px-4 py-2">{level.lotSizeMin} ~ {level.lotSizeMax}</td>
                                <td className="px-4 py-2 text-center font-medium">{level.sampleSize}</td>
                                <td className="px-4 py-2 text-center">
                                  <span className="px-2 py-1 bg-green-100 text-green-700 rounded">{level.acceptanceNumber}</span>
                                </td>
                                <td className="px-4 py-2 text-center">
                                  <span className="px-2 py-1 bg-red-100 text-red-700 rounded">{level.rejectionNumber}</span>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}

                    {plan.measurementPoints && (
                      <div className="p-4">
                        <div className="grid grid-cols-3 gap-4">
                          <div className="p-3 bg-blue-50 rounded-lg">
                            <p className="text-xs text-gray-500">기본 샘플 수</p>
                            <p className="font-bold text-blue-700">{plan.defaultSampleSize}</p>
                          </div>
                          <div className="p-3 bg-green-50 rounded-lg">
                            <p className="text-xs text-gray-500">측정 포인트</p>
                            <p className="font-bold text-green-700">{plan.measurementPoints}개 (①~⑤)</p>
                          </div>
                          <div className="p-3 bg-yellow-50 rounded-lg">
                            <p className="text-xs text-gray-500">합격판정개수</p>
                            <p className="font-bold text-yellow-700">{plan.acceptanceNumber}</p>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 분류 탭 */}
          {activeTab === 'category' && (
            <div>
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-medium">{config.tabs.find(t => t.id === 'category')?.label} (계층구조)</h3>
                <button
                  onClick={() => handleAddCategory(null)}
                  className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
                >
                  <Plus className="w-4 h-4" /> 분류 추가
                </button>
              </div>

              <div className="flex gap-4">
                {/* 트리 뷰 */}
                <div className="flex-1 border rounded-xl p-3">
                  {renderCategoryTree(categoryTree)}
                </div>

                {/* 선택된 분류 상세 */}
                {selectedCategory && (
                  <div className="w-80 border rounded-xl p-4">
                    <h4 className="font-medium mb-4">분류 상세</h4>
                    <div className="space-y-3">
                      <div>
                        <label className="text-xs text-gray-500">코드</label>
                        <p className="font-mono text-sm">{selectedCategory.code}</p>
                      </div>
                      <div>
                        <label className="text-xs text-gray-500">이름</label>
                        <p className="text-sm">{selectedCategory.name}</p>
                      </div>
                      <div>
                        <label className="text-xs text-gray-500">레벨</label>
                        <p className="text-sm">{selectedCategory.level}</p>
                      </div>
                      <div>
                        <label className="text-xs text-gray-500">경로</label>
                        <p className="font-mono text-xs text-gray-500">{selectedCategory.path}</p>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* 템플릿 관리 탭 */}
          {activeTab === 'template' && (
            <div>
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-medium">템플릿 관리</h3>
              </div>

              <div className="grid grid-cols-2 gap-4">
                {/* 유형 목록 */}
                <div className="border rounded-xl">
                  <div className="p-3 border-b bg-gray-50">
                    <span className="font-medium text-sm">유형</span>
                  </div>
                  <div className="p-3 space-y-2">
                    {entityTypes.map(type => (
                      <div key={type.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                        <div className="flex items-center gap-3">
                          <span className="w-10 h-10 bg-blue-100 text-blue-600 rounded-lg flex items-center justify-center text-sm font-bold">
                            {type.code}
                          </span>
                          <div>
                            <p className="font-medium text-sm">{type.name}</p>
                            <p className="text-xs text-gray-500">{type.description}</p>
                          </div>
                        </div>
                        <div className="flex items-center gap-1">
                          <button className="p-1 hover:bg-gray-200 rounded">
                            <Edit2 className="w-4 h-4 text-gray-500" />
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* 페이지 템플릿 목록 */}
                <div className="border rounded-xl">
                  <div className="p-3 border-b bg-gray-50">
                    <span className="font-medium text-sm">페이지 템플릿</span>
                  </div>
                  <div className="p-3 space-y-2">
                    {pageTemplates.map(page => (
                      <div key={page.id} className="p-3 bg-gray-50 rounded-lg">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="font-medium text-sm">{page.pageName}</p>
                            <p className="text-xs text-gray-500">{page.pagePath}</p>
                          </div>
                          <div className="flex gap-1">
                            {page.itemTypes.map(type => (
                              <span key={type} className="px-2 py-0.5 bg-blue-100 text-blue-600 rounded text-xs">
                                {type}
                              </span>
                            ))}
                          </div>
                        </div>
                        <div className="mt-2 text-xs text-gray-400">
                          {page.sections.length}개 섹션, {page.sections.reduce((sum, s) => sum + s.fields.length, 0)}개 필드
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 페이지 추가 모달 */}
      {showPageModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl w-full max-w-md p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-bold text-lg">페이지 추가</h3>
              <button onClick={() => setShowPageModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <p className="text-sm text-gray-500 mb-4">새로운 페이지를 생성합니다</p>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">페이지명 *</label>
                <input
                  type="text"
                  value={pageForm.pageName}
                  onChange={(e) => setPageForm({ ...pageForm, pageName: e.target.value })}
                  placeholder="예: 등록"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">유형 *</label>
                <select
                  value={pageForm.itemTypes[0] || ''}
                  onChange={(e) => setPageForm({ ...pageForm, itemTypes: [e.target.value] })}
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                >
                  {entityTypes.map(type => (
                    <option key={type.code} value={type.code}>{type.name} ({type.code})</option>
                  ))}
                </select>
              </div>
            </div>

            <div className="flex justify-end gap-2 mt-6">
              <button
                onClick={() => setShowPageModal(false)}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg text-sm"
              >
                취소
              </button>
              <button
                onClick={handleSavePage}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
              >
                추가
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 섹션 추가 모달 */}
      {showSectionModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl w-full max-w-md p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-bold text-lg">섹션 추가</h3>
              <button onClick={() => setShowSectionModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <p className="text-sm text-gray-500 mb-4">마스터 섹션을 불러오거나 직접 입력하세요</p>

            {/* 탭: 직접 입력 / 마스터 섹션 불러오기 */}
            <div className="flex gap-2 mb-4">
              <button
                onClick={() => setSectionForm({ ...sectionForm, useMaster: false })}
                className={`flex-1 py-2 rounded-lg text-sm font-medium ${!sectionForm.useMaster ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600'}`}
              >
                직접 입력
              </button>
              <button
                onClick={() => setSectionForm({ ...sectionForm, useMaster: true })}
                className={`flex-1 py-2 rounded-lg text-sm font-medium ${sectionForm.useMaster ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600'}`}
              >
                마스터 섹션 불러오기
              </button>
            </div>

            {!sectionForm.useMaster ? (
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">섹션 제목 *</label>
                  <input
                    type="text"
                    value={sectionForm.sectionName}
                    onChange={(e) => setSectionForm({ ...sectionForm, sectionName: e.target.value })}
                    placeholder="예: 기본 정보"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">설명 (선택)</label>
                  <input
                    type="text"
                    value={sectionForm.description}
                    onChange={(e) => setSectionForm({ ...sectionForm, description: e.target.value })}
                    placeholder="섹션에 대한 설명"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
              </div>
            ) : (
              <div className="space-y-2 max-h-60 overflow-y-auto">
                {masterSections.map(section => (
                  <div
                    key={section.id}
                    onClick={() => setSectionForm({ ...sectionForm, sectionName: section.sectionName, sectionKey: section.sectionKey, masterSectionId: section.id })}
                    className={`p-3 border rounded-lg cursor-pointer hover:bg-gray-50 ${sectionForm.masterSectionId === section.id ? 'border-blue-500 bg-blue-50' : ''}`}
                  >
                    <p className="font-medium text-sm">{section.sectionName}</p>
                    <p className="text-xs text-gray-500">{section.description}</p>
                  </div>
                ))}
              </div>
            )}

            <div className="flex justify-end gap-2 mt-6">
              <button
                onClick={() => setShowSectionModal(false)}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg text-sm"
              >
                취소
              </button>
              <button
                onClick={handleSaveSection}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
              >
                추가
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 항목 추가 모달 */}
      {showFieldModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl w-full max-w-lg p-6 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-bold text-lg">항목 추가</h3>
              <button onClick={() => setShowFieldModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <p className="text-sm text-gray-500 mb-4">재사용 가능한 마스터 항목을 선택하거나 직접 입력하세요</p>

            {/* 탭 */}
            <div className="flex gap-2 mb-4">
              <button
                onClick={() => setFieldForm({ ...fieldForm, useMaster: false })}
                className={`flex-1 py-2 rounded-lg text-sm font-medium ${!fieldForm.useMaster ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600'}`}
              >
                직접 입력
              </button>
              <button
                onClick={() => setFieldForm({ ...fieldForm, useMaster: true })}
                className={`flex-1 py-2 rounded-lg text-sm font-medium ${fieldForm.useMaster ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600'}`}
              >
                마스터 항목 선택
              </button>
            </div>

            {!fieldForm.useMaster ? (
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">항목명 *</label>
                    <input
                      type="text"
                      value={fieldForm.fieldName}
                      onChange={(e) => setFieldForm({ ...fieldForm, fieldName: e.target.value })}
                      placeholder="예: 품목명"
                      className="w-full px-3 py-2 border rounded-lg text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">필드 키 *</label>
                    <input
                      type="text"
                      value={fieldForm.fieldKey}
                      onChange={(e) => setFieldForm({ ...fieldForm, fieldKey: e.target.value })}
                      placeholder="예: itemName"
                      className="w-full px-3 py-2 border rounded-lg text-sm"
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">입력방식 *</label>
                  <select
                    value={fieldForm.inputType}
                    onChange={(e) => setFieldForm({ ...fieldForm, inputType: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  >
                    {commonInputTypeOptions.map(opt => (
                      <option key={opt.value} value={opt.value}>{opt.label}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">설명 (선택)</label>
                  <input
                    type="text"
                    value={fieldForm.description}
                    onChange={(e) => setFieldForm({ ...fieldForm, description: e.target.value })}
                    placeholder="항목에 대한 설명"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="isRequired"
                    checked={fieldForm.isRequired}
                    onChange={(e) => setFieldForm({ ...fieldForm, isRequired: e.target.checked })}
                    className="w-4 h-4"
                  />
                  <label htmlFor="isRequired" className="text-sm">필수 ��목</label>
                </div>
              </div>
            ) : (
              <div className="space-y-2 max-h-60 overflow-y-auto">
                {masterFields.map(field => (
                  <div
                    key={field.id}
                    onClick={() => setFieldForm({
                      ...field,
                      useMaster: true,
                      masterFieldId: field.id
                    })}
                    className={`p-3 border rounded-lg cursor-pointer hover:bg-gray-50 ${fieldForm.masterFieldId === field.id ? 'border-blue-500 bg-blue-50' : ''}`}
                  >
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-medium text-sm">{field.fieldName}</p>
                        <p className="text-xs text-gray-500">필드키: {field.fieldKey}</p>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="px-2 py-0.5 bg-gray-100 rounded text-xs">
                          {commonInputTypeOptions.find(o => o.value === field.inputType)?.label}
                        </span>
                        {field.isRequired && (
                          <span className="px-2 py-0.5 bg-red-100 text-red-600 rounded text-xs">필수</span>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            <div className="flex justify-end gap-2 mt-6">
              <button
                onClick={() => setShowFieldModal(false)}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg text-sm"
              >
                취소
              </button>
              <button
                onClick={handleSaveField}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
              >
                저장
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 분류 추가 모달 */}
      {showCategoryModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl w-full max-w-md p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-bold text-lg">분류 추가</h3>
              <button onClick={() => setShowCategoryModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">분류 코드 *</label>
                <input
                  type="text"
                  value={categoryForm.code}
                  onChange={(e) => setCategoryForm({ ...categoryForm, code: e.target.value.toUpperCase() })}
                  placeholder="예: NEW-CODE"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">분류명 *</label>
                <input
                  type="text"
                  value={categoryForm.name}
                  onChange={(e) => setCategoryForm({ ...categoryForm, name: e.target.value })}
                  placeholder="예: 신규분류"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
              {categoryForm.parentId && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">상위 분류</label>
                  <p className="text-sm text-gray-500">
                    {categories.find(c => c.id === categoryForm.parentId)?.name}
                  </p>
                </div>
              )}
            </div>

            <div className="flex justify-end gap-2 mt-6">
              <button
                onClick={() => setShowCategoryModal(false)}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg text-sm"
              >
                취소
              </button>
              <button
                onClick={handleSaveCategory}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
              >
                추가
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============================================================
// 품목관리 컴포넌트 (목록/등록/수정/상세)
// ============================================================

// 품목 초기 데이터 (단가는 단가관리에서 별도 관리)
const initialItems = itemPriceMaster.map((item, idx) => ({
  id: idx + 1,
  itemCode: item.itemCode,
  itemName: item.itemName,
  category: item.category,
  itemType: item.category.includes('절곡') || item.category.includes('가이드') || item.category.includes('케이스') || item.category.includes('하단') || item.category.includes('연기') ? '반제품' :
    item.category.includes('전동') || item.category.includes('연동') || item.category.includes('샤프트') || item.category.includes('브라켓') || item.category.includes('앵글') ? '부품' :
      item.category.includes('검사') ? '서비스' : '원자재',
  unit: item.unit,
  spec: item.itemName.match(/\d+/) ? item.itemName.match(/[\d×\-]+/)?.[0] || '-' : '-',
  safetyStock: Math.floor(Math.random() * 20) + 5,
  currentStock: Math.floor(Math.random() * 50) + 10,
  leadTime: Math.floor(Math.random() * 7) + 1,
  isActive: true,
  createdAt: '2024-01-01',
}));

// 품목 목록 컴포넌트
// props.items가 전달되면 공유 상태 사용, 없으면 기본 데이터 사용
const ItemList = ({ onNavigate, items: externalItems, onAddItem, onUpdateItem, onDeleteItem }) => {
  // 외부 items가 전달되면 사용, 없으면 로컬 상태 사용
  const [localItems, setLocalItems] = useState(initialItems);
  const items = externalItems || localItems;
  const setItems = externalItems ? () => { } : setLocalItems; // 외부 상태면 로컬 setter 비활성화

  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  // 품목유형별 카운트
  const typeCount = {
    all: items.length,
    '제품': items.filter(i => i.itemType === '제품').length,
    '부품': items.filter(i => i.itemType === '부품').length,
    '부자재': items.filter(i => i.itemType === '부자재').length,
    '원자재': items.filter(i => i.itemType === '원자재').length,
    '소모품': items.filter(i => i.itemType === '소모품').length,
  };

  // 필터링된 품목 먼저 계산 (ID 내림차순 정렬 - 최신 등록 최상단)
  const filtered = items
    .filter(i => activeTab === 'all' || i.itemType === activeTab)
    .filter(i =>
      i.itemCode.toLowerCase().includes(search.toLowerCase()) ||
      i.itemName.includes(search) ||
      (i.spec && i.spec.includes(search))
    )
    .sort((a, b) => b.id - a.id);

  // 목록 선택 훅
  const {
    selectedIds,
    handleSelect,
    handleSelectAll,
    clearSelection,
    isAllSelected,
    hasSelection,
    isMultiSelect,
    isSelected,
  } = useListSelection(filtered);

  // 삭제 핸들러 (공유 상태 연동)
  const handleDelete = (item) => {
    if (window.confirm(`'${item.itemName}' 품목을 삭제하시겠습니까?`)) {
      if (onDeleteItem) {
        // 공유 상태 연동 시 부모로 삭제 요청
        onDeleteItem(item.id);
      } else {
        // 로컬 상태 사용 시
        setLocalItems(prev => prev.filter(i => i.id !== item.id));
      }
    }
  };

  const handleBulkDelete = () => {
    if (onDeleteItem) {
      // 공유 상태 연동 시 각 항목 삭제
      selectedIds.forEach(id => onDeleteItem(id));
    } else {
      // 로컬 상태 사용 시
      setLocalItems(prev => prev.filter(i => !selectedIds.includes(i.id)));
    }
    clearSelection();
    setShowDeleteModal(false);
  };

  const tabs = [
    { id: 'all', label: '전체', count: typeCount.all },
    { id: '제품', label: '제품', count: typeCount['제품'] },
    { id: '부품', label: '부품', count: typeCount['부품'] },
    { id: '부자재', label: '부자재', count: typeCount['부자재'] || 0 },
    { id: '원자재', label: '원자재', count: typeCount['원자재'] || 0 },
    { id: '소모품', label: '소모품', count: typeCount['소모품'] || 0 },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Package}
        title="품목 목록"
        actions={
          <Button variant="primary" onClick={() => onNavigate('item-create')}>
            <Plus className="w-4 h-4" /> 품목 등록
          </Button>
        }
      />

      {/* 통계 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center justify-between">
          <div>
            <p className="text-sm text-gray-500">전체 품목</p>
            <p className="text-2xl font-bold text-gray-900">{typeCount.all}</p>
          </div>
          <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
            <Package className="w-5 h-5 text-blue-600" />
          </div>
        </div>
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center justify-between">
          <div>
            <p className="text-sm text-gray-500">제품</p>
            <p className="text-2xl font-bold text-gray-900">{typeCount['제품']}</p>
          </div>
          <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
            <Package className="w-5 h-5 text-green-600" />
          </div>
        </div>
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center justify-between">
          <div>
            <p className="text-sm text-gray-500">부품</p>
            <p className="text-2xl font-bold text-gray-900">{typeCount['부품']}</p>
          </div>
          <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
            <Package className="w-5 h-5 text-purple-600" />
          </div>
        </div>
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center justify-between">
          <div>
            <p className="text-sm text-gray-500">부자재</p>
            <p className="text-2xl font-bold text-gray-900">{typeCount['부자재'] || 0}</p>
          </div>
          <div className="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center">
            <Package className="w-5 h-5 text-orange-600" />
          </div>
        </div>
      </div>

      {/* 검색바 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            placeholder="품목코드, 품목명, 규격 검색..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg text-sm"
          />
        </div>
      </div>

      {/* 목록 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200">
        <div className="p-4 border-b border-gray-200">
          <h3 className="font-semibold">전체 목록 ({filtered.length}개)</h3>
        </div>

        {/* 탭 */}
        <div className="px-4 pt-4 border-b border-gray-200">
          <div className="flex gap-1">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-4 py-2 text-sm font-medium rounded-t-lg transition-colors ${activeTab === tab.id
                    ? 'bg-gray-100 text-gray-900 border-b-2 border-gray-900'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
              >
                {tab.label} ({tab.count})
              </button>
            ))}
          </div>
        </div>

        {/* 선택 삭제 버튼 (2개 이상 선택 시) */}
        {isMultiSelect && (
          <div className="px-4 py-2 bg-blue-50 border-b border-blue-100">
            <div className="flex items-center justify-between">
              <span className="text-sm text-blue-700">{selectedIds.length}개 선택됨</span>
              <Button variant="danger" size="sm" onClick={() => setShowDeleteModal(true)}>
                <Trash2 className="w-4 h-4" /> 선택 삭제
              </Button>
            </div>
          </div>
        )}

        {/* 테이블 */}
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 border-b border-gray-200">
              <tr>
                <th className="px-4 py-3 text-center w-10">
                  <input
                    type="checkbox"
                    checked={isAllSelected}
                    onChange={handleSelectAll}
                    className="w-4 h-4 rounded border-gray-300"
                  />
                </th>
                <th className="px-4 py-3 text-left font-medium text-gray-600">번호</th>
                <th className="px-4 py-3 text-left font-medium text-gray-600">품목코드</th>
                <th className="px-4 py-3 text-left font-medium text-gray-600">품목유형</th>
                <th className="px-4 py-3 text-left font-medium text-gray-600">품목명</th>
                <th className="px-4 py-3 text-left font-medium text-gray-600">규격</th>
                <th className="px-4 py-3 text-left font-medium text-gray-600">단위</th>
                <th className="px-4 py-3 text-left font-medium text-gray-600">품목 상태</th>
                {hasSelection && <th className="px-4 py-3 text-center font-medium text-gray-600">작업</th>}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {filtered.slice(0, 20).map((item, index) => (
                <tr key={item.id} className={`hover:bg-gray-50 ${isSelected(item.id) ? 'bg-blue-50' : ''}`}>
                  <td className="px-4 py-3 text-center">
                    <input
                      type="checkbox"
                      checked={isSelected(item.id)}
                      onChange={() => handleSelect(item.id)}
                      onClick={(e) => e.stopPropagation()}
                      className="w-4 h-4 rounded border-gray-300"
                    />
                  </td>
                  <td className="px-4 py-3 text-gray-500">{filtered.length - index}</td>
                  <td className="px-4 py-3">
                    <span className="px-2 py-1 bg-gray-100 rounded text-xs font-mono">
                      {item.itemCode}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-1 rounded text-xs font-medium ${item.itemType === '제품' ? 'bg-blue-100 text-blue-700' :
                        item.itemType === '부품' ? 'bg-purple-100 text-purple-700' :
                          item.itemType === '부자재' ? 'bg-orange-100 text-orange-700' :
                            item.itemType === '원자재' ? 'bg-green-100 text-green-700' :
                              'bg-gray-100 text-gray-700'
                      }`}>
                      {item.itemType}
                    </span>
                  </td>
                  <td className="px-4 py-3 font-medium">{item.itemName}</td>
                  <td className="px-4 py-3 text-gray-600">{item.spec || '-'}</td>
                  <td className="px-4 py-3 text-gray-600">{item.unit}</td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-1 rounded text-xs font-medium ${item.isActive ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
                      }`}>
                      {item.isActive ? '사용중' : '미사용'}
                    </span>
                  </td>
                  {hasSelection && isSelected(item.id) && (
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-center gap-1">
                        <button
                          onClick={() => onNavigate('item-detail', item)}
                          className="p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded"
                          title="상세보기"
                        >
                          <Search className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => onNavigate('item-edit', item)}
                          className="p-1.5 text-gray-400 hover:text-green-600 hover:bg-green-50 rounded"
                          title="수정"
                        >
                          <Edit className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDelete(item)}
                          className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded"
                          title="삭제"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  )}
                  {hasSelection && !isSelected(item.id) && <td className="px-4 py-3"></td>}
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* 페이지네이션 */}
        <div className="p-4 border-t border-gray-200 flex items-center justify-between text-sm text-gray-600">
          <span>총 {filtered.length}개 중 1-{Math.min(20, filtered.length)}개 표시</span>
          <div className="flex gap-2">
            <button className="px-3 py-1 border border-gray-300 rounded hover:bg-gray-50">이전</button>
            <button className="px-3 py-1 bg-gray-900 text-white rounded">1</button>
            <button className="px-3 py-1 border border-gray-300 rounded hover:bg-gray-50">다음</button>
          </div>
        </div>
      </div>

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-md w-full mx-4">
            <h3 className="text-lg font-bold mb-4">품목 삭제</h3>
            <p className="text-gray-600 mb-6">선택한 {selectedIds.length}개 품목을 삭제하시겠습니까?</p>
            <div className="flex justify-end gap-2">
              <Button variant="ghost" onClick={() => setShowDeleteModal(false)}>취소</Button>
              <Button variant="danger" onClick={handleBulkDelete}>삭제</Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 품목 등록/수정 컴포넌트
const ItemForm = ({ item, onNavigate, isEdit = false, onAddItem, onUpdateItem }) => {
  const [formData, setFormData] = useState(item || {
    itemType: '',
    partSubType: '',
    productName: '',
    itemName: '',
    itemCode: '',
    lotPrefix: '',
    isActive: true,
    description: '',
    certNumber: '',
    certStartDate: '',
    certEndDate: '',
    needsBom: false,
    spec: '',
    material: '',
    unit: 'EA',
    installType: '',
    finishing: '',
    sideWidth: '',
    sideHeight: '',
    length: '',
    drawingInputType: 'file',
    drawingFile: '',
  });

  // 유효성 검사 규칙
  const validationRules = {
    itemType: { required: true, label: '품목유형', message: '품목유형을 선택해주세요.' },
    itemName: { required: true, label: '품목명', message: '품목명을 입력해주세요.' },
  };

  const { errors, touched, hasError, getFieldError, validateForm, handleBlur, clearFieldError } = useFormValidation(formData, validationRules);

  const [bomItems, setBomItems] = useState([]);
  const [showDrawingEditor, setShowDrawingEditor] = useState(false);
  const [drawingDetails, setDrawingDetails] = useState([]);

  // 전개도 상세 행 추가
  const addDrawingDetailRow = () => {
    const newRow = {
      id: Date.now(),
      seq: drawingDetails.length + 1,
      input: 0,
      elongation: -1,
      elongationCalc: -1,
      total: -(drawingDetails.length + 1),
      shadow: '',
      angle: '각도',
    };
    setDrawingDetails([...drawingDetails, newRow]);
  };

  // 전개도 상세 행 삭제
  const removeDrawingDetailRow = (id) => {
    setDrawingDetails(drawingDetails.filter(row => row.id !== id).map((row, idx) => ({
      ...row,
      seq: idx + 1,
      total: -(idx + 1),
    })));
  };

  // 전개도 상세 행 업데이트
  const updateDrawingDetailRow = (id, field, value) => {
    setDrawingDetails(drawingDetails.map(row =>
      row.id === id ? { ...row, [field]: value } : row
    ));
  };

  const itemTypes = [
    { value: '제품', label: '제품 (Finished Goods)', desc: '완제품으로 판매되는 품목' },
    { value: '부품', label: '부품 (Part)', desc: '제품 조립에 사용되는 부품' },
    { value: '부자재', label: '부자재 (Sub Material)', desc: '생산 보조 자재' },
    { value: '원자재', label: '원자재 (Raw Material)', desc: '가공 전 기본 재료' },
    { value: '소모품', label: '소모품 (Consumables)', desc: '소모성 자재' },
  ];

  const partSubTypes = [
    { value: '조립 부품', label: '조립 부품 (Assembly Part)' },
    { value: '절곡 부품', label: '절곡 부품 (Bending Part) - 전개도만 사용' },
    { value: '단일 부품', label: '단일 부품 (Single Part)' },
    { value: '가공 부품', label: '가공 부품 (Processed Part)' },
    { value: '구매 부품', label: '구매 부품 (Purchased Part)' },
  ];

  const partItemNames = ['가이드레일', '케이스', '하단마감재', '연기차단재', '전동개폐기', '연동제어기', '감기샤프트', '브라켓', '앵글', '환봉', '조인트바', '각파이프', '하장바', '엘바', '보강평철', '무게평철', '마구리', '상부덮개', 'BASE'];

  // 절곡 부품용 품목명 (설치유형 코드 포함)
  const bendingPartItemNames = [
    { value: '가이드레일(벽면형)', label: '가이드레일(벽면형) (R)', code: 'R' },
    { value: '가이드레일(측면형)', label: '가이드레일(측면형) (S)', code: 'S' },
    { value: '케이스', label: '케이스 (C)', code: 'C' },
    { value: '하단마감재(스크린)', label: '하단마감재(스크린) (B)', code: 'B' },
    { value: '하단마감재(철재)', label: '하단마감재(철재) (T)', code: 'T' },
    { value: 'L-Bar', label: 'L-Bar (L)', code: 'L' },
    { value: '연기차단재', label: '연기차단재 (G)', code: 'G' },
  ];

  // 절곡 부품용 종류 옵션 (lotTypeCodes 기반)
  const bendingPartTypes = [
    { value: '본체', label: '본체 (M)', code: 'M' },
    { value: '본체(철재)', label: '본체(철재) (T)', code: 'T' },
    { value: 'C형', label: 'C형 (C)', code: 'C' },
    { value: 'D형', label: 'D형 (D)', code: 'D' },
    { value: 'SUS마감재', label: 'SUS마감재 (S)', code: 'S' },
    { value: 'SUS마감재①', label: 'SUS마감재① (S)', code: 'S' },
    { value: 'SUS마감재②', label: 'SUS마감재② (U)', code: 'U' },
    { value: '전면부', label: '전면부 (F)', code: 'F' },
    { value: '점검구', label: '점검구 (P)', code: 'P' },
    { value: '린텔부', label: '린텔부 (L)', code: 'L' },
    { value: '후면코너부', label: '후면코너부 (B)', code: 'B' },
    { value: 'SUS', label: 'SUS (S)', code: 'S' },
    { value: 'EGI', label: 'EGI (E)', code: 'E' },
    { value: '스크린용', label: '스크린용 (A)', code: 'A' },
    { value: '화이바원단(W50)', label: '화이바원단(W50) (I)', code: 'I' },
    { value: '화이바원단(W80)', label: '화이바원단(W80) (I)', code: 'I' },
  ];

  // 절곡 부품용 모양&길이 옵션 (lotSizeCodes 기반)
  const bendingSizeLengths = [
    { value: '1219', label: '1219 (12)', code: '12' },
    { value: '2438', label: '2438 (24)', code: '24' },
    { value: '3000', label: '3000 (30)', code: '30' },
    { value: '3500', label: '3500 (35)', code: '35' },
    { value: '4000', label: '4000 (40)', code: '40' },
    { value: '4150', label: '4150 (41)', code: '41' },
    { value: '4200', label: '4200 (42)', code: '42' },
    { value: '4300', label: '4300 (43)', code: '43' },
  ];

  const installTypes = [{ value: '벽면형', label: '벽면형 (R)' }, { value: '측면형', label: '측면형 (S)' }];
  const units = ['M', 'mm', 'EA', 'SET', 'KG', 'T', 'BOX', 'L', 'M2', 'M3', 'ROLL', 'SHEET', 'PACK'];
  const finishings = ['SUS마감', 'EGI마감'];
  const lengths = ['1219', '2438', '3000', '3500'];

  const isProductType = formData.itemType === '제품';
  const isPartType = formData.itemType === '부품';
  const isSubMaterialType = formData.itemType === '부자재';
  const isRawMaterialType = formData.itemType === '원자재';
  const isConsumableType = formData.itemType === '소모품';
  const isAssemblyPart = isPartType && formData.partSubType === '조립 부품';
  const isBendingPart = isPartType && formData.partSubType === '절곡 부품';
  const isPurchasedPart = isPartType && formData.partSubType === '구매 부품';

  // 부자재 전용 옵션들
  const subMaterialItems = [
    {
      value: '스크린원단',
      label: '스크린원단',
      specs: ['0.3T', '0.4T', '0.5T', '0.6T'],
      code: 'SCR'
    },
    {
      value: '슬랫',
      label: '슬랫',
      specs: ['50mm', '75mm', '100mm'],
      code: 'SLT'
    },
    {
      value: '가이드레일',
      label: '가이드레일',
      specs: ['50×50', '60×60', '70×70', '80×80'],
      code: 'GR'
    },
    {
      value: '샤프트',
      label: '샤프트',
      specs: ['4인치', '5인치', '6인치'],
      code: 'SFT'
    },
    {
      value: '스프링',
      label: '스프링',
      specs: ['소형', '중형', '대형'],
      code: 'SPR'
    },
    {
      value: '체인',
      label: '체인',
      specs: ['#25', '#35', '#40'],
      code: 'CHN'
    },
  ];

  // 부자재 규격 옵션 (품목명에 따라 필터링)
  const getSubMaterialSpecs = () => {
    const selectedItem = subMaterialItems.find(item => item.value === formData.itemName);
    return selectedItem?.specs || [];
  };

  // 부자재 품목코드 자동생성
  // 새 규칙: 품목명-규격
  // 예: 연동제어기-매립(유선)
  const getSubMaterialCode = () => {
    if (!formData.itemName) return '';
    const itemName = formData.itemName;
    const spec = formData.spec || '';
    // 패턴: 품목명-규격
    return spec ? `${itemName}-${spec}` : itemName;
  };

  // 원자재 전용 옵션들
  const rawMaterialItems = [
    {
      value: '철판',
      label: '철판',
      specs: ['1.0T', '1.2T', '1.6T', '2.0T', '2.3T', '3.0T'],
      code: 'STEEL'
    },
    {
      value: '아연도금강판',
      label: '아연도금강판',
      specs: ['0.8T', '1.0T', '1.2T', '1.6T'],
      code: 'EGI'
    },
    {
      value: '스테인리스',
      label: '스테인리스',
      specs: ['0.8T', '1.0T', '1.2T', '1.5T', '2.0T'],
      code: 'SUS'
    },
    {
      value: '알루미늄판',
      label: '알루미늄판',
      specs: ['1.0T', '1.5T', '2.0T', '3.0T'],
      code: 'AL'
    },
    {
      value: '각파이프',
      label: '각파이프',
      specs: ['30×30', '40×40', '50×50', '60×60'],
      code: 'PIPE'
    },
  ];

  // 원자재 규격 옵션 (품목명에 따라 필터링)
  const getRawMaterialSpecs = () => {
    const selectedItem = rawMaterialItems.find(item => item.value === formData.itemName);
    return selectedItem?.specs || [];
  };

  // 원자재 품목코드 자동생성
  // 새 규칙: 품목명-규격
  // 예: 철판-SUS-1.2T
  const getRawMaterialCode = () => {
    if (!formData.itemName) return '';
    const itemName = formData.itemName;
    const spec = formData.spec || '';
    // 패턴: 품목명-규격
    return spec ? `${itemName}-${spec}` : itemName;
  };

  // 소모품 품목코드 자동생성
  // 새 규칙: 품목명-규격
  // 예: 용접봉-3.2MM, 장갑-면장갑
  const getConsumableCode = () => {
    if (!formData.itemName) return '';
    const itemName = formData.itemName;
    const spec = formData.spec || '';
    // 패턴: 품목명-규격
    return spec ? `${itemName}-${spec}` : itemName;
  };

  // 구매 부품 전용 옵션들
  const purchasedPartItemNames = [
    { value: '전동개폐기', label: '전동개폐기 (E)', code: 'E' },
    { value: '수동개폐기', label: '수동개폐기 (M)', code: 'M' },
    { value: '제어반', label: '제어반 (CTL)', code: 'CTL' },
    { value: '연기감지기', label: '연기감지기 (SMK)', code: 'SMK' },
    { value: '열감지기', label: '열감지기 (HT)', code: 'HT' },
    { value: '비상스위치', label: '비상스위치 (SW)', code: 'SW' },
  ];
  const powerOptions = ['220V', '380V'];
  const capacityOptions = ['150 KG', '300 KG', '400 KG', '500 KG', '600 KG', '800 KG', '1000 KG'];

  // 구매 부품 품목코드 자동생성
  // 새 규칙: 품목명-규격 (규격 = 전원 + 용량, 공백 없이 연결)
  // 예: 전동개폐기-220V300KG
  const getPurchasedPartCode = () => {
    if (!formData.itemName) return '';
    const itemName = formData.itemName;
    const power = formData.power || '';
    const capacity = formData.capacity || '';
    // 규격 = 전원 + 용량 (공백 제거)
    const spec = `${power}${capacity}`.replace(/\s/g, '');
    // 패턴: 품목명-규격
    return spec ? `${itemName}-${spec}` : itemName;
  };

  const handleSubmit = () => {
    // 유효성 검사 실행
    if (!validateForm()) {
      return;
    }
    if (isPartType && !formData.partSubType) {
      alert('부품 유형을 선택해주세요.');
      return;
    }

    // 공유 상태 연동: 품목 추가/수정 시 콜백 호출
    const itemData = {
      ...formData,
      itemCode: formData.itemCode || `ITEM-${Date.now()}`,
      createdAt: item?.createdAt || new Date().toISOString().slice(0, 10),
      purchasePrice: formData.purchasePrice || 0,
      sellingPrice: formData.sellingPrice || 0,
      marginRate: 20,
    };

    if (isEdit && onUpdateItem) {
      onUpdateItem({ ...item, ...itemData });
    } else if (onAddItem) {
      onAddItem(itemData);
    }

    alert(isEdit ? '품목이 수정되었습니다.' : '품목이 등록되었습니다.');
    onNavigate('item-list');
  };

  const addBomItem = () => {
    setBomItems([...bomItems, {
      id: Date.now(),
      itemCode: '',
      itemName: '',
      spec: '',
      material: '',
      quantity: 1,
      unit: 'EA',
      price: 0,
      description: '',
    }]);
  };

  const removeBomItem = (id) => {
    setBomItems(bomItems.filter(item => item.id !== id));
  };

  const updateBomItem = (id, field, value) => {
    setBomItems(bomItems.map(item =>
      item.id === id ? { ...item, [field]: value } : item
    ));
  };

  // 품목코드 자동생성 미리보기 (조립부품 새 규칙)
  // 패턴: 품목명 설치유형-측면규격(가로)*측면규격(세로)*길이(앞2자리)
  // 예: 가이드레일 벽면형-1211*1111*24
  const getAutoItemCode = () => {
    if (!formData.itemName) return '';
    const installType = formData.installType || '?';
    const sideWidth = formData.sideWidth || '?';
    const sideHeight = formData.sideHeight || '?';
    const lengthCode = formData.length ? String(formData.length).substring(0, 2) : '?';
    return `${formData.itemName} ${installType}-${sideWidth}*${sideHeight}*${lengthCode}`;
  };

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Package}
        title={isEdit ? '품목 수정' : '품목 등록'}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => onNavigate('item-list')}>
              취소
            </Button>
            <Button variant="primary" onClick={handleSubmit}>
              <Save className="w-4 h-4" /> 저장
            </Button>
          </div>
        }
      />

      {/* 기본 정보 - 품목유형 드롭다운 방식 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <h3 className="text-lg font-semibold mb-4 pb-2 border-b">기본 정보</h3>
        <div className="space-y-4">
          {/* 품목유형 드롭다운 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              품목유형 <span className="text-red-500">*</span> <span className="text-blue-600">(먼저 선택하세요)</span>
            </label>
            <select
              value={formData.itemType}
              onChange={(e) => {
                setFormData({ ...formData, itemType: e.target.value, partSubType: '' });
                clearFieldError('itemType');
              }}
              onBlur={() => handleBlur('itemType')}
              className={getInputClassName(hasError('itemType'))}
            >
              <option value="">품목 유형을 선택하세요</option>
              {itemTypes.map(type => (
                <option key={type.value} value={type.value}>{type.label}</option>
              ))}
            </select>
            {hasError('itemType') ? (
              <p className="text-xs text-red-500 mt-1">{getFieldError('itemType')}</p>
            ) : (
              <p className="text-xs text-red-500 mt-1">* 품목 유형에 따라 입력 항목이 다릅니다</p>
            )}
          </div>

          {/* 품목유형 미선택 시 경고 */}
          {!formData.itemType && (
            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 flex items-center gap-3">
              <AlertCircle className="w-5 h-5 text-yellow-600" />
              <span className="text-yellow-800">품목유형을 먼저 선택해주세요. 선택한 유형에 따라 입력 항목이 달라집니다.</span>
            </div>
          )}

          {/* 부품일 때 부품 유형 선택 */}
          {isPartType && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                부품 유형 <span className="text-red-500">*</span>
              </label>
              <select
                value={formData.partSubType}
                onChange={(e) => setFormData({ ...formData, partSubType: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              >
                <option value="">부품 유형을 선택하세요</option>
                {partSubTypes.map(type => (
                  <option key={type.value} value={type.value}>{type.label}</option>
                ))}
              </select>
              {/* 절곡 부품 안내 메시지 */}
              {isBendingPart && (
                <p className="text-xs text-gray-500 mt-1">* 절곡 부품은 전개도(바라시)만 있으며, 부품 구성(BOM)은 사용하지 않습니다.</p>
              )}
            </div>
          )}

          {/* 절곡 부품일 때 필드들 */}
          {isBendingPart && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  품목명 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.itemName}
                  onChange={(e) => {
                    setFormData({ ...formData, itemName: e.target.value, bendingPartItemName: e.target.value });
                    clearFieldError('itemName');
                  }}
                  onBlur={() => handleBlur('itemName')}
                  className={getInputClassName(hasError('itemName'))}
                >
                  <option value="">품목명을 선택하세요</option>
                  {bendingPartItemNames.map(item => (
                    <option key={item.value} value={item.value}>{item.label}</option>
                  ))}
                </select>
                {hasError('itemName') && <p className="text-xs text-red-500 mt-1">{getFieldError('itemName')}</p>}
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  종류 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.bendingPartType || ''}
                  onChange={(e) => setFormData({ ...formData, bendingPartType: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  <option value="">종류를 선택하세요</option>
                  {bendingPartTypes.map(type => (
                    <option key={type.value} value={type.value}>{type.label}</option>
                  ))}
                </select>
                <p className="text-xs text-gray-500 mt-1">* 절곡부품의 종류를 선택합니다 (본체, C형, D형 등)</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  모양&길이 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.bendingSizeLength || ''}
                  onChange={(e) => setFormData({ ...formData, bendingSizeLength: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  <option value="">모양&길이를 선택하세요</option>
                  {bendingSizeLengths.map(size => (
                    <option key={size.value} value={size.value}>{size.label}</option>
                  ))}
                </select>
                <p className="text-xs text-gray-500 mt-1">* 절곡부품의 길이를 선택합니다 (앞 2자리가 코드로 사용)</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목코드 미리보기</label>
                <input
                  type="text"
                  value={(() => {
                    const itemName = formData.itemName || '';
                    const partType = formData.bendingPartType || '';
                    const sizeLength = formData.bendingSizeLength || '';
                    const productCode = bendingPartItemNames.find(i => i.value === itemName)?.code || '';
                    const typeCode = bendingPartTypes.find(t => t.value === partType)?.code || '';
                    const sizeCode = bendingSizeLengths.find(s => s.value === sizeLength)?.code || (sizeLength ? String(sizeLength).substring(0, 2) : '');
                    return `${productCode}${typeCode}${sizeCode}` || '품목명, 종류, 모양&길이를 선택하세요';
                  })()}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-blue-50 text-blue-800 font-mono"
                  disabled
                />
                <p className="text-xs text-blue-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 절곡부품 코드규칙: 품목코드 + 종류코드 + 모양&길이코드 (공통코드관리 설정)
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목 상태</label>
                <select
                  value={formData.isActive ? '활성' : '비활성'}
                  onChange={(e) => setFormData({ ...formData, isActive: e.target.value === '활성' })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  <option value="활성">활성</option>
                  <option value="비활성">비활성</option>
                </select>
                <p className="text-xs text-gray-500 mt-1">* 비활성 시 품목 사용이 제한됩니다</p>
              </div>
            </>
          )}

          {/* 조립 부품일 때 추가 필드들 */}
          {isAssemblyPart && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  품목명 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.itemName}
                  onChange={(e) => {
                    setFormData({ ...formData, itemName: e.target.value });
                    clearFieldError('itemName');
                  }}
                  onBlur={() => handleBlur('itemName')}
                  className={getInputClassName(hasError('itemName'))}
                >
                  <option value="">품목명을 선택하세요</option>
                  {partItemNames.map(name => (
                    <option key={name} value={name}>{name}</option>
                  ))}
                </select>
                {hasError('itemName') && <p className="text-xs text-red-500 mt-1">{getFieldError('itemName')}</p>}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  설치 유형 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.installType}
                  onChange={(e) => setFormData({ ...formData, installType: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  <option value="">설치 유형을 선택하세요</option>
                  {installTypes.map(type => (
                    <option key={type.value} value={type.value}>{type.label}</option>
                  ))}
                </select>
                <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 품목기준관리에서 관리되는 항목입니다 (13개 옵션)
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  단위 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.unit}
                  onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  <option value="">단위를 선택하세요</option>
                  {units.map(unit => (
                    <option key={unit} value={unit}>{unit}</option>
                  ))}
                </select>
                <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 품목기준관리에서 관리되는 항목입니다 (13개 옵션)
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  마감 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.finishing}
                  onChange={(e) => setFormData({ ...formData, finishing: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  <option value="">마감을 선택하세요</option>
                  {finishings.map(f => (
                    <option key={f} value={f}>{f}</option>
                  ))}
                </select>
                <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 품목기준관리에서 관리되는 항목입니다 (2개 옵션)
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <input
                  type="text"
                  value={formData.description || ''}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                  placeholder="비고 사항을 입력하세요"
                />
              </div>
            </>
          )}

          {/* 제품일 때 기존 필드들 */}
          {isProductType && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">상품명</label>
                <input
                  type="text"
                  value={formData.productName}
                  onChange={(e) => setFormData({ ...formData, productName: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                  placeholder="상품명을 입력하세요"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목명 <span className="text-red-500">*</span></label>
                <input
                  type="text"
                  value={formData.itemName}
                  onChange={(e) => {
                    // 제품의 경우 품목명 = 품목코드 규칙 적용
                    setFormData({ ...formData, itemName: e.target.value, itemCode: e.target.value });
                    clearFieldError('itemName');
                  }}
                  onBlur={() => handleBlur('itemName')}
                  className={getInputClassName(hasError('itemName'))}
                  placeholder="품목명을 입력하세요 (예: 방화셔터 W3000×H4000)"
                />
                {hasError('itemName') && <p className="text-xs text-red-500 mt-1">{getFieldError('itemName')}</p>}
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목코드</label>
                <input
                  type="text"
                  value={formData.itemName || ''}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-blue-50 text-blue-800 font-mono"
                  placeholder="품목명 입력 시 자동 적용"
                  disabled
                />
                <p className="text-xs text-blue-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 제품은 품목명 = 품목코드 규칙이 적용됩니다 (공통코드관리 설정)
                </p>
              </div>
            </>
          )}

          {/* 부자재일 때 필드들 */}
          {isSubMaterialType && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  품목명 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.itemName}
                  onChange={(e) => {
                    setFormData({ ...formData, itemName: e.target.value, spec: '' });
                    clearFieldError('itemName');
                  }}
                  onBlur={() => handleBlur('itemName')}
                  className={getInputClassName(hasError('itemName'))}
                >
                  <option value="">품목명을 선택하세요</option>
                  {subMaterialItems.map(item => (
                    <option key={item.value} value={item.value}>{item.label}</option>
                  ))}
                </select>
                {hasError('itemName') && <p className="text-xs text-red-500 mt-1">{getFieldError('itemName')}</p>}
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  규격 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.spec || ''}
                  onChange={(e) => setFormData({ ...formData, spec: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                  disabled={!formData.itemName}
                >
                  <option value="">규격을 선택하세요</option>
                  {getSubMaterialSpecs().map(spec => (
                    <option key={spec} value={spec}>{spec}</option>
                  ))}
                </select>
                <p className="text-xs text-gray-500 mt-1">* 규격은 품목명 선택 시 자동으로 필터링됩니다</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목코드 미리보기</label>
                <input
                  type="text"
                  value={getSubMaterialCode()}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-blue-50 text-blue-800 font-mono"
                  placeholder="품목명, 규격을 선택하세요"
                  disabled
                />
                <p className="text-xs text-blue-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 부자재 코드규칙: 품목명-규격 (공통코드관리 설정)
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목 상태</label>
                <select
                  value={formData.isActive ? '활성' : '비활성'}
                  onChange={(e) => setFormData({ ...formData, isActive: e.target.value === '활성' })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  <option value="활성">활성</option>
                  <option value="비활성">비활성</option>
                </select>
                <p className="text-xs text-gray-500 mt-1">* 비활성 시 품목 사용이 제한됩니다</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  단위 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.unit}
                  onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  {units.map(unit => (
                    <option key={unit} value={unit}>{unit}</option>
                  ))}
                </select>
                <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 품목기준관리에서 관리되는 항목입니다 (13개 옵션)
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <input
                  type="text"
                  value={formData.description || ''}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                  placeholder="비고 사항을 입력하세요"
                />
              </div>
            </>
          )}

          {/* 원자재일 때 필드들 */}
          {isRawMaterialType && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  품목명 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.itemName}
                  onChange={(e) => {
                    setFormData({ ...formData, itemName: e.target.value, spec: '' });
                    clearFieldError('itemName');
                  }}
                  onBlur={() => handleBlur('itemName')}
                  className={getInputClassName(hasError('itemName'))}
                >
                  <option value="">품목명을 선택하세요</option>
                  {rawMaterialItems.map(item => (
                    <option key={item.value} value={item.value}>{item.label}</option>
                  ))}
                </select>
                {hasError('itemName') && <p className="text-xs text-red-500 mt-1">{getFieldError('itemName')}</p>}
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  규격 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.spec || ''}
                  onChange={(e) => setFormData({ ...formData, spec: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                  disabled={!formData.itemName}
                >
                  <option value="">규격을 선택하세요</option>
                  {getRawMaterialSpecs().map(spec => (
                    <option key={spec} value={spec}>{spec}</option>
                  ))}
                </select>
                <p className="text-xs text-gray-500 mt-1">* 규격은 품목명 선택 시 자동으로 필터링됩니다</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목코드 미리보기</label>
                <input
                  type="text"
                  value={getRawMaterialCode()}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-blue-50 text-blue-800 font-mono"
                  placeholder="품목명, 규격을 선택하세요"
                  disabled
                />
                <p className="text-xs text-blue-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 원자재 코드규칙: 품목명-규격 (공통코드관리 설정)
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목 상태</label>
                <select
                  value={formData.isActive ? '활성' : '비활성'}
                  onChange={(e) => setFormData({ ...formData, isActive: e.target.value === '활성' })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  <option value="활성">활성</option>
                  <option value="비활성">비활성</option>
                </select>
                <p className="text-xs text-gray-500 mt-1">* 비활성 시 품목 사용이 제한됩니다</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  단위 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.unit}
                  onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  {units.map(unit => (
                    <option key={unit} value={unit}>{unit}</option>
                  ))}
                </select>
                <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 품목기준관리에서 관리되는 항목입니다 (13개 옵션)
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <input
                  type="text"
                  value={formData.description || ''}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                  placeholder="비고 사항을 입력하세요"
                />
              </div>
            </>
          )}

          {/* 소모품일 때 필드들 */}
          {isConsumableType && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  품목명 <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={formData.itemName}
                  onChange={(e) => {
                    setFormData({ ...formData, itemName: e.target.value });
                    clearFieldError('itemName');
                  }}
                  onBlur={() => handleBlur('itemName')}
                  className={getInputClassName(hasError('itemName'))}
                  placeholder="품목명을 입력하세요"
                />
                {hasError('itemName') && <p className="text-xs text-red-500 mt-1">{getFieldError('itemName')}</p>}
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  규격(사양) <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={formData.spec || ''}
                  onChange={(e) => setFormData({ ...formData, spec: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                  placeholder="예: 면-L, 고급형, A4"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목코드 미리보기</label>
                <input
                  type="text"
                  value={getConsumableCode()}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-blue-50 text-blue-800 font-mono"
                  placeholder="품목명, 규격을 입력하세요"
                  disabled
                />
                <p className="text-xs text-blue-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 소모품 코드규칙: 품목명-규격 (공통코드관리 설정)
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  단위 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.unit}
                  onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  {units.map(unit => (
                    <option key={unit} value={unit}>{unit}</option>
                  ))}
                </select>
                <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 품목기준관리에서 관리되는 항목입니다 (13개 옵션)
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <input
                  type="text"
                  value={formData.description || ''}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                  placeholder="비고 사항을 입력하세요"
                />
              </div>
            </>
          )}

          {/* 구매 부품일 때 필드들 */}
          {isPurchasedPart && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  품목명 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.itemName}
                  onChange={(e) => {
                    setFormData({ ...formData, itemName: e.target.value, power: '', capacity: '' });
                    clearFieldError('itemName');
                  }}
                  onBlur={() => handleBlur('itemName')}
                  className={getInputClassName(hasError('itemName'))}
                >
                  <option value="">품목명을 선택하세요</option>
                  {purchasedPartItemNames.map(item => (
                    <option key={item.value} value={item.value}>{item.label}</option>
                  ))}
                </select>
                {hasError('itemName') && <p className="text-xs text-red-500 mt-1">{getFieldError('itemName')}</p>}
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  전원 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.power || ''}
                  onChange={(e) => setFormData({ ...formData, power: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  <option value="">전원을 선택하세요</option>
                  {powerOptions.map(power => (
                    <option key={power} value={power}>{power}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  용량 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.capacity || ''}
                  onChange={(e) => setFormData({ ...formData, capacity: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  <option value="">용량을 선택하세요</option>
                  {capacityOptions.map(cap => (
                    <option key={cap} value={cap}>{cap}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  단위 <span className="text-red-500">*</span>
                </label>
                <select
                  value={formData.unit}
                  onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  {units.map(unit => (
                    <option key={unit} value={unit}>{unit}</option>
                  ))}
                </select>
                <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 품목기준관리에서 관리되는 항목입니다 (13개 옵션)
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <input
                  type="text"
                  value={formData.description || ''}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                  placeholder="비고 사항을 입력하세요"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목코드 미리보기</label>
                <input
                  type="text"
                  value={getPurchasedPartCode()}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-blue-50 text-blue-800 font-mono"
                  placeholder="품목명, 전원, 용량을 선택하세요"
                  disabled
                />
                <p className="text-xs text-blue-600 mt-1 flex items-center gap-1">
                  <Check className="w-3 h-3" /> 구매부품 코드규칙: 품목명-규격 (규격 = 전원 + 용량) (공통코드관리 설정)
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목 상태</label>
                <select
                  value={formData.isActive ? '활성' : '비활성'}
                  onChange={(e) => setFormData({ ...formData, isActive: e.target.value === '활성' })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  <option value="활성">활성</option>
                  <option value="비활성">비활성</option>
                </select>
                <p className="text-xs text-gray-500 mt-1">* 비활성 시 품목 사용이 제한됩니다</p>
              </div>
              <div>
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={formData.needsBom}
                    onChange={(e) => setFormData({ ...formData, needsBom: e.target.checked })}
                    className="w-4 h-4 text-blue-600 rounded"
                  />
                  <span className="text-sm font-medium">부품구성 (BOM) 필요</span>
                </label>
                <p className="text-xs text-gray-500 mt-1 ml-6">* 이 부품이 하위 구성품을 포함하는 경우 체크하세요</p>
              </div>
            </>
          )}

          {/* 부품 - 비조립/비절곡/비구매 부품 선택 시 기본 필드 */}
          {isPartType && formData.partSubType && !isAssemblyPart && !isBendingPart && !isPurchasedPart && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목명 <span className="text-red-500">*</span></label>
                <input
                  type="text"
                  value={formData.itemName}
                  onChange={(e) => {
                    setFormData({ ...formData, itemName: e.target.value });
                    clearFieldError('itemName');
                  }}
                  onBlur={() => handleBlur('itemName')}
                  className={getInputClassName(hasError('itemName'))}
                  placeholder="품목명을 입력하세요"
                />
                {hasError('itemName') && <p className="text-xs text-red-500 mt-1">{getFieldError('itemName')}</p>}
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">규격</label>
                <input
                  type="text"
                  value={formData.spec || ''}
                  onChange={(e) => setFormData({ ...formData, spec: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                  placeholder="규격을 입력하세요"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">단위</label>
                <select
                  value={formData.unit}
                  onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                >
                  {units.map(unit => (
                    <option key={unit} value={unit}>{unit}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <textarea
                  value={formData.description || ''}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                  rows={2}
                  placeholder="비고를 입력하세요"
                />
              </div>
            </>
          )}
        </div>
      </div>

      {/* 절곡 부품일 때 전개도 섹션 */}
      {isBendingPart && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center gap-2 mb-4 pb-2 border-b">
            <Layers className="w-5 h-5 text-gray-600" />
            <h3 className="text-lg font-semibold">절곡품 전개도 (바라시)</h3>
          </div>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">입력방식 선택</label>
              <div className="flex items-center gap-6">
                <label className="flex items-center gap-2">
                  <input
                    type="radio"
                    checked={formData.drawingInputType === 'file'}
                    onChange={() => setFormData({ ...formData, drawingInputType: 'file' })}
                    className="w-4 h-4 text-blue-600"
                  />
                  <span className="text-sm">파일 선택 (이미지 파일 업로드)</span>
                </label>
                <label className="flex items-center gap-2">
                  <input
                    type="radio"
                    checked={formData.drawingInputType === 'drawing'}
                    onChange={() => setFormData({ ...formData, drawingInputType: 'drawing' })}
                    className="w-4 h-4 text-blue-600"
                  />
                  <span className="text-sm">드로잉 (직접 그리기)</span>
                </label>
              </div>
              <p className="text-xs text-gray-500 mt-1">* 전개도 이미지를 파일로 업로드하거나 직접 그릴 수 있습니다</p>
            </div>

            {formData.drawingInputType === 'file' ? (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">파일 선택</label>
                <div className="flex items-center gap-2">
                  <input
                    type="text"
                    value={formData.drawingFile || ''}
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
                    placeholder="파일 선택"
                    disabled
                  />
                  <Button variant="outline" className="shrink-0">
                    <Upload className="w-4 h-4" /> 파일 선택
                  </Button>
                </div>
                <p className="text-xs text-gray-500 mt-1">* 절곡품 전개도 이미지를 업로드하세요 (JPG, PNG, PDF 등)</p>
              </div>
            ) : (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">드로잉</label>
                <p className="text-xs text-gray-500 mb-2">* '전개도 그리기' 버튼을 클릭하여 캔버스에 직접 그릴 수 있습니다</p>
                <Button variant="outline" onClick={() => setShowDrawingEditor(true)}>
                  <Edit3 className="w-4 h-4" /> 전개도 그리기
                </Button>
              </div>
            )}

            {/* 미리보기 영역 */}
            <div className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-medium text-gray-700">미리보기</span>
                {formData.drawingFile && (
                  <button className="text-sm text-red-500 hover:text-red-700 flex items-center gap-1">
                    <X className="w-4 h-4" /> 전개도 삭제
                  </button>
                )}
              </div>
              <div className="min-h-[200px] bg-gray-50 rounded-lg flex items-center justify-center text-gray-400">
                {formData.drawingFile ? (
                  <div className="text-center">
                    <img src="/api/placeholder/300/200" alt="전개도 미리보기" className="max-w-full h-auto" />
                  </div>
                ) : (
                  <span>전개도 이미지가 없습니다</span>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 절곡 부품일 때 전개도 상세 입력 (치수 계산) */}
      {isBendingPart && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4 pb-2 border-b">
            <h3 className="text-lg font-semibold">전개도 상세 입력 (치수 계산)</h3>
            <Button variant="outline" onClick={addDrawingDetailRow}>
              <Plus className="w-4 h-4" /> 행 추가
            </Button>
          </div>

          {drawingDetails.length === 0 ? (
            <div className="text-center py-8 text-gray-500 border border-dashed border-gray-300 rounded-lg">
              전개도 상세 치수를 입력하세요. '행 추가' 버튼을 클릭하여 행을 추가합니다.
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-3 py-2 text-center font-medium text-gray-600 w-16">번호</th>
                    <th className="px-3 py-2 text-center font-medium text-gray-600">입력</th>
                    <th className="px-3 py-2 text-center font-medium text-gray-600">연신율</th>
                    <th className="px-3 py-2 text-center font-medium text-gray-600">연신율계산후</th>
                    <th className="px-3 py-2 text-center font-medium text-gray-600">합계</th>
                    <th className="px-3 py-2 text-center font-medium text-gray-600">음영</th>
                    <th className="px-3 py-2 text-center font-medium text-gray-600">A각</th>
                    <th className="px-3 py-2 text-center font-medium text-gray-600 w-16">삭제</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {drawingDetails.map((row) => (
                    <tr key={row.id}>
                      <td className="px-3 py-2 text-center">
                        <span className="text-sm font-medium">{row.seq}</span>
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="number"
                          value={row.input}
                          onChange={(e) => updateDrawingDetailRow(row.id, 'input', parseFloat(e.target.value) || 0)}
                          className="w-full px-2 py-1 border border-gray-300 rounded text-sm text-center"
                        />
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="number"
                          value={row.elongation}
                          onChange={(e) => updateDrawingDetailRow(row.id, 'elongation', parseFloat(e.target.value) || 0)}
                          className="w-full px-2 py-1 border border-gray-300 rounded text-sm text-center"
                        />
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="number"
                          value={row.elongationCalc}
                          onChange={(e) => updateDrawingDetailRow(row.id, 'elongationCalc', parseFloat(e.target.value) || 0)}
                          className="w-full px-2 py-1 border border-gray-300 rounded text-sm text-center bg-gray-50"
                        />
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="number"
                          value={row.total}
                          className="w-full px-2 py-1 border border-gray-300 rounded text-sm text-center bg-gray-50"
                          readOnly
                        />
                      </td>
                      <td className="px-3 py-2 text-center">
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={row.shadow === 'on'}
                            onChange={(e) => updateDrawingDetailRow(row.id, 'shadow', e.target.checked ? 'on' : '')}
                            className="sr-only peer"
                          />
                          <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div>
                        </label>
                      </td>
                      <td className="px-3 py-2">
                        <select
                          value={row.angle}
                          onChange={(e) => updateDrawingDetailRow(row.id, 'angle', e.target.value)}
                          className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                        >
                          <option value="각도">각도</option>
                          <option value="90">90°</option>
                          <option value="45">45°</option>
                          <option value="135">135°</option>
                          <option value="직선">직선</option>
                        </select>
                      </td>
                      <td className="px-3 py-2 text-center">
                        <button
                          onClick={() => removeDrawingDetailRow(row.id)}
                          className="p-1 text-red-500 hover:bg-red-50 rounded"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          <div className="mt-4 p-3 bg-blue-50 rounded-lg">
            <p className="text-xs text-blue-700">
              * 연신율: 절곡 시 소재가 늘어나는 비율 계산값
              <br />
              * 합계: 입력값 + 연신율계산후 값의 누적 합
              <br />
              * 음영: 전개도에서 절곡 방향을 표시할 때 사용
            </p>
          </div>
        </div>
      )}

      {/* 조립 부품일 때 측면 규격 및 길이 섹션 */}
      {isAssemblyPart && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-semibold mb-4 pb-2 border-b">측면 규격 및 길이</h3>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                측면 규격 (가로) <span className="text-red-500">*</span>
              </label>
              <input
                type="number"
                value={formData.sideWidth}
                onChange={(e) => setFormData({ ...formData, sideWidth: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                placeholder="예: 50"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                측면 규격 (세로) <span className="text-red-500">*</span>
              </label>
              <input
                type="number"
                value={formData.sideHeight}
                onChange={(e) => setFormData({ ...formData, sideHeight: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                placeholder="예: 100"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                길이 <span className="text-red-500">*</span>
              </label>
              <select
                value={formData.length}
                onChange={(e) => setFormData({ ...formData, length: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              >
                <option value="">길이 선택</option>
                {lengths.map(l => (
                  <option key={l} value={l}>{l}</option>
                ))}
              </select>
              <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                <Check className="w-3 h-3" /> 품목기준관리에서 관리되는 항목입니다 (4개 옵션)
              </p>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">품목코드 미리보기</label>
              <input
                type="text"
                value={getAutoItemCode()}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-blue-50 text-blue-800 font-mono"
                disabled
              />
              <p className="text-xs text-blue-600 mt-1 flex items-center gap-1">
                <Check className="w-3 h-3" /> 조립부품 코드규칙: 품목명 설치유형-측면규격(가로)*측면규격(세로)*길이(앞2자리) (공통코드관리 설정)
              </p>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">품목 상태</label>
              <select
                value={formData.isActive ? '활성' : '비활성'}
                onChange={(e) => setFormData({ ...formData, isActive: e.target.value === '활성' })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              >
                <option value="활성">활성</option>
                <option value="비활성">비활성</option>
              </select>
              <p className="text-xs text-gray-500 mt-1">* 비활성 시 품목 사용이 제한됩니다</p>
            </div>
            <div>
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={formData.needsBom}
                  onChange={(e) => setFormData({ ...formData, needsBom: e.target.checked })}
                  className="w-4 h-4 text-blue-600 rounded"
                />
                <span className="text-sm font-medium">부품구성 (BOM) 필요</span>
              </label>
              <p className="text-xs text-gray-500 mt-1 ml-6">* 이 부품이 하위 구성품을 포함하는 경우 체크하세요</p>
            </div>
          </div>
        </div>
      )}

      {/* 조립 부품일 때 전개도 섹션 */}
      {isAssemblyPart && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center gap-2 mb-4 pb-2 border-b">
            <Layers className="w-5 h-5 text-gray-600" />
            <h3 className="text-lg font-semibold">조립품 전개도 (바라시)</h3>
          </div>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">입력방식 선택</label>
              <div className="flex items-center gap-6">
                <label className="flex items-center gap-2">
                  <input
                    type="radio"
                    checked={formData.drawingInputType === 'file'}
                    onChange={() => setFormData({ ...formData, drawingInputType: 'file' })}
                    className="w-4 h-4 text-blue-600"
                  />
                  <span className="text-sm">파일 선택 (이미지 파일 업로드)</span>
                </label>
                <label className="flex items-center gap-2">
                  <input
                    type="radio"
                    checked={formData.drawingInputType === 'drawing'}
                    onChange={() => setFormData({ ...formData, drawingInputType: 'drawing' })}
                    className="w-4 h-4 text-blue-600"
                  />
                  <span className="text-sm">드로잉 (직접 그리기)</span>
                </label>
              </div>
              <p className="text-xs text-gray-500 mt-1">* 전개도 이미지를 파일로 업로드하거나 직접 그릴 수 있습니다</p>
            </div>

            {formData.drawingInputType === 'file' ? (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">파일 선택</label>
                <div className="flex items-center gap-2">
                  <input
                    type="text"
                    value={formData.drawingFile || ''}
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
                    placeholder="파일 선택"
                    disabled
                  />
                  <Button variant="outline" className="shrink-0">
                    <Upload className="w-4 h-4" /> 파일 선택
                  </Button>
                </div>
                <p className="text-xs text-gray-500 mt-1">* 철곡품 전개도 이미지를 업로드하세요 (JPG, PNG, PDF 등)</p>
              </div>
            ) : (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">드로잉</label>
                <p className="text-xs text-gray-500 mb-2">* '전개도 그리기' 버튼을 클릭하여 캔버스에 직접 그릴 수 있습니다</p>
                <Button variant="outline" onClick={() => setShowDrawingEditor(true)}>
                  <Edit3 className="w-4 h-4" /> 전개도 그리기
                </Button>
              </div>
            )}

            {/* 미리보기 영역 */}
            <div className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-medium text-gray-700">미리보기</span>
                {formData.drawingFile && (
                  <button className="text-sm text-red-500 hover:text-red-700 flex items-center gap-1">
                    <X className="w-4 h-4" /> 전개도 삭제
                  </button>
                )}
              </div>
              <div className="min-h-[200px] bg-gray-50 rounded-lg flex items-center justify-center text-gray-400">
                {formData.drawingFile ? (
                  <div className="text-center">
                    <img src="/api/placeholder/300/200" alt="전개도 미리보기" className="max-w-full h-auto" />
                  </div>
                ) : (
                  <span>전개도 이미지가 없습니다</span>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 조립 부품일 때 BOM 섹션 */}
      {isAssemblyPart && formData.needsBom && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4 pb-2 border-b">
            <h3 className="text-lg font-semibold">부품 구성 (BOM)</h3>
            <Button variant="outline" onClick={addBomItem}>
              <Plus className="w-4 h-4" /> BOM 품목 추가
            </Button>
          </div>

          {bomItems.length === 0 ? (
            <div className="text-center py-8 text-gray-500 border border-dashed border-gray-300 rounded-lg">
              BOM 품목을 추가해주세요
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-3 py-2 text-left font-medium text-gray-600">품목코드 / 품목명 입력</th>
                    <th className="px-3 py-2 text-left font-medium text-gray-600">품목명</th>
                    <th className="px-3 py-2 text-left font-medium text-gray-600">규격</th>
                    <th className="px-3 py-2 text-left font-medium text-gray-600">재질</th>
                    <th className="px-3 py-2 text-left font-medium text-gray-600">수량</th>
                    <th className="px-3 py-2 text-left font-medium text-gray-600">단위</th>
                    <th className="px-3 py-2 text-left font-medium text-gray-600">단가</th>
                    <th className="px-3 py-2 text-left font-medium text-gray-600">비고</th>
                    <th className="px-3 py-2 text-center font-medium text-gray-600">삭제</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {bomItems.map(bomItem => (
                    <tr key={bomItem.id}>
                      <td className="px-3 py-2">
                        <div className="flex items-center gap-1">
                          <input
                            type="text"
                            value={bomItem.itemCode}
                            onChange={(e) => updateBomItem(bomItem.id, 'itemCode', e.target.value)}
                            className="flex-1 px-2 py-1 border border-gray-300 rounded text-sm"
                            placeholder="CTL-001"
                          />
                          <Check className="w-4 h-4 text-green-500" />
                          <Search className="w-4 h-4 text-gray-400 cursor-pointer hover:text-gray-600" />
                        </div>
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="text"
                          value={bomItem.itemName}
                          onChange={(e) => updateBomItem(bomItem.id, 'itemName', e.target.value)}
                          className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                          placeholder="제어기 기본형"
                        />
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="text"
                          value={bomItem.spec}
                          onChange={(e) => updateBomItem(bomItem.id, 'spec', e.target.value)}
                          className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                          placeholder="기본형"
                        />
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="text"
                          value={bomItem.material}
                          onChange={(e) => updateBomItem(bomItem.id, 'material', e.target.value)}
                          className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                          placeholder="재질"
                        />
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="number"
                          value={bomItem.quantity}
                          onChange={(e) => updateBomItem(bomItem.id, 'quantity', parseInt(e.target.value) || 0)}
                          className="w-16 px-2 py-1 border border-gray-300 rounded text-sm text-center"
                          min="1"
                        />
                      </td>
                      <td className="px-3 py-2">
                        <span className="text-sm">EA</span>
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="number"
                          value={bomItem.price}
                          onChange={(e) => updateBomItem(bomItem.id, 'price', parseInt(e.target.value) || 0)}
                          className="w-24 px-2 py-1 border border-gray-300 rounded text-sm text-right"
                          min="0"
                        />
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="text"
                          value={bomItem.description}
                          onChange={(e) => updateBomItem(bomItem.id, 'description', e.target.value)}
                          className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                          placeholder="비고"
                        />
                      </td>
                      <td className="px-3 py-2 text-center">
                        <button
                          onClick={() => removeBomItem(bomItem.id)}
                          className="p-1 text-red-500 hover:bg-red-50 rounded"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {/* 제품일 때 인정 정보 섹션 */}
      {isProductType && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-semibold mb-4 pb-2 border-b">인정 정보</h3>
          <div className="grid grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">인정번호</label>
              <input
                type="text"
                value={formData.certNumber}
                onChange={(e) => setFormData({ ...formData, certNumber: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                placeholder="인정번호를 입력하세요"
              />
            </div>
            <div></div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">인정유효기간 시작일</label>
              <input
                type="date"
                value={formData.certStartDate}
                onChange={(e) => setFormData({ ...formData, certStartDate: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">인정유효기간 종료일</label>
              <input
                type="date"
                value={formData.certEndDate}
                onChange={(e) => setFormData({ ...formData, certEndDate: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">시방서 (PDF)</label>
              <div className="flex items-center gap-2">
                <input
                  type="text"
                  className="flex-1 px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
                  placeholder="파일을 선택하세요"
                  disabled
                />
                <Button variant="outline" className="shrink-0">
                  <Upload className="w-4 h-4" /> 업로드
                </Button>
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">인정서 (PDF)</label>
              <div className="flex items-center gap-2">
                <input
                  type="text"
                  className="flex-1 px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
                  placeholder="파일을 선택하세요"
                  disabled
                />
                <Button variant="outline" className="shrink-0">
                  <Upload className="w-4 h-4" /> 업로드
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 제품일 때 BOM 섹션 */}
      {isProductType && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4 pb-2 border-b">
            <h3 className="text-lg font-semibold">부품 구성 (BOM)</h3>
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={formData.needsBom}
                onChange={(e) => setFormData({ ...formData, needsBom: e.target.checked })}
                className="w-4 h-4 text-blue-600 rounded"
              />
              <span className="text-sm font-medium">부품구성(BOM) 필요</span>
            </label>
          </div>

          {formData.needsBom ? (
            <div className="space-y-4">
              <div className="flex justify-end">
                <Button variant="outline" onClick={addBomItem}>
                  <Plus className="w-4 h-4" /> 부품 추가
                </Button>
              </div>

              {bomItems.length === 0 ? (
                <div className="text-center py-8 text-gray-500 border border-dashed border-gray-300 rounded-lg">
                  부품을 추가해주세요
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-3 py-2 text-left font-medium text-gray-600">품목코드/품목명 입력</th>
                        <th className="px-3 py-2 text-left font-medium text-gray-600">품목명</th>
                        <th className="px-3 py-2 text-left font-medium text-gray-600">규격</th>
                        <th className="px-3 py-2 text-left font-medium text-gray-600">재질</th>
                        <th className="px-3 py-2 text-left font-medium text-gray-600">수량</th>
                        <th className="px-3 py-2 text-left font-medium text-gray-600">단위</th>
                        <th className="px-3 py-2 text-left font-medium text-gray-600">단가</th>
                        <th className="px-3 py-2 text-left font-medium text-gray-600">비고</th>
                        <th className="px-3 py-2 text-center font-medium text-gray-600">삭제</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                      {bomItems.map(bomItem => (
                        <tr key={bomItem.id}>
                          <td className="px-3 py-2">
                            <input
                              type="text"
                              value={bomItem.itemCode}
                              onChange={(e) => updateBomItem(bomItem.id, 'itemCode', e.target.value)}
                              className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                              placeholder="품목코드"
                            />
                          </td>
                          <td className="px-3 py-2">
                            <input
                              type="text"
                              value={bomItem.itemName}
                              onChange={(e) => updateBomItem(bomItem.id, 'itemName', e.target.value)}
                              className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                              placeholder="품목명"
                            />
                          </td>
                          <td className="px-3 py-2">
                            <input
                              type="text"
                              value={bomItem.spec}
                              onChange={(e) => updateBomItem(bomItem.id, 'spec', e.target.value)}
                              className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                              placeholder="규격"
                            />
                          </td>
                          <td className="px-3 py-2">
                            <input
                              type="text"
                              value={bomItem.material}
                              onChange={(e) => updateBomItem(bomItem.id, 'material', e.target.value)}
                              className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                              placeholder="재질"
                            />
                          </td>
                          <td className="px-3 py-2">
                            <input
                              type="number"
                              value={bomItem.quantity}
                              onChange={(e) => updateBomItem(bomItem.id, 'quantity', parseInt(e.target.value) || 0)}
                              className="w-20 px-2 py-1 border border-gray-300 rounded text-sm"
                              min="1"
                            />
                          </td>
                          <td className="px-3 py-2">
                            <select
                              value={bomItem.unit}
                              onChange={(e) => updateBomItem(bomItem.id, 'unit', e.target.value)}
                              className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                            >
                              {units.map(u => (
                                <option key={u} value={u}>{u}</option>
                              ))}
                            </select>
                          </td>
                          <td className="px-3 py-2">
                            <input
                              type="number"
                              value={bomItem.price}
                              onChange={(e) => updateBomItem(bomItem.id, 'price', parseInt(e.target.value) || 0)}
                              className="w-24 px-2 py-1 border border-gray-300 rounded text-sm"
                              min="0"
                            />
                          </td>
                          <td className="px-3 py-2">
                            <input
                              type="text"
                              value={bomItem.description}
                              onChange={(e) => updateBomItem(bomItem.id, 'description', e.target.value)}
                              className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                              placeholder="비고"
                            />
                          </td>
                          <td className="px-3 py-2 text-center">
                            <button
                              onClick={() => removeBomItem(bomItem.id)}
                              className="p-1 text-red-500 hover:bg-red-50 rounded"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              BOM 정보가 필요하면 위의 체크박스를 선택해주세요
            </div>
          )}
        </div>
      )}

      {/* 이미지 편집기 모달 */}
      {showDrawingEditor && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-2xl w-full mx-4">
            <div className="flex items-center justify-between mb-4">
              <div>
                <h3 className="text-lg font-bold">이미지 편집기</h3>
                <p className="text-sm text-gray-500">품목 이미지를 그리거나 편집합니다.</p>
              </div>
              <button onClick={() => setShowDrawingEditor(false)} className="p-1 hover:bg-gray-100 rounded">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="border border-gray-200 rounded-lg p-4 mb-4">
              <div className="flex items-center gap-2 mb-4">
                <button className="p-2 bg-blue-100 text-blue-600 rounded"><Edit3 className="w-4 h-4" /></button>
                <button className="p-2 hover:bg-gray-100 rounded">─</button>
                <button className="p-2 hover:bg-gray-100 rounded">□</button>
                <button className="p-2 hover:bg-gray-100 rounded">○</button>
                <button className="p-2 hover:bg-gray-100 rounded">T</button>
                <button className="p-2 hover:bg-gray-100 rounded"><Eraser className="w-4 h-4" /></button>
                <button className="p-2 hover:bg-gray-100 rounded">↩</button>
                <button className="p-2 hover:bg-gray-100 rounded"><Trash2 className="w-4 h-4" /></button>
              </div>
              <div className="flex items-center gap-2 mb-4">
                {['#000000', '#FF0000', '#0000FF', '#00FF00', '#FF00FF', '#FFFF00', '#00FFFF', '#FFA500', '#800080', '#FFC0CB'].map(color => (
                  <button key={color} className="w-6 h-6 rounded" style={{ backgroundColor: color }}></button>
                ))}
              </div>
              <div className="flex items-center gap-2 mb-4">
                <span className="text-sm">선 두께: 2px</span>
                <div className="w-12 h-6 bg-gray-200 rounded-full relative">
                  <div className="absolute right-1 top-1 w-4 h-4 bg-blue-500 rounded-full"></div>
                </div>
              </div>
              <div className="h-64 bg-white border border-gray-300 rounded"></div>
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setShowDrawingEditor(false)}>취소</Button>
              <Button variant="primary" onClick={() => setShowDrawingEditor(false)}>
                <Save className="w-4 h-4" /> 저장
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 품목 상세 컴포넌트
const ItemDetail = ({ item, onNavigate }) => {
  if (!item) {
    return (
      <div className="p-8 text-center text-gray-500">
        품목 정보를 찾을 수 없습니다.
        <Button variant="outline" className="mt-4" onClick={() => onNavigate('item-list')}>
          목록으로
        </Button>
      </div>
    );
  }

  // 현재 날짜를 ISO 형식으로
  const currentDate = new Date().toISOString();

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Package}
        title="품목 상세"
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => onNavigate('item-list')}>
              <List className="w-4 h-4" /> 목록
            </Button>
            <Button variant="primary" onClick={() => onNavigate('item-edit', item)}>
              <Edit className="w-4 h-4" /> 수정
            </Button>
          </div>
        }
      />

      {/* 기본 정보 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <h3 className="font-semibold mb-4">기본 정보</h3>
        <div className="grid grid-cols-3 gap-6">
          <div>
            <p className="text-sm text-gray-500 mb-1">품목코드</p>
            <p className="px-3 py-2 bg-gray-100 rounded-lg font-mono text-sm">{item.itemCode}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">품목명</p>
            <p className="font-medium">{item.itemName}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">품목유형</p>
            <span className={`px-2 py-1 rounded text-xs font-medium ${item.itemType === '제품' ? 'bg-blue-100 text-blue-700' :
                item.itemType === '부품' ? 'bg-purple-100 text-purple-700' :
                  item.itemType === '부자재' ? 'bg-orange-100 text-orange-700' :
                    item.itemType === '원자재' ? 'bg-green-100 text-green-700' :
                      'bg-gray-100 text-gray-700'
              }`}>
              {item.itemType}
            </span>
          </div>
        </div>

        <div className="mt-4">
          <p className="text-sm text-gray-500 mb-1">비고</p>
          <p className="text-gray-600">{item.description || item.itemName}</p>
        </div>

        <div className="grid grid-cols-2 gap-6 mt-4">
          <div>
            <p className="text-sm text-gray-500 mb-1">현재 버전</p>
            <p className="font-medium">V0</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">수정 횟수</p>
            <p className="font-medium">0회</p>
          </div>
        </div>

        <div className="mt-4">
          <p className="text-sm text-gray-500 mb-1">등록일</p>
          <p className="text-gray-600">{item.createdAt || currentDate}</p>
        </div>
      </div>

      {/* 부품 구성 (BOM) */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200">
        <div className="p-4 border-b border-gray-200 flex items-center gap-2">
          <Package className="w-5 h-5 text-gray-400" />
          <h3 className="font-semibold">부품 구성 (BOM)</h3>
        </div>
        <div className="p-8">
          <div className="flex flex-col items-center justify-center text-center py-8">
            <div className="w-16 h-16 bg-gray-100 rounded-xl flex items-center justify-center mb-4">
              <Package className="w-8 h-8 text-gray-300" />
            </div>
            <p className="text-gray-500 mb-1">등록된 BOM 품목이 없습니다</p>
            <p className="text-sm text-gray-400">품목 수정에서 BOM을 추가할 수 있습니다</p>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// 기존 품목기준관리 컴포넌트 (호환성 유지)
// ============================================================
const ItemMasterManagement = ({ onNavigate }) => {
  return <MasterConfigurationManager configId="item" onNavigate={onNavigate} />;
};

// ============================================================
// 자재기준관리 컴포넌트
// ============================================================
const MaterialMasterManagement = ({ onNavigate }) => {
  return <MasterConfigurationManager configId="material" onNavigate={onNavigate} />;
};

// 초기 데이터 - 품목유형 (레거시 호환)
const initialItemTypes = [
  { id: 1, code: 'FG', name: '제품', description: '완제품', sortOrder: 1, isActive: true },
  { id: 2, code: 'PT', name: '부품', description: '부품/파트', sortOrder: 2, isActive: true },
  { id: 3, code: 'WIP', name: '반제품', description: '반제품/공정품', sortOrder: 3, isActive: true },
  { id: 4, code: 'RM', name: '원자재', description: '원자재', sortOrder: 4, isActive: true },
];

// 초기 데이터 - 품목분류 (계층구조)
const initialItemCategories = [
  { id: 1, code: 'SCR', name: '스크린', parentId: null, level: 1, path: '/1', sortOrder: 1 },
  { id: 2, code: 'SCR-STD', name: '표준형', parentId: 1, level: 2, path: '/1/2', sortOrder: 1 },
  { id: 3, code: 'SCR-PRM', name: '프리미엄', parentId: 1, level: 2, path: '/1/3', sortOrder: 2 },
  { id: 4, code: 'SLT', name: '슬랫', parentId: null, level: 1, path: '/4', sortOrder: 2 },
  { id: 5, code: 'SLT-STD', name: '표준형', parentId: 4, level: 2, path: '/4/5', sortOrder: 1 },
  { id: 6, code: 'BND', name: '절곡', parentId: null, level: 1, path: '/6', sortOrder: 3 },
  { id: 7, code: 'MTR', name: '모터', parentId: null, level: 1, path: '/7', sortOrder: 4 },
  { id: 8, code: 'MTR-TUB', name: '튜블러모터', parentId: 7, level: 2, path: '/7/8', sortOrder: 1 },
  { id: 9, code: 'MTR-GRD', name: '기어드모터', parentId: 7, level: 2, path: '/7/9', sortOrder: 2 },
];

// 초기 데이터 - 마스터 필드
const initialMasterFields = [
  { id: 1, fieldKey: 'itemCode', fieldName: '품목코드', inputType: 'text', isRequired: true, validations: { maxLength: 20, pattern: '^[A-Z0-9-]+$' }, description: '품목 식별 코드' },
  { id: 2, fieldKey: 'itemName', fieldName: '품목명', inputType: 'text', isRequired: true, validations: { maxLength: 100 }, description: '품목 이름' },
  { id: 3, fieldKey: 'category', fieldName: '분류', inputType: 'select', isRequired: false, options: { source: 'api', apiUrl: '/api/item-categories' }, description: '품목 분류' },
  { id: 4, fieldKey: 'itemType', fieldName: '품목유형', inputType: 'select', isRequired: true, options: { items: ['제품', '부품', '반제품', '원자재'] }, description: '제품/부품/반제품/원자재' },
  { id: 5, fieldKey: 'unit', fieldName: '단위', inputType: 'select', isRequired: true, options: { items: ['EA', 'SET', 'M', 'KG', 'TON'] }, description: '수량 단위' },
  { id: 6, fieldKey: 'spec', fieldName: '규격', inputType: 'text', isRequired: false, description: '제품 규격' },
  { id: 7, fieldKey: 'bomRequired', fieldName: 'BOM 필요', inputType: 'checkbox', isRequired: false, description: 'BOM 구성 필요 여부' },
  { id: 8, fieldKey: 'inspectionRequired', fieldName: '검사 필요', inputType: 'checkbox', isRequired: false, description: '입고/출고 검사 필요 여부' },
  { id: 9, fieldKey: 'leadTime', fieldName: '리드타임', inputType: 'number', isRequired: false, validations: { min: 0 }, description: '조달/생산 소요일' },
  { id: 10, fieldKey: 'safetyStock', fieldName: '안전재고', inputType: 'number', isRequired: false, validations: { min: 0 }, description: '안전재고 수량' },
  { id: 11, fieldKey: 'description', fieldName: '설명', inputType: 'textarea', isRequired: false, description: '품목 상세 설명' },
  { id: 12, fieldKey: 'price', fieldName: '단가', inputType: 'number', isRequired: false, validations: { min: 0 }, description: '기준 단가' },
];

// 초기 데이터 - 마스터 섹션
const initialMasterSections = [
  { id: 1, sectionKey: 'basicInfo', sectionName: '기본정보', sectionType: 'general', applicableTypes: ['FG', 'PT', 'WIP', 'RM'], description: '품목 기본 정보', fields: [1, 2, 3, 4, 5, 6] },
  { id: 2, sectionKey: 'bom', sectionName: 'BOM', sectionType: 'module', applicableTypes: ['FG', 'WIP'], description: 'BOM 구성 정보', fields: [7] },
  { id: 3, sectionKey: 'inventory', sectionName: '재고정보', sectionType: 'general', applicableTypes: ['FG', 'PT', 'RM'], description: '재고 관련 정보', fields: [9, 10] },
  { id: 4, sectionKey: 'quality', sectionName: '품질정보', sectionType: 'module', applicableTypes: ['FG', 'PT', 'RM'], description: '품질 검사 정보', fields: [8] },
  { id: 5, sectionKey: 'pricing', sectionName: '단가정보', sectionType: 'general', applicableTypes: ['FG', 'PT', 'RM'], description: '단가 정보', fields: [12] },
];

// 초기 데이터 - 페이지 템플릿
const initialPageTemplates = [
  {
    id: 1,
    pageCode: 'item_registration',
    pageName: '품목 등록',
    pagePath: '/제품관리/품목_등록',
    itemTypes: ['FG'],
    sections: [
      {
        sectionId: 1, sectionKey: 'basicInfo', sectionName: '기본정보', sortOrder: 1, fields: [
          { fieldId: 1, fieldKey: 'itemCode', fieldName: '품목코드', inputType: 'text', isRequired: true },
          { fieldId: 2, fieldKey: 'itemName', fieldName: '품목명', inputType: 'text', isRequired: true },
          { fieldId: 3, fieldKey: 'category', fieldName: '분류', inputType: 'select', isRequired: false },
        ]
      },
      {
        sectionId: 2, sectionKey: 'bom', sectionName: 'BOM', sortOrder: 2, fields: [
          { fieldId: 7, fieldKey: 'bomRequired', fieldName: 'BOM 필요', inputType: 'checkbox', isRequired: false },
        ]
      },
    ],
    conditions: [
      { id: 1, sourceFieldKey: 'category', conditionType: 'equals', conditionValue: 'FG', displayType: 'show_section', targetSectionKey: 'bom' }
    ]
  }
];

// ============================================================
// 코드기준 관리 컴포넌트
// ============================================================
const CodeRuleManagement = ({ onNavigate }) => {
  const [showHelp, setShowHelp] = useState(false);

  // 코드기준 목록 (LOT 관련은 채번관리에서 관리)
  const [codeRules, setCodeRules] = useState([
    // === 기본 코드 ===
    { id: 1, name: '품목코드 기준', target: '품목코드', codeType: 'composite', prefix: '', useDate: false, dateFormat: '', useProcess: false, seqDigits: 3, separator: '-', components: ['itemType', 'category', 'seq'], example: 'BP-GR-001', status: '활성', description: '품목유형 + 카테고리 + 일련번호', category: '기본코드' },
    { id: 2, name: '거래처코드 기준', target: '거래처코드', codeType: 'simple', prefix: 'C', useDate: false, dateFormat: '', useProcess: false, seqDigits: 3, separator: '-', components: ['prefix', 'seq'], example: 'C-001', status: '활성', description: '거래처 식별코드', category: '기본코드' },
    { id: 3, name: '현장코드 기준', target: '현장코드', codeType: 'simple', prefix: 'S', useDate: false, dateFormat: '', useProcess: false, seqDigits: 3, separator: '-', components: ['prefix', 'seq'], example: 'S-001', status: '활성', description: '현장 식별코드', category: '기본코드' },
    // === 부자재 코드 ===
    { id: 4, name: '스크린원단', target: '부자재', codeType: 'mapping', prefix: 'SCR', example: 'SCR-0.3T', status: '활성', description: '패턴: {코드}-{규격}', category: '부자재' },
    { id: 5, name: '엔드바', target: '부자재', codeType: 'mapping', prefix: 'END', example: 'END-0.5T', status: '활성', description: '패턴: {코드}-{규격}', category: '부자재' },
    { id: 6, name: '하부바', target: '부자재', codeType: 'mapping', prefix: 'BTM', example: 'BTM-1.2T', status: '활성', description: '패턴: {코드}-{규격}', category: '부자재' },
    { id: 7, name: '사이드가이드', target: '부자재', codeType: 'mapping', prefix: 'SDG', example: 'SDG-1.6T', status: '활성', description: '패턴: {코드}-{규격}', category: '부자재' },
    { id: 8, name: '브라켓', target: '부자재', codeType: 'mapping', prefix: 'BKT', example: 'BKT-2.3T', status: '활성', description: '패턴: {코드}-{규격}', category: '부자재' },
    // === 원자재 코드 ===
    { id: 9, name: 'EGI코일', target: '원자재', codeType: 'mapping', prefix: 'EGI', example: 'EGI-0.5T', status: '활성', description: '패턴: {코드}-{규격}', category: '원자재' },
    { id: 10, name: 'SUS코일', target: '원자재', codeType: 'mapping', prefix: 'SUS', example: 'SUS-0.6T', status: '활성', description: '패턴: {코드}-{규격}', category: '원자재' },
    { id: 11, name: '슬랫원단', target: '원자재', codeType: 'mapping', prefix: 'SLT', example: 'SLT-1.2T', status: '활성', description: '패턴: {코드}-{규격}', category: '원자재' },
    { id: 12, name: '경첩', target: '원자재', codeType: 'mapping', prefix: 'HNG', example: 'HNG-STD', status: '활성', description: '패턴: {코드}-{규격}', category: '원자재' },
    // === 구매부품 코드 ===
    { id: 13, name: '전기개폐기', target: '구매부품', codeType: 'mapping', prefix: 'E', example: 'E-220V-300KG', status: '활성', description: '패턴: {코드}-{전원}-{용량}', category: '구매부품' },
    { id: 14, name: '수동개폐기', target: '구매부품', codeType: 'mapping', prefix: 'M', example: 'M-MANUAL', status: '활성', description: '패턴: {코드}-{타입}', category: '구매부품' },
    { id: 15, name: '제어반', target: '구매부품', codeType: 'mapping', prefix: 'CTL', example: 'CTL-220V', status: '활성', description: '패턴: {코드}-{전원}', category: '구매부품' },
    // === 절곡부품 품목코드 ===
    { id: 16, name: '가이드레일(벽면형)', target: '절곡부품', codeType: 'mapping', prefix: 'R', example: 'RC24', status: '활성', description: '{제품코드}{종류코드}{길이코드}', category: '절곡부품' },
    { id: 17, name: '가이드레일(측면형)', target: '절곡부품', codeType: 'mapping', prefix: 'S', example: 'SC30', status: '활성', description: '{제품코드}{종류코드}{길이코드}', category: '절곡부품' },
    { id: 18, name: '케이스', target: '절곡부품', codeType: 'mapping', prefix: 'C', example: 'CM24', status: '활성', description: '{제품코드}{종류코드}{길이코드}', category: '절곡부품' },
    { id: 19, name: '하단마감재(스크린)', target: '절곡부품', codeType: 'mapping', prefix: 'B', example: 'BM30', status: '활성', description: '{제품코드}{종류코드}{길이코드}', category: '절곡부품' },
    { id: 20, name: 'L-Bar', target: '절곡부품', codeType: 'mapping', prefix: 'L', example: 'LM24', status: '활성', description: '{제품코드}{종류코드}{길이코드}', category: '절곡부품' },
    { id: 21, name: '연기차단재', target: '절곡부품', codeType: 'mapping', prefix: 'G', example: 'G-I-4A05-53', status: '활성', description: '{제품}-{종류}-{날짜}-{규격}', category: '절곡부품' },
    { id: 22, name: '하단마감재(철재)', target: '절곡부품', codeType: 'mapping', prefix: 'T', example: 'TM24', status: '활성', description: '{제품코드}{종류코드}{길이코드}', category: '절곡부품' },
    // === 셔터종류 코드 ===
    { id: 29, name: '실리카', target: '셔터종류', codeType: 'mapping', prefix: 'SI', example: 'SI', status: '활성', description: '셔터종류 코드', category: '셔터종류' },
    { id: 30, name: '와이어', target: '셔터종류', codeType: 'mapping', prefix: 'WS', example: 'WS', status: '활성', description: '셔터종류 코드', category: '셔터종류' },
    { id: 31, name: '화이바', target: '셔터종류', codeType: 'mapping', prefix: 'FS', example: 'FS', status: '활성', description: '셔터종류 코드', category: '셔터종류' },
    { id: 32, name: '철재(조적용)', target: '셔터종류', codeType: 'mapping', prefix: 'IJ', example: 'IJ', status: '활성', description: '인정제품 조적용', category: '셔터종류' },
    // === 인정제품 코드 ===
    { id: 33, name: '실리카(EGI)', target: '인정제품', codeType: 'mapping', prefix: 'SE', example: 'KD-SE-251217-01', status: '활성', description: 'KSE01', category: '인정제품' },
    { id: 34, name: '실리카(SUS)', target: '인정제품', codeType: 'mapping', prefix: 'SS', example: 'KD-SS-251217-01', status: '활성', description: 'KSS01', category: '인정제품' },
    { id: 35, name: '와이어(EGI)', target: '인정제품', codeType: 'mapping', prefix: 'WE', example: 'KD-WE-251217-01', status: '활성', description: 'KWE01', category: '인정제품' },
    { id: 36, name: '철재(EGI)', target: '인정제품', codeType: 'mapping', prefix: 'TE', example: 'KD-TE-251217-01', status: '활성', description: 'KTE01', category: '인정제품' },
    { id: 37, name: '철재(SUS)', target: '인정제품', codeType: 'mapping', prefix: 'TS', example: 'KD-TS-251217-01', status: '활성', description: 'KQTS01', category: '인정제품' },
    // === 신규 인정제품 코드 ===
    { id: 38, name: '실리카(신규)', target: '신규인정', codeType: 'mapping', prefix: 'SA', example: 'KD-SA-251217-01', status: '활성', description: 'KSS02 (시험체 적용)', category: '신규인정' },
    { id: 39, name: '와이어(신규)', target: '신규인정', codeType: 'mapping', prefix: 'WW', example: 'KD-WW-251217-01', status: '활성', description: 'KWWS02 (시험체 적용)', category: '신규인정' },
    { id: 40, name: '조적와이어', target: '신규인정', codeType: 'mapping', prefix: 'JW', example: 'KD-JW-251217-01', status: '활성', description: 'KJWS01 (시험체 적용)', category: '신규인정' },
    { id: 41, name: 'DS셔터', target: '신규인정', codeType: 'mapping', prefix: 'DS', example: 'KD-DS-251217-01', status: '활성', description: 'KDSS01 (시험체 적용)', category: '신규인정' },
  ]);

  const [showModal, setShowModal] = useState(false);
  const [editingRule, setEditingRule] = useState(null);
  const [selectedCategory, setSelectedCategory] = useState('전체');

  // 카테고리 목록 추출
  const categories = ['전체', ...new Set(codeRules.map(r => r.category).filter(Boolean))];

  // 필터링된 코드 규칙
  const filteredCodeRules = selectedCategory === '전체'
    ? codeRules
    : codeRules.filter(r => r.category === selectedCategory);

  const [formData, setFormData] = useState({
    name: '',
    target: '',
    codeType: 'simple',
    prefix: '',
    useDate: false,
    dateFormat: 'YYMMDD',
    useProcess: false,
    seqDigits: 3,
    separator: '-',
    status: '활성',
    description: '',
  });

  // 적용대상 및 템플릿 (LOT 관련은 채번관리에서 관리)
  const targetTemplates = [
    { value: '품목코드', label: '품목코드', codeType: 'composite', prefix: '', useDate: false, useProcess: false, seqDigits: 3 },
    { value: '거래처코드', label: '거래처코드', codeType: 'simple', prefix: 'C', useDate: false, useProcess: false, seqDigits: 3 },
    { value: '현장코드', label: '현장코드', codeType: 'simple', prefix: 'S', useDate: false, useProcess: false, seqDigits: 3 },
  ];

  // 코드 유형 (LOT형은 채번관리에서 관리)
  const codeTypes = [
    { value: 'simple', label: '단순형', desc: '접두사 + 순번', example: 'C-001' },
    { value: 'composite', label: '조합형', desc: '품목유형 + 카테고리 + 순번', example: 'BP-GR-001' },
  ];

  // 날짜 형식
  const dateFormats = [
    { value: 'YYMMDD', label: 'YYMMDD (251205)', example: '251205' },
    { value: 'YYYYMMDD', label: 'YYYYMMDD (20251205)', example: '20251205' },
    { value: 'YYMM', label: 'YYMM (2512)', example: '2512' },
  ];

  // 순번 자릿수
  const seqDigitOptions = [
    { value: 2, label: '2자리 (01~99)' },
    { value: 3, label: '3자리 (001~999)' },
    { value: 4, label: '4자리 (0001~9999)' },
  ];

  // 구분자
  const separatorOptions = [
    { value: '-', label: '하이픈 (-)' },
    { value: '_', label: '언더스코어 (_)' },
    { value: '', label: '없음' },
  ];

  // 코드 미리보기 생성 (LOT형은 채번관리에서 관리)
  const generatePreview = (data) => {
    const sep = data.separator;
    const seq = '1'.padStart(data.seqDigits, '0');

    // 코드 유형별 생성
    switch (data.codeType) {
      case 'simple':
        return `${data.prefix}${sep}${seq}`;
      case 'composite':
        return `BP${sep}GR${sep}${seq}`;
      default:
        return `${data.prefix}${sep}${seq}`;
    }
  };

  // 구조 설명 생성 (LOT형은 채번관리에서 관리)
  const getStructureDescription = (data) => {
    const parts = [];
    switch (data.codeType) {
      case 'simple':
        parts.push('접두사');
        parts.push('순번');
        break;
      case 'composite':
        parts.push('품목유형코드');
        parts.push('카테고리코드');
        parts.push('일련번호');
        break;
    }
    return parts.join(' + ');
  };

  // 적용대상 선택 시 템플릿 적용
  const handleTargetChange = (target) => {
    const template = targetTemplates.find(t => t.value === target);
    if (template) {
      setFormData(prev => ({
        ...prev,
        target,
        name: `${target} 기준`,
        codeType: template.codeType,
        prefix: template.prefix,
        useDate: template.useDate,
        useProcess: template.useProcess,
        seqDigits: template.seqDigits,
      }));
    }
  };

  // 신규 등록 모달
  const openCreateModal = () => {
    setEditingRule(null);
    setFormData({
      name: '',
      target: '',
      codeType: 'simple',
      prefix: '',
      useDate: false,
      dateFormat: 'YYMMDD',
      useProcess: false,
      seqDigits: 3,
      separator: '-',
      status: '활성',
      description: '',
    });
    setShowModal(true);
  };

  // 수정 모달
  const openEditModal = (rule) => {
    setEditingRule(rule);
    setFormData({
      name: rule.name,
      target: rule.target,
      codeType: rule.codeType,
      prefix: rule.prefix,
      useDate: rule.useDate,
      dateFormat: rule.dateFormat || 'YYMMDD',
      useProcess: rule.useProcess,
      seqDigits: rule.seqDigits,
      separator: rule.separator,
      status: rule.status,
      description: rule.description || '',
    });
    setShowModal(true);
  };

  // 저장
  const handleSave = () => {
    const example = generatePreview(formData);
    const structure = getStructureDescription(formData);
    if (editingRule) {
      setCodeRules(prev => prev.map(r =>
        r.id === editingRule.id ? { ...r, ...formData, example, description: structure } : r
      ));
    } else {
      setCodeRules(prev => [...prev, {
        id: Math.max(...prev.map(r => r.id)) + 1,
        ...formData,
        example,
        description: structure,
      }]);
    }
    setShowModal(false);
  };

  // 삭제
  const handleDelete = (id) => {
    if (confirm('이 코드기준을 삭제하시겠습니까?')) {
      setCodeRules(prev => prev.filter(r => r.id !== id));
    }
  };

  // 상태 토글
  const toggleStatus = (id) => {
    setCodeRules(prev => prev.map(r =>
      r.id === id ? { ...r, status: r.status === '활성' ? '비활성' : '활성' } : r
    ));
  };

  return (
    <div className="space-y-4">
      {/* 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <Layers className="w-6 h-6 text-blue-500" />
          공통코드 목록
        </h1>
        <div className="flex items-center justify-end gap-2">
          <button
            onClick={() => setShowHelp(true)}
            className="w-8 h-8 rounded-full bg-gray-100 text-gray-600 hover:bg-gray-200 flex items-center justify-center text-sm font-bold"
            title="코드기준 vs 번호기준 차이점"
          >
            ?
          </button>
          <button
            onClick={openCreateModal}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
          >
            <Plus className="w-4 h-4" /> 등록
          </button>
        </div>
      </div>

      {/* 도움말 모달 */}
      {showHelp && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl max-w-lg w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b flex justify-between items-center sticky top-0 bg-white z-10">
              <h3 className="font-bold text-lg">코드기준 vs 번호기준 차이점</h3>
              <button onClick={() => setShowHelp(false)} className="text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
                  <h4 className="font-medium text-orange-900 mb-2">코드기준 (실물용)
                  </h4>
                  <p className="text-sm text-orange-700 mb-2">
                    <strong>실물/마스터</strong>에 부여하는 식별코드
                  </p>
                  <ul className="text-sm text-orange-600 space-y-1">
                    <li>• 품목코드 (RC30, CB24 등)</li>
                    <li>• 입고LOT, 생산LOT</li>
                    <li>• 거래처코드, 현장코드</li>
                  </ul>
                </div>
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <h4 className="font-medium text-blue-900 mb-2">번호기준 (문서용)
                  </h4>
                  <p className="text-sm text-blue-700 mb-2">
                    <strong>문서</strong>에 부여하는 일련번호
                  </p>
                  <ul className="text-sm text-blue-600 space-y-1">
                    <li>• 견적번호, 수주번호</li>
                    <li>• 생산지시번호, 출하번호</li>
                    <li>• 발주번호</li>
                  </ul>
                </div>
              </div>
              <div className="bg-gray-50 rounded-lg p-3 text-sm text-gray-600">
                <strong>요약:</strong> 코드기준은 품목/거래처 등 <u>마스터 데이터</u>를 식별하고,
                번호기준은 견적서/수주서 등 <u>업무 문서</u>를 식별합니다.
              </div>
            </div>
            <div className="p-4 border-t bg-gray-50 rounded-b-xl">
              <button
                onClick={() => setShowHelp(false)}
                className="w-full py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600"
              >
                확인
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 카테고리 필터 */}
      <div className="flex flex-wrap gap-2 mb-4">
        {categories.map(cat => (
          <button
            key={cat}
            onClick={() => setSelectedCategory(cat)}
            className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${selectedCategory === cat
                ? 'bg-orange-500 text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
          >
            {cat}
            {cat !== '전체' && (
              <span className="ml-1.5 px-1.5 py-0.5 rounded-full text-xs bg-white/20">
                {codeRules.filter(r => r.category === cat).length}
              </span>
            )}
          </button>
        ))}
      </div>

      {/* 코드기준 목록 */}
      <div className="bg-white rounded-lg shadow-sm border overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">번호</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">코드기준 이름</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">적용 대상</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">접두사</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">설명</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">예시</th>
              <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
              <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {filteredCodeRules.map((rule, idx) => (
              <tr key={rule.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 text-sm text-gray-500">{filteredCodeRules.length - idx}</td>
                <td className="px-4 py-3 text-sm font-medium text-gray-900">{rule.name}</td>
                <td className="px-4 py-3 text-sm text-gray-600">
                  {rule.target}
                </td>
                <td className="px-4 py-3 text-sm">
                  <span className="px-2 py-0.5 rounded text-xs font-mono font-bold bg-blue-100 text-blue-700">
                    {rule.prefix}
                  </span>
                </td>
                <td className="px-4 py-3 text-sm text-gray-600">{rule.description}</td>
                <td className="px-4 py-3 text-sm font-mono text-gray-900 bg-gray-50">{rule.example}</td>
                <td className="px-4 py-3 text-center">
                  <button
                    onClick={() => toggleStatus(rule.id)}
                    className={`px-2 py-1 rounded-full text-xs font-medium ${rule.status === '활성'
                        ? 'bg-green-100 text-green-700'
                        : 'bg-gray-100 text-gray-500'
                      }`}
                  >
                    {rule.status}
                  </button>
                </td>
                <td className="px-4 py-3 text-center">
                  <div className="flex justify-center gap-2">
                    <button
                      onClick={() => openEditModal(rule)}
                      className="px-2 py-1 text-xs text-gray-600 hover:bg-gray-100 rounded border border-gray-200"
                      title="수정"
                    >
                      수정
                    </button>
                    <button
                      onClick={() => handleDelete(rule.id)}
                      className="px-2 py-1 text-xs text-red-500 hover:bg-red-50 rounded border border-red-200"
                      title="삭제"
                    >
                      삭제
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 등록/수정 모달 */}
      {showModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            {/* 모달 헤더 */}
            <div className="flex justify-between items-center p-4 border-b sticky top-0 bg-white">
              <h3 className="text-lg font-bold">
                {editingRule ? '코드기준 수정' : '코드기준 등록'}
              </h3>
              <button onClick={() => setShowModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>

            {/* 모달 내용 */}
            <div className="p-4 space-y-6">
              {/* 적용 대상 선택 */}
              <div className="space-y-4">
                <h4 className="font-medium text-gray-900 flex items-center gap-2">
                  <span className="w-6 h-6 bg-orange-100 text-orange-600 rounded-full flex items-center justify-center text-sm">1</span>
                  적용 대상 선택
                </h4>

                <div className="grid grid-cols-3 gap-2">
                  {targetTemplates.map(template => (
                    <button
                      key={template.value}
                      onClick={() => handleTargetChange(template.value)}
                      className={`p-3 border rounded-lg text-center transition-all ${formData.target === template.value
                          ? 'border-orange-500 bg-orange-50 ring-2 ring-orange-200'
                          : 'border-gray-200 hover:border-gray-300'
                        }`}
                    >
                      <div className="text-sm font-medium">{template.label}</div>
                    </button>
                  ))}
                </div>

                {/* 코드기준 이름 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    코드기준 이름 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                    className="w-full border rounded-lg px-3 py-2 text-sm"
                    placeholder="예: 입고LOT 기준"
                  />
                </div>
              </div>

              {/* 코드 유형 선택 */}
              <div className="space-y-4">
                <h4 className="font-medium text-gray-900 flex items-center gap-2">
                  <span className="w-6 h-6 bg-orange-100 text-orange-600 rounded-full flex items-center justify-center text-sm">2</span>
                  코드 유형
                </h4>

                <div className="grid grid-cols-3 gap-3">
                  {codeTypes.map(type => (
                    <button
                      key={type.value}
                      onClick={() => setFormData(prev => ({ ...prev, codeType: type.value }))}
                      className={`p-3 border rounded-lg text-left transition-all ${formData.codeType === type.value
                          ? 'border-orange-500 bg-orange-50 ring-2 ring-orange-200'
                          : 'border-gray-200 hover:border-gray-300'
                        }`}
                    >
                      <div className="font-medium text-sm">{type.label}</div>
                      <div className="text-xs text-gray-500 mt-1">{type.desc}</div>
                      <div className="text-xs font-mono text-orange-600 mt-1">{type.example}</div>
                    </button>
                  ))}
                </div>
              </div>

              {/* 코드 구성 설정 */}
              <div className="space-y-4">
                <h4 className="font-medium text-gray-900 flex items-center gap-2">
                  <span className="w-6 h-6 bg-orange-100 text-orange-600 rounded-full flex items-center justify-center text-sm">3</span>
                  코드 구성
                </h4>

                {/* 단순형, LOT형일 때만 접두사 표시 */}
                {formData.codeType !== 'composite' && (
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">접두사</label>
                      <input
                        type="text"
                        value={formData.prefix}
                        onChange={(e) => setFormData(prev => ({ ...prev, prefix: e.target.value }))}
                        className="w-full border rounded-lg px-3 py-2 text-sm font-mono"
                        placeholder="예: L, P, C"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">구분자</label>
                      <select
                        value={formData.separator}
                        onChange={(e) => setFormData(prev => ({ ...prev, separator: e.target.value }))}
                        className="w-full border rounded-lg px-3 py-2 text-sm"
                      >
                        {separatorOptions.map(opt => (
                          <option key={opt.value} value={opt.value}>{opt.label}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                )}

                {/* LOT형일 때 날짜/공정 옵션 */}
                {formData.codeType === 'lot' && (
                  <div className="space-y-4 p-4 bg-gray-50 rounded-lg">
                    <div className="flex items-center gap-4">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={formData.useDate}
                          onChange={(e) => setFormData(prev => ({ ...prev, useDate: e.target.checked }))}
                          className="rounded text-orange-500"
                        />
                        <span className="text-sm">날짜 포함</span>
                      </label>
                      {formData.useDate && (
                        <select
                          value={formData.dateFormat}
                          onChange={(e) => setFormData(prev => ({ ...prev, dateFormat: e.target.value }))}
                          className="border rounded-lg px-3 py-1.5 text-sm"
                        >
                          {dateFormats.map(opt => (
                            <option key={opt.value} value={opt.value}>{opt.label}</option>
                          ))}
                        </select>
                      )}
                    </div>
                    <label className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={formData.useProcess}
                        onChange={(e) => setFormData(prev => ({ ...prev, useProcess: e.target.checked }))}
                        className="rounded text-orange-500"
                      />
                      <span className="text-sm">공정코드 포함 (SC, SL, BD 등)</span>
                    </label>
                  </div>
                )}

                {/* 조합형 안내 */}
                {formData.codeType === 'composite' && (
                  <div className="p-4 bg-orange-50 rounded-lg">
                    <p className="text-sm text-orange-700">
                      <strong>조합형</strong>은 품목유형코드 + 카테고리코드 + 일련번호로 구성됩니다.
                    </p>
                    <p className="text-xs text-orange-600 mt-2">
                      예: BP(절곡부품) + GR(가이드레일) + 001 = BP-GR-001
                    </p>
                  </div>
                )}

                {/* 순번 자릿수 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">순번 자릿수</label>
                  <select
                    value={formData.seqDigits}
                    onChange={(e) => setFormData(prev => ({ ...prev, seqDigits: Number(e.target.value) }))}
                    className="w-full border rounded-lg px-3 py-2 text-sm"
                  >
                    {seqDigitOptions.map(opt => (
                      <option key={opt.value} value={opt.value}>{opt.label}</option>
                    ))}
                  </select>
                </div>
              </div>

              {/* 코드 미리보기 */}
              <div className="bg-gray-50 rounded-lg p-4 space-y-3">
                <h4 className="font-medium text-gray-900 flex items-center gap-2">
                  <span className="w-6 h-6 bg-green-100 text-green-600 rounded-full flex items-center justify-center text-sm">✓</span>
                  생성 코드 미리보기
                </h4>

                {/* 시각적 분해 */}
                <div className="flex items-center gap-1 justify-center py-4 flex-wrap">
                  {formData.codeType === 'composite' ? (
                    <>
                      <div className="bg-orange-100 text-orange-700 px-3 py-2 rounded font-mono text-sm">BP</div>
                      <div className="text-gray-400 text-lg">{formData.separator}</div>
                      <div className="bg-purple-100 text-purple-700 px-3 py-2 rounded font-mono text-sm">GR</div>
                      <div className="text-gray-400 text-lg">{formData.separator}</div>
                      <div className="bg-green-100 text-green-700 px-3 py-2 rounded font-mono text-sm">
                        {'0'.repeat(formData.seqDigits - 1)}1
                      </div>
                    </>
                  ) : (
                    <>
                      {formData.prefix && (
                        <>
                          <div className="bg-orange-100 text-orange-700 px-3 py-2 rounded font-mono text-sm">
                            {formData.prefix}
                          </div>
                          {formData.separator && <div className="text-gray-400 text-lg">{formData.separator}</div>}
                        </>
                      )}
                      {formData.useDate && (
                        <>
                          <div className="bg-purple-100 text-purple-700 px-3 py-2 rounded font-mono text-sm">
                            {dateFormats.find(d => d.value === formData.dateFormat)?.example}
                          </div>
                          {formData.separator && <div className="text-gray-400 text-lg">{formData.separator}</div>}
                        </>
                      )}
                      {formData.useProcess && (
                        <>
                          <div className="bg-blue-100 text-blue-700 px-3 py-2 rounded font-mono text-sm">SC</div>
                          {formData.separator && <div className="text-gray-400 text-lg">{formData.separator}</div>}
                        </>
                      )}
                      <div className="bg-green-100 text-green-700 px-3 py-2 rounded font-mono text-sm">
                        {'0'.repeat(formData.seqDigits - 1)}1
                      </div>
                    </>
                  )}
                </div>

                {/* 구성 설명 */}
                <div className="flex justify-center gap-4 text-xs text-gray-500 flex-wrap">
                  {formData.codeType === 'composite' ? (
                    <>
                      <span className="flex items-center gap-1">
                        <span className="w-3 h-3 bg-orange-100 rounded"></span> 품목유형
                      </span>
                      <span className="flex items-center gap-1">
                        <span className="w-3 h-3 bg-purple-100 rounded"></span> 카테고리
                      </span>
                      <span className="flex items-center gap-1">
                        <span className="w-3 h-3 bg-green-100 rounded"></span> 일련번호
                      </span>
                    </>
                  ) : (
                    <>
                      {formData.prefix && (
                        <span className="flex items-center gap-1">
                          <span className="w-3 h-3 bg-orange-100 rounded"></span> 접두사
                        </span>
                      )}
                      {formData.useDate && (
                        <span className="flex items-center gap-1">
                          <span className="w-3 h-3 bg-purple-100 rounded"></span> 날짜
                        </span>
                      )}
                      {formData.useProcess && (
                        <span className="flex items-center gap-1">
                          <span className="w-3 h-3 bg-blue-100 rounded"></span> 공정코드
                        </span>
                      )}
                      <span className="flex items-center gap-1">
                        <span className="w-3 h-3 bg-green-100 rounded"></span> 순번
                      </span>
                    </>
                  )}
                </div>

                {/* 최종 결과 */}
                <div className="text-center pt-2 border-t">
                  <span className="text-sm text-gray-500">생성될 코드: </span>
                  <span className="text-lg font-mono font-bold text-orange-600">
                    {generatePreview(formData)}
                  </span>
                </div>
              </div>

              {/* LOT번호 생성 규칙 참조 */}
              <div className="p-4 bg-gradient-to-r from-orange-50 to-blue-50 rounded-lg border border-orange-200">
                <h4 className="font-medium text-gray-900 mb-3">LOT번호 생성 규칙 (참조)</h4>
                <div className="flex items-center gap-2 justify-center flex-wrap">
                  <div className="bg-white border-2 border-gray-300 px-3 py-1.5 rounded font-mono text-sm font-bold">KD</div>
                  <span className="text-gray-400">-</span>
                  <div className="bg-orange-100 border-2 border-orange-400 px-3 py-1.5 rounded font-mono text-sm font-bold text-orange-700">XX</div>
                  <span className="text-gray-400">-</span>
                  <div className="bg-blue-100 border-2 border-blue-400 px-3 py-1.5 rounded font-mono text-sm font-bold text-blue-700">YYMMDD</div>
                  <span className="text-gray-400">-</span>
                  <div className="bg-green-100 border-2 border-green-400 px-3 py-1.5 rounded font-mono text-sm font-bold text-green-700">NN</div>
                </div>
                <div className="flex justify-center gap-4 mt-2 text-xs text-gray-500 flex-wrap">
                  <span className="flex items-center gap-1"><span className="w-2 h-2 bg-gray-200 rounded"></span> 회사코드</span>
                  <span className="flex items-center gap-1"><span className="w-2 h-2 bg-orange-200 rounded"></span> 인정제품</span>
                  <span className="flex items-center gap-1"><span className="w-2 h-2 bg-blue-200 rounded"></span> 생성일자</span>
                  <span className="flex items-center gap-1"><span className="w-2 h-2 bg-green-200 rounded"></span> 순번</span>
                </div>
                <div className="text-center mt-2">
                  <span className="text-xs text-gray-500">예시: </span>
                  <span className="font-mono font-medium text-sm">KD-SS-240919-01</span>
                </div>
              </div>

              {/* 상태 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">상태</label>
                <div className="flex gap-4">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="codeStatus"
                      value="활성"
                      checked={formData.status === '활성'}
                      onChange={(e) => setFormData(prev => ({ ...prev, status: e.target.value }))}
                      className="text-orange-500"
                    />
                    <span className="text-sm">활성</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="codeStatus"
                      value="비활성"
                      checked={formData.status === '비활성'}
                      onChange={(e) => setFormData(prev => ({ ...prev, status: e.target.value }))}
                      className="text-orange-500"
                    />
                    <span className="text-sm">비활성</span>
                  </label>
                </div>
              </div>
            </div>

            {/* 모달 푸터 */}
            <div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
              <button
                onClick={() => setShowModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleSave}
                disabled={!formData.target || !formData.name}
                className="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 disabled:bg-gray-300 disabled:cursor-not-allowed"
              >
                {editingRule ? '수정' : '등록'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============================================================
// 재고 현황 컴포넌트 (통합)
// ============================================================
const StockList = ({ inventory = [], onNavigate }) => {
  const [selectedItemType, setSelectedItemType] = useState('전체');
  const [selectedCategory, setSelectedCategory] = useState('전체');
  const [search, setSearch] = useState('');
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  // 품목별 샘플 LOT 데이터 생성 (실제로는 서버에서 조회)
  const generateSampleLots = (item) => {
    const today = new Date();
    const lots = [];
    const lotCount = Math.min(Math.ceil(item.stock / 30), 5); // 최대 5개 LOT
    let remainingStock = item.stock;

    for (let i = 0; i < lotCount && remainingStock > 0; i++) {
      const daysAgo = (lotCount - i) * 7 + Math.floor(Math.random() * 5); // 오래된 순
      const inboundDate = new Date(today);
      inboundDate.setDate(inboundDate.getDate() - daysAgo);

      const qty = i === lotCount - 1 ? remainingStock : Math.floor(remainingStock / (lotCount - i) * (0.8 + Math.random() * 0.4));
      remainingStock -= qty;

      const suppliers = ['포스코', '현대제철', '동국제강', '세아제강', '한국철강'];
      const locations = ['A-01', 'A-02', 'B-01', 'B-02', 'C-01'];

      lots.push({
        id: `${item.materialCode}-LOT-${i + 1}`,
        lotNo: `${inboundDate.toISOString().slice(2, 10).replace(/-/g, '')}-${String(i + 1).padStart(2, '0')}`,
        inboundDate: inboundDate.toISOString().split('T')[0],
        supplier: suppliers[i % suppliers.length],
        qty: qty,
        remainingQty: qty,
        location: locations[i % locations.length],
        status: qty > 0 ? 'AVAILABLE' : 'DEPLETED',
        daysInStock: daysAgo,
        poNo: `PO-${inboundDate.toISOString().slice(2, 10).replace(/-/g, '')}-${String(Math.floor(Math.random() * 99) + 1).padStart(2, '0')}`,
      });
    }

    // FIFO 순서 (입고일 오름차순 - 오래된 것 먼저)
    return lots.sort((a, b) => new Date(a.inboundDate) - new Date(b.inboundDate));
  };

  // LOT 상태별 색상
  const getLotStatusStyle = (status, daysInStock) => {
    if (daysInStock > 30) return 'bg-orange-100 text-orange-700'; // 장기 재고
    if (status === 'AVAILABLE') return 'bg-green-100 text-green-700';
    if (status === 'RESERVED') return 'bg-blue-100 text-blue-700';
    if (status === 'HOLD') return 'bg-yellow-100 text-yellow-700';
    return 'bg-gray-100 text-gray-700';
  };

  // 행 클릭 시 상세 페이지로 이동
  const handleRowClick = (item) => {
    onNavigate?.('stock-detail', item);
  };

  // 품목유형 목록
  const itemTypes = [
    { code: '전체', name: '전체' },
    { code: '원자재', name: '원자재' },
    { code: '절곡부품', name: '절곡부품' },
    { code: '구매부품', name: '구매부품' },
    { code: '부자재', name: '부자재' },
    { code: '소모품', name: '소모품' },
  ];

  // 현재 품목유형에 해당하는 품목들
  const filteredByType = selectedItemType === '전체'
    ? inventory
    : inventory.filter(item => item.itemType === selectedItemType);

  // 카테고리 목록 추출 (현재 품목유형 기준)
  const categories = ['전체', ...new Set(filteredByType.map(p => p.category).filter(Boolean))];

  // 카테고리 필터 적용
  const filteredByCategory = selectedCategory === '전체'
    ? filteredByType
    : filteredByType.filter(item => item.category === selectedCategory);

  // 검색 필터 적용 (ID 내림차순 정렬 - 최신 등록 최상단)
  const filteredItems = filteredByCategory.filter(item => {
    if (!search) return true;
    return item.materialCode.toLowerCase().includes(search.toLowerCase()) ||
      item.materialName.toLowerCase().includes(search.toLowerCase());
  }).sort((a, b) => b.id - a.id);

  // 목록 선택 훅
  const {
    selectedIds,
    handleSelect,
    handleSelectAll,
    clearSelection,
    isAllSelected,
    hasSelection,
    isMultiSelect,
    isSelected,
  } = useListSelection(filteredItems);

  // 품목유형별 통계
  const getTypeStats = (typeCode) => {
    const items = typeCode === '전체' ? inventory : inventory.filter(i => i.itemType === typeCode);
    return {
      count: items.length,
      lowStock: items.filter(i => i.stock <= i.minStock).length,
    };
  };

  // 재고 상태 판단
  const getStockStatus = (item) => {
    if (item.stock === 0) return { label: '재고없음', color: 'bg-red-100 text-red-700' };
    if (item.stock <= item.minStock) return { label: '부족', color: 'bg-orange-100 text-orange-700' };
    return { label: '정상', color: 'bg-green-100 text-green-700' };
  };

  // 품목유형 변경 시 카테고리 초기화
  const handleTypeChange = (type) => {
    setSelectedItemType(type);
    setSelectedCategory('전체');
  };

  // 재고 통계 계산
  const totalItems = inventory.length;
  const lowStockItems = inventory.filter(i => i.stock <= i.minStock && i.stock > 0).length;
  const noStockItems = inventory.filter(i => i.stock === 0).length;
  const normalItems = inventory.filter(i => i.stock > i.minStock).length;

  return (
    <div className="space-y-6">
      {/* 헤더 - PageHeader 사용 */}
      <PageHeader
        icon={Package}
        title="재고 목록"
        actions={
          <Button variant="secondary" onClick={() => { }}>
            <Download className="w-4 h-4" /> 엑셀 다운로드
          </Button>
        }
      />

      {/* 리포트 카드 - 4개 한 줄 */}
      <div className="grid grid-cols-4 gap-4">
        <DashboardCard
          icon={Package}
          title="전체 품목"
          value={`${totalItems}종`}
          color="blue"
          onClick={() => handleTypeChange('전체')}
        />
        <DashboardCard
          icon={CheckCircle}
          title="정상 재고"
          value={`${normalItems}종`}
          color="green"
        />
        <DashboardCard
          icon={AlertCircle}
          title="재고 부족"
          value={`${lowStockItems}종`}
          color="yellow"
        />
        <DashboardCard
          icon={XCircle}
          title="재고 없음"
          value={`${noStockItems}종`}
          color="red"
        />
      </div>

      {/* 품목유형 칩 탭 */}
      <div className="flex items-center gap-3 flex-wrap">
        {itemTypes.map(type => {
          const stats = getTypeStats(type.code);
          const isActive = selectedItemType === type.code;
          return (
            <button
              key={type.code}
              onClick={() => handleTypeChange(type.code)}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-all ${
                isActive
                  ? 'bg-blue-600 text-white shadow-sm'
                  : 'bg-white text-gray-700 border border-gray-200 hover:border-blue-300 hover:bg-blue-50'
              }`}
            >
              {type.name}
              <span className={`ml-2 px-2 py-0.5 rounded-full text-xs ${
                isActive ? 'bg-blue-500' : 'bg-gray-100'
              }`}>
                {stats.count}
              </span>
            </button>
          );
        })}
      </div>

      {/* 검색바 */}
      <div>
        <SearchInput
          placeholder="품목코드, 품목명 검색..."
          value={search}
          onChange={setSearch}
        />
      </div>

      {/* 테이블 */}
      <div className="bg-white rounded-lg shadow-sm border">
        {/* 선택 삭제 버튼 (2개 이상 선택 시) */}
        {isMultiSelect && (
          <div className="px-4 py-2 bg-gray-50 border-b flex justify-end">
            <button
              onClick={() => setShowDeleteModal(true)}
              className="px-3 py-1.5 bg-red-600 text-white text-sm rounded hover:bg-red-700 flex items-center gap-1"
            >
              <Trash2 className="w-4 h-4" />
              선택 삭제 ({selectedIds.length})
            </button>
          </div>
        )}
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-center w-10">
                  <input
                    type="checkbox"
                    checked={isAllSelected}
                    onChange={handleSelectAll}
                    className="rounded border-gray-300"
                  />
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목코드</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목유형</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">단위</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">재고량</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">안전재고</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">LOT</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">위치</th>
                {hasSelection && (
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">관리</th>
                )}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {filteredItems.length === 0 ? (
                <tr>
                  <td colSpan={hasSelection ? 11 : 10} className="px-4 py-8 text-center text-gray-500">
                    해당 조건의 품목이 없습니다.
                  </td>
                </tr>
              ) : (
                filteredItems.map(item => {
                  const status = getStockStatus(item);
                  const selected = isSelected(item.id);

                  return (
                    <React.Fragment key={item.id}>
                      <tr
                        className={`hover:bg-gray-50 cursor-pointer ${selected ? 'bg-blue-50' : ''}`}
                        onClick={() => handleRowClick(item)}
                      >
                        <td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                          <input
                            type="checkbox"
                            checked={selected}
                            onChange={() => handleSelect(item.id)}
                            className="rounded border-gray-300"
                          />
                        </td>
                        <td className="px-4 py-3 text-sm font-mono text-blue-600 font-medium">
                          {item.materialCode}
                        </td>
                        <td className="px-4 py-3 text-sm text-gray-900">{item.materialName}</td>
                        <td className="px-4 py-3 text-sm">
                          <span className={`px-2 py-0.5 rounded text-xs ${item.itemType === '원자재' ? 'bg-purple-100 text-purple-700' :
                              item.itemType === '절곡부품' ? 'bg-orange-100 text-orange-700' :
                                item.itemType === '구매부품' ? 'bg-blue-100 text-blue-700' :
                                  item.itemType === '부자재' ? 'bg-gray-100 text-gray-700' :
                                    'bg-gray-100 text-gray-600'
                            }`}>
                            {item.itemType || '-'}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-sm text-center text-gray-600">{item.unit}</td>
                        <td className="px-4 py-3 text-sm text-right font-medium text-gray-900">{item.stock.toLocaleString()}</td>
                        <td className="px-4 py-3 text-sm text-right text-gray-500">{item.minStock.toLocaleString()}</td>
                        <td className="px-4 py-3 text-center">
                          <div className="flex flex-col items-center gap-0.5">
                            <span className="text-sm font-medium text-gray-900">{item.lotCount || 0}개</span>
                            {item.oldestLotDays && (
                              <span className={`text-xs ${item.oldestLotDays > 60 ? 'text-red-600 font-medium' :
                                  item.oldestLotDays > 30 ? 'text-orange-600' :
                                    'text-gray-500'
                                }`}>
                                {item.oldestLotDays > 60 ? '⚠️ ' : ''}{item.oldestLotDays}일 경과
                              </span>
                            )}
                          </div>
                        </td>
                        <td className="px-4 py-3 text-center">
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${status.color}`}>
                            {status.label}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-sm text-center text-gray-500">{item.location}</td>
                        {hasSelection && (
                          <td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                            {selected && (
                              <div className="flex items-center justify-center gap-1">
                                <button className="p-1 text-blue-600 hover:bg-blue-50 rounded">
                                  <Edit3 className="w-4 h-4" />
                                </button>
                                <button
                                  onClick={() => setShowDeleteModal(true)}
                                  className="p-1 text-red-600 hover:bg-red-50 rounded"
                                >
                                  <Trash2 className="w-4 h-4" />
                                </button>
                              </div>
                            )}
                          </td>
                        )}
                      </tr>
                    </React.Fragment>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* 요약 */}
        {filteredItems.length > 0 && (
          <div className="px-4 py-3 bg-gray-50 border-t text-sm text-gray-600">
            총 <span className="font-medium">{filteredItems.length}</span>종 /
            재고부족 <span className="font-medium text-orange-600">{filteredItems.filter(i => i.stock <= i.minStock).length}</span>종
          </div>
        )}
      </div>
    </div>
  );
};

// ============================================================
// 재고조정 컴포넌트 (실사/조정/폐기 관리)
// ============================================================
const StockAdjustment = ({ inventory = [], onNavigate }) => {
  const [activeTab, setActiveTab] = useState('list'); // list, register
  const [search, setSearch] = useState('');
  const [filterType, setFilterType] = useState('전체');
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectedAdjustment, setSelectedAdjustment] = useState(null);
  const [showRegisterModal, setShowRegisterModal] = useState(false);

  // 조정 유형
  const adjustmentTypes = [
    { code: 'PHYSICAL_COUNT', name: '실사조정', icon: ClipboardList, color: 'blue', desc: '실사 결과 반영' },
    { code: 'DEFECT_SCRAP', name: '불량폐기', icon: Trash2, color: 'red', desc: '불량품 재고 차감' },
    { code: 'EXPIRED_SCRAP', name: '만료폐기', icon: Clock, color: 'orange', desc: '유통기한 만료품' },
    { code: 'LOCATION_MOVE', name: '위치이동', icon: ArrowRight, color: 'green', desc: '창고/위치 간 이동' },
    { code: 'OTHER', name: '기타조정', icon: Edit3, color: 'gray', desc: '기타 사유 조정' },
  ];

  // 샘플 조정 이력 데이터
  const [adjustments, setAdjustments] = useState([
    {
      id: 1,
      adjustNo: 'ADJ-241218-01',
      adjustType: 'PHYSICAL_COUNT',
      adjustDate: '2024-12-18',
      itemCode: 'STEEL-1.2T',
      itemName: '철판 1.2T',
      lotNo: '241210-01',
      beforeQty: 100,
      adjustQty: -5,
      afterQty: 95,
      reason: '정기 실사 결과 차이 발생',
      location: 'A-01',
      status: '승인완료',
      approver: '김공장장',
      approvedAt: '2024-12-18 14:30',
      createdBy: '이재고',
      createdAt: '2024-12-18 10:00',
    },
    {
      id: 2,
      adjustNo: 'ADJ-241217-02',
      adjustType: 'DEFECT_SCRAP',
      adjustDate: '2024-12-17',
      itemCode: 'E-220V-300KG',
      itemName: '전동개폐기 220V 300KG',
      lotNo: '241205-01',
      beforeQty: 20,
      adjustQty: -2,
      afterQty: 18,
      reason: 'IQC 불합격 처리',
      location: 'B-02',
      status: '승인완료',
      approver: '김공장장',
      approvedAt: '2024-12-17 16:20',
      createdBy: '박품질',
      createdAt: '2024-12-17 11:00',
    },
    {
      id: 3,
      adjustNo: 'ADJ-241217-01',
      adjustType: 'LOCATION_MOVE',
      adjustDate: '2024-12-17',
      itemCode: 'SCR-0.3T',
      itemName: '스크린망 0.3T',
      lotNo: '241201-03',
      beforeQty: 50,
      adjustQty: 0,
      afterQty: 50,
      reason: '창고 재배치',
      location: 'A-01 → C-01',
      status: '승인완료',
      approver: '김공장장',
      approvedAt: '2024-12-17 09:30',
      createdBy: '이재고',
      createdAt: '2024-12-17 09:00',
    },
    {
      id: 4,
      adjustNo: 'ADJ-241216-01',
      adjustType: 'EXPIRED_SCRAP',
      adjustDate: '2024-12-16',
      itemCode: 'RUBBER-PAD',
      itemName: '고무패킹',
      lotNo: '240601-01',
      beforeQty: 30,
      adjustQty: -30,
      afterQty: 0,
      reason: '유통기한 만료 (6개월 경과)',
      location: 'D-01',
      status: '승인완료',
      approver: '김공장장',
      approvedAt: '2024-12-16 17:00',
      createdBy: '박품질',
      createdAt: '2024-12-16 14:00',
    },
    {
      id: 5,
      adjustNo: 'ADJ-241215-01',
      adjustType: 'OTHER',
      adjustDate: '2024-12-15',
      itemCode: 'BOLT-M8',
      itemName: '볼트 M8×20',
      lotNo: '241101-02',
      beforeQty: 500,
      adjustQty: -10,
      afterQty: 490,
      reason: '샘플 출고 (품질 테스트용)',
      location: 'E-01',
      status: '승인대기',
      approver: null,
      approvedAt: null,
      createdBy: '이재고',
      createdAt: '2024-12-15 11:30',
    },
  ]);

  // 등록 폼 상태
  const [registerForm, setRegisterForm] = useState({
    adjustType: '',
    itemCode: '',
    itemName: '',
    lotNo: '',
    currentQty: 0,
    adjustQty: '',
    reason: '',
    fromLocation: '',
    toLocation: '',
  });

  // 조정 유형별 색상
  const getTypeStyle = (typeCode) => {
    const type = adjustmentTypes.find(t => t.code === typeCode);
    if (!type) return 'bg-gray-100 text-gray-700';
    const colors = {
      blue: 'bg-blue-100 text-blue-700',
      red: 'bg-red-100 text-red-700',
      orange: 'bg-orange-100 text-orange-700',
      green: 'bg-green-100 text-green-700',
      gray: 'bg-gray-100 text-gray-700',
    };
    return colors[type.color] || colors.gray;
  };

  // 상태별 스타일
  const getStatusStyle = (status) => {
    if (status === '승인완료') return 'bg-green-100 text-green-700';
    if (status === '승인대기') return 'bg-yellow-100 text-yellow-700';
    if (status === '반려') return 'bg-red-100 text-red-700';
    return 'bg-gray-100 text-gray-700';
  };

  // 필터링된 데이터
  const filteredAdjustments = adjustments.filter(adj => {
    const matchType = filterType === '전체' || adj.adjustType === filterType;
    const matchSearch = !search ||
      adj.adjustNo.toLowerCase().includes(search.toLowerCase()) ||
      adj.itemCode.toLowerCase().includes(search.toLowerCase()) ||
      adj.itemName.toLowerCase().includes(search.toLowerCase()) ||
      adj.lotNo.toLowerCase().includes(search.toLowerCase());
    return matchType && matchSearch;
  }).sort((a, b) => b.id - a.id);

  // 통계 계산
  const stats = {
    total: adjustments.length,
    pending: adjustments.filter(a => a.status === '승인대기').length,
    thisMonth: adjustments.filter(a => a.adjustDate.startsWith('2024-12')).length,
    scrapQty: adjustments.filter(a => ['DEFECT_SCRAP', 'EXPIRED_SCRAP'].includes(a.adjustType))
      .reduce((sum, a) => sum + Math.abs(a.adjustQty), 0),
  };

  // 상세 보기
  const handleViewDetail = (adj) => {
    setSelectedAdjustment(adj);
    setShowDetailModal(true);
  };

  // 조정 유형명
  const getTypeName = (typeCode) => {
    const type = adjustmentTypes.find(t => t.code === typeCode);
    return type ? type.name : typeCode;
  };

  // 조정 등록 모달 열기
  const handleOpenRegister = (typeCode = '') => {
    setRegisterForm({
      adjustType: typeCode,
      itemCode: '',
      itemName: '',
      lotNo: '',
      currentQty: 0,
      adjustQty: '',
      reason: '',
      fromLocation: '',
      toLocation: '',
    });
    setShowRegisterModal(true);
  };

  // 조정 등록 처리
  const handleRegister = () => {
    const today = new Date();
    const dateStr = today.toISOString().slice(2, 10).replace(/-/g, '');
    const seq = String(adjustments.filter(a => a.adjustDate === today.toISOString().split('T')[0]).length + 1).padStart(2, '0');

    const newAdjustment = {
      id: adjustments.length + 1,
      adjustNo: `ADJ-${dateStr}-${seq}`,
      adjustType: registerForm.adjustType,
      adjustDate: today.toISOString().split('T')[0],
      itemCode: registerForm.itemCode,
      itemName: registerForm.itemName,
      lotNo: registerForm.lotNo,
      beforeQty: registerForm.currentQty,
      adjustQty: parseInt(registerForm.adjustQty) || 0,
      afterQty: registerForm.currentQty + (parseInt(registerForm.adjustQty) || 0),
      reason: registerForm.reason,
      location: registerForm.adjustType === 'LOCATION_MOVE'
        ? `${registerForm.fromLocation} → ${registerForm.toLocation}`
        : registerForm.fromLocation,
      status: '승인대기',
      approver: null,
      approvedAt: null,
      createdBy: '현재사용자',
      createdAt: today.toISOString().slice(0, 16).replace('T', ' '),
    };

    setAdjustments([newAdjustment, ...adjustments]);
    setShowRegisterModal(false);
  };

  // 품목 선택 시 (실제로는 모달이나 검색으로 선택)
  const handleSelectItem = (item) => {
    setRegisterForm(prev => ({
      ...prev,
      itemCode: item.materialCode,
      itemName: item.materialName,
      currentQty: item.stock,
      fromLocation: 'A-01', // 기본값
    }));
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <PageHeader
        icon={RefreshCw}
        title="재고 조정"
        actions={
          <Button variant="primary" onClick={() => handleOpenRegister()}>
            <Plus className="w-4 h-4" /> 조정 등록
          </Button>
        }
      />

      {/* 리포트 카드 - 4개 한 줄 */}
      <div className="grid grid-cols-4 gap-4">
        <DashboardCard
          icon={ClipboardList}
          title="전체 조정"
          value={`${stats.total}건`}
          color="blue"
        />
        <DashboardCard
          icon={Clock}
          title="승인 대기"
          value={`${stats.pending}건`}
          color="yellow"
        />
        <DashboardCard
          icon={Calendar}
          title="이번 달 조정"
          value={`${stats.thisMonth}건`}
          color="green"
        />
        <DashboardCard
          icon={Trash2}
          title="폐기 수량"
          value={`${stats.scrapQty}개`}
          color="red"
        />
      </div>

      {/* 조정 유형 버튼 */}
      <Card className="p-4">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-sm font-medium text-gray-600 mr-2">빠른 등록:</span>
          {adjustmentTypes.map(type => {
            const Icon = type.icon;
            return (
              <button
                key={type.code}
                onClick={() => handleOpenRegister(type.code)}
                className={`flex items-center gap-2 px-3 py-2 rounded-lg border hover:bg-gray-50 transition-colors`}
              >
                <Icon className="w-4 h-4" />
                <span className="text-sm">{type.name}</span>
              </button>
            );
          })}
        </div>
      </Card>

      {/* 검색 및 필터 */}
      <div className="flex items-center gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder="조정번호, 품목코드, 품목명, LOT번호 검색..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 border rounded-lg"
          />
        </div>
        <select
          value={filterType}
          onChange={(e) => setFilterType(e.target.value)}
          className="px-4 py-2.5 border rounded-lg bg-white"
        >
          <option value="전체">전체 유형</option>
          {adjustmentTypes.map(type => (
            <option key={type.code} value={type.code}>{type.name}</option>
          ))}
        </select>
      </div>

      {/* 조정 이력 테이블 */}
      <Card>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">조정번호</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">유형</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">조정일</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">품목</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">LOT</th>
                <th className="px-4 py-3 text-right text-sm font-medium text-gray-600">조정 전</th>
                <th className="px-4 py-3 text-right text-sm font-medium text-gray-600">조정량</th>
                <th className="px-4 py-3 text-right text-sm font-medium text-gray-600">조정 후</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">위치</th>
                <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">상태</th>
                <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">작업</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {filteredAdjustments.map(adj => (
                <tr key={adj.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3 text-sm font-mono">{adj.adjustNo}</td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-1 text-xs rounded-full ${getTypeStyle(adj.adjustType)}`}>
                      {getTypeName(adj.adjustType)}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-sm">{adj.adjustDate}</td>
                  <td className="px-4 py-3">
                    <div className="text-sm font-medium">{adj.itemName}</div>
                    <div className="text-xs text-gray-500">{adj.itemCode}</div>
                  </td>
                  <td className="px-4 py-3 text-sm font-mono">{adj.lotNo}</td>
                  <td className="px-4 py-3 text-sm text-right">{adj.beforeQty}</td>
                  <td className="px-4 py-3 text-sm text-right font-medium">
                    <span className={adj.adjustQty < 0 ? 'text-red-600' : adj.adjustQty > 0 ? 'text-blue-600' : ''}>
                      {adj.adjustQty > 0 ? '+' : ''}{adj.adjustQty}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-sm text-right font-medium">{adj.afterQty}</td>
                  <td className="px-4 py-3 text-sm">{adj.location}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`px-2 py-1 text-xs rounded-full ${getStatusStyle(adj.status)}`}>
                      {adj.status}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <button
                      onClick={() => handleViewDetail(adj)}
                      className="p-1 text-gray-400 hover:text-blue-600"
                    >
                      <Eye className="w-4 h-4" />
                    </button>
                  </td>
                </tr>
              ))}
              {filteredAdjustments.length === 0 && (
                <tr>
                  <td colSpan={11} className="px-4 py-8 text-center text-gray-500">
                    조정 이력이 없습니다.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* 요약 */}
        {filteredAdjustments.length > 0 && (
          <div className="px-4 py-3 bg-gray-50 border-t text-sm text-gray-600">
            총 <span className="font-medium">{filteredAdjustments.length}</span>건 /
            승인대기 <span className="font-medium text-yellow-600">{filteredAdjustments.filter(a => a.status === '승인대기').length}</span>건
          </div>
        )}
      </Card>

      {/* 상세 모달 */}
      {showDetailModal && selectedAdjustment && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg mx-4">
            <div className="flex items-center justify-between p-4 border-b">
              <h3 className="text-lg font-bold">조정 상세</h3>
              <button onClick={() => setShowDetailModal(false)} className="p-1 hover:bg-gray-100 rounded">
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-4 space-y-4">
              <div className="flex items-center gap-3">
                <span className={`px-3 py-1 text-sm rounded-full ${getTypeStyle(selectedAdjustment.adjustType)}`}>
                  {getTypeName(selectedAdjustment.adjustType)}
                </span>
                <span className={`px-3 py-1 text-sm rounded-full ${getStatusStyle(selectedAdjustment.status)}`}>
                  {selectedAdjustment.status}
                </span>
              </div>

              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <div className="text-gray-500">조정번호</div>
                  <div className="font-mono font-medium">{selectedAdjustment.adjustNo}</div>
                </div>
                <div>
                  <div className="text-gray-500">조정일</div>
                  <div>{selectedAdjustment.adjustDate}</div>
                </div>
                <div>
                  <div className="text-gray-500">품목코드</div>
                  <div className="font-mono">{selectedAdjustment.itemCode}</div>
                </div>
                <div>
                  <div className="text-gray-500">품목명</div>
                  <div>{selectedAdjustment.itemName}</div>
                </div>
                <div>
                  <div className="text-gray-500">LOT번호</div>
                  <div className="font-mono">{selectedAdjustment.lotNo}</div>
                </div>
                <div>
                  <div className="text-gray-500">위치</div>
                  <div>{selectedAdjustment.location}</div>
                </div>
              </div>

              <div className="bg-gray-50 rounded-lg p-4">
                <div className="grid grid-cols-3 gap-4 text-center">
                  <div>
                    <div className="text-sm text-gray-500">조정 전</div>
                    <div className="text-xl font-bold">{selectedAdjustment.beforeQty}</div>
                  </div>
                  <div>
                    <div className="text-sm text-gray-500">조정량</div>
                    <div className={`text-xl font-bold ${selectedAdjustment.adjustQty < 0 ? 'text-red-600' : 'text-blue-600'}`}>
                      {selectedAdjustment.adjustQty > 0 ? '+' : ''}{selectedAdjustment.adjustQty}
                    </div>
                  </div>
                  <div>
                    <div className="text-sm text-gray-500">조정 후</div>
                    <div className="text-xl font-bold">{selectedAdjustment.afterQty}</div>
                  </div>
                </div>
              </div>

              <div>
                <div className="text-sm text-gray-500 mb-1">조정 사유</div>
                <div className="p-3 bg-gray-50 rounded-lg text-sm">{selectedAdjustment.reason}</div>
              </div>

              <div className="grid grid-cols-2 gap-4 text-sm pt-2 border-t">
                <div>
                  <div className="text-gray-500">등록자</div>
                  <div>{selectedAdjustment.createdBy}</div>
                  <div className="text-xs text-gray-400">{selectedAdjustment.createdAt}</div>
                </div>
                {selectedAdjustment.approver && (
                  <div>
                    <div className="text-gray-500">승인자</div>
                    <div>{selectedAdjustment.approver}</div>
                    <div className="text-xs text-gray-400">{selectedAdjustment.approvedAt}</div>
                  </div>
                )}
              </div>
            </div>

            <div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
              <button
                onClick={() => setShowDetailModal(false)}
                className="px-4 py-2 border rounded-lg hover:bg-gray-100"
              >
                닫기
              </button>
              {selectedAdjustment.status === '승인대기' && (
                <button
                  onClick={() => {
                    setAdjustments(adjustments.map(a =>
                      a.id === selectedAdjustment.id
                        ? { ...a, status: '승인완료', approver: '김공장장', approvedAt: new Date().toISOString().slice(0, 16).replace('T', ' ') }
                        : a
                    ));
                    setShowDetailModal(false);
                  }}
                  className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700"
                >
                  승인
                </button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 등록 모달 */}
      {showRegisterModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg mx-4">
            <div className="flex items-center justify-between p-4 border-b">
              <h3 className="text-lg font-bold">재고 조정 등록</h3>
              <button onClick={() => setShowRegisterModal(false)} className="p-1 hover:bg-gray-100 rounded">
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-4 space-y-4">
              {/* 조정 유형 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">조정 유형 *</label>
                <div className="grid grid-cols-3 gap-2">
                  {adjustmentTypes.map(type => {
                    const Icon = type.icon;
                    return (
                      <button
                        key={type.code}
                        type="button"
                        onClick={() => setRegisterForm(prev => ({ ...prev, adjustType: type.code }))}
                        className={`flex flex-col items-center gap-1 p-3 rounded-lg border-2 transition-colors ${registerForm.adjustType === type.code
                            ? 'border-blue-500 bg-blue-50'
                            : 'border-gray-200 hover:border-gray-300'
                          }`}
                      >
                        <Icon className="w-5 h-5" />
                        <span className="text-xs">{type.name}</span>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* 품목 선택 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">품목 *</label>
                <select
                  value={registerForm.itemCode}
                  onChange={(e) => {
                    const item = inventory.find(i => i.materialCode === e.target.value);
                    if (item) handleSelectItem(item);
                  }}
                  className="w-full px-3 py-2 border rounded-lg"
                >
                  <option value="">품목 선택</option>
                  {inventory.map(item => (
                    <option key={item.materialCode} value={item.materialCode}>
                      [{item.materialCode}] {item.materialName} (재고: {item.stock})
                    </option>
                  ))}
                </select>
              </div>

              {/* LOT 선택 */}
              {registerForm.itemCode && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">LOT번호 *</label>
                  <select
                    value={registerForm.lotNo}
                    onChange={(e) => setRegisterForm(prev => ({ ...prev, lotNo: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                  >
                    <option value="">LOT 선택</option>
                    <option value="241210-01">241210-01 (수량: 50)</option>
                    <option value="241205-02">241205-02 (수량: 30)</option>
                    <option value="241201-03">241201-03 (수량: 20)</option>
                  </select>
                </div>
              )}

              {/* 현재 수량 / 조정량 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">현재 수량</label>
                  <input
                    type="number"
                    value={registerForm.currentQty}
                    readOnly
                    className="w-full px-3 py-2 border rounded-lg bg-gray-50"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    조정량 * {registerForm.adjustType !== 'LOCATION_MOVE' && '(증가: +, 감소: -)'}
                  </label>
                  <input
                    type="number"
                    value={registerForm.adjustQty}
                    onChange={(e) => setRegisterForm(prev => ({ ...prev, adjustQty: e.target.value }))}
                    placeholder={registerForm.adjustType === 'LOCATION_MOVE' ? '이동 수량' : '예: -5'}
                    className="w-full px-3 py-2 border rounded-lg"
                    disabled={registerForm.adjustType === 'LOCATION_MOVE'}
                  />
                </div>
              </div>

              {/* 위치 (이동인 경우) */}
              {registerForm.adjustType === 'LOCATION_MOVE' ? (
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">출발 위치 *</label>
                    <input
                      type="text"
                      value={registerForm.fromLocation}
                      onChange={(e) => setRegisterForm(prev => ({ ...prev, fromLocation: e.target.value }))}
                      placeholder="예: A-01"
                      className="w-full px-3 py-2 border rounded-lg"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">도착 위치 *</label>
                    <input
                      type="text"
                      value={registerForm.toLocation}
                      onChange={(e) => setRegisterForm(prev => ({ ...prev, toLocation: e.target.value }))}
                      placeholder="예: B-02"
                      className="w-full px-3 py-2 border rounded-lg"
                    />
                  </div>
                </div>
              ) : (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">위치</label>
                  <input
                    type="text"
                    value={registerForm.fromLocation}
                    onChange={(e) => setRegisterForm(prev => ({ ...prev, fromLocation: e.target.value }))}
                    placeholder="예: A-01"
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
              )}

              {/* 조정 사유 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">조정 사유 *</label>
                <textarea
                  value={registerForm.reason}
                  onChange={(e) => setRegisterForm(prev => ({ ...prev, reason: e.target.value }))}
                  placeholder="조정 사유를 입력하세요"
                  className="w-full px-3 py-2 border rounded-lg h-20 resize-none"
                />
              </div>

              {/* 조정 결과 미리보기 */}
              {registerForm.adjustQty && registerForm.adjustType !== 'LOCATION_MOVE' && (
                <div className="bg-blue-50 rounded-lg p-3">
                  <div className="text-sm text-blue-700">
                    조정 결과: {registerForm.currentQty} → {registerForm.currentQty + parseInt(registerForm.adjustQty)}
                  </div>
                </div>
              )}
            </div>

            <div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
              <button
                onClick={() => setShowRegisterModal(false)}
                className="px-4 py-2 border rounded-lg hover:bg-gray-100"
              >
                취소
              </button>
              <button
                onClick={handleRegister}
                disabled={!registerForm.adjustType || !registerForm.itemCode || !registerForm.reason}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed"
              >
                등록
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============================================================
// 입고관리 컴포넌트 (견적 목록 스타일 적용)
// ============================================================
const InboundManagement = ({
  purchaseOrders = [],
  inventory = [],
  onReceive,
  onNavigate,
  onCreateInspection
}) => {
  const [activeTab, setActiveTab] = useState('all'); // all, pending, received
  const [selectedPO, setSelectedPO] = useState(null);
  const [showReceiveModal, setShowReceiveModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showInboundSlip, setShowInboundSlip] = useState(false);
  const [slipData, setSlipData] = useState(null);
  const [search, setSearch] = useState('');
  const [selectedIds, setSelectedIds] = useState([]);
  const [receiveForm, setReceiveForm] = useState({
    receivedQty: '',
    incomingLot: '',
    supplierLot: '',
    location: '',
    note: '',
  });

  // 입고대기: 발주완료 또는 배송중 상태
  const pendingList = purchaseOrders.filter(po =>
    po.status === '발주완료' || po.status === '배송중'
  );

  // 입고완료
  const receivedList = purchaseOrders.filter(po =>
    po.status === '입고완료' || po.status === '검사대기' || po.status === '검사완료'
  );

  // 금일 입고
  const todayReceived = receivedList.filter(po =>
    po.receivedDate === new Date().toISOString().split('T')[0]
  ).length;

  // 탭별 카운트
  const getStatusCount = (status) => {
    if (status === 'all') return purchaseOrders.length;
    if (status === 'pending') return pendingList.length;
    if (status === 'received') return receivedList.length;
    return 0;
  };

  // 탭 구성
  const tabs = [
    { id: 'all', label: '전체', count: getStatusCount('all') },
    { id: 'pending', label: '입고대기', count: getStatusCount('pending') },
    { id: 'received', label: '입고완료', count: getStatusCount('received') },
  ];

  // 필터링 로직
  const statusFilter = {
    all: () => true,
    pending: (po) => po.status === '발주완료' || po.status === '배송중',
    received: (po) => po.status === '입고완료' || po.status === '검사대기' || po.status === '검사완료',
  };

  const filteredList = purchaseOrders
    .filter(statusFilter[activeTab])
    .filter(po => {
      if (!search) return true;
      return (
        po.poNo?.toLowerCase().includes(search.toLowerCase()) ||
        po.materialCode?.toLowerCase().includes(search.toLowerCase()) ||
        po.materialName?.toLowerCase().includes(search.toLowerCase()) ||
        po.vendor?.toLowerCase().includes(search.toLowerCase())
      );
    })
    .sort((a, b) => b.id - a.id); // ID 기준 내림차순 (최신 등록 최상단)

  // 전체 선택/해제
  const handleSelectAll = (e) => {
    if (e.target.checked) {
      setSelectedIds(filteredList.map(po => po.id));
    } else {
      setSelectedIds([]);
    }
  };

  // 개별 선택
  const handleSelectOne = (id, e) => {
    e.stopPropagation();
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  };

  // 선택 초기화
  const clearSelection = () => setSelectedIds([]);

  // 선택 상태 확인
  const isSelected = (id) => selectedIds.includes(id);
  const hasSelection = selectedIds.length > 0;
  const isMultiSelect = selectedIds.length >= 2;
  const isAllSelected = filteredList.length > 0 && selectedIds.length === filteredList.length;

  const handleOpenReceive = (po) => {
    setSelectedPO(po);
    const today = new Date();
    const dateStr = today.toISOString().slice(2, 10).replace(/-/g, '');
    const seq = String(Math.floor(Math.random() * 99) + 1).padStart(2, '0');
    setReceiveForm({
      receivedQty: po.requestQty,
      incomingLot: `${dateStr}-${seq}`,
      supplierLot: '',
      location: '',
      note: '',
    });
    setShowReceiveModal(true);
  };

  const handleReceive = () => {
    if (!receiveForm.receivedQty || !receiveForm.location) {
      alert('입고수량과 입고위치를 입력해주세요.');
      return;
    }

    const receiveData = {
      ...selectedPO,
      status: '검사대기',
      receivedQty: Number(receiveForm.receivedQty),
      incomingLot: receiveForm.incomingLot,
      supplierLot: receiveForm.supplierLot,
      location: receiveForm.location,
      receivedDate: new Date().toISOString().split('T')[0],
      note: receiveForm.note,
    };

    onReceive?.(receiveData);
    setShowReceiveModal(false);
    setSelectedPO(null);
    alert(`✅ 입고 처리되었습니다.\n\n입고LOT: ${receiveForm.incomingLot}\n수입검사가 필요합니다.`);
  };

  const getStatusBadge = (status) => {
    const styles = {
      '발주완료': 'bg-blue-100 text-blue-700',
      '배송중': 'bg-purple-100 text-purple-700',
      '입고완료': 'bg-green-100 text-green-700',
      '검사대기': 'bg-yellow-100 text-yellow-700',
      '검사완료': 'bg-green-100 text-green-700',
      '부분입고': 'bg-orange-100 text-orange-700',
    };
    return styles[status] || 'bg-gray-100 text-gray-700';
  };

  // 삭제 확인
  const handleDeleteConfirm = () => {
    // 삭제 로직 구현
    setSelectedIds([]);
    setShowDeleteModal(false);
    alert('선택한 입고 내역이 삭제되었습니다.');
  };

  return (
    <div className="space-y-6">
      {/* 헤더 - 타이틀/버튼 분리 */}
      <div className="space-y-3">
        {/* 타이틀 영역 */}
        <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
          <Download className="w-6 h-6 text-blue-500" />
          입고 목록
        </h1>
      </div>

      {/* 리포트 카드 - 4개 한 줄 */}
      <div className="grid grid-cols-4 gap-4">
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">입고대기</p>
          <p className="text-2xl font-bold">{pendingList.length}건</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">배송중</p>
          <p className="text-2xl font-bold">{purchaseOrders.filter(po => po.status === '배송중').length}건</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">검사대기</p>
          <p className="text-2xl font-bold">{purchaseOrders.filter(po => po.status === '검사대기').length}건</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">금일입고</p>
          <p className="text-2xl font-bold">{todayReceived}건</p>
        </div>
      </div>

      {/* 검색바 (전체 너비) */}
      <div className="mb-6">
        <div className="relative">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder="발주번호, 품목코드, 품목명, 공급업체 검색..."
            className="w-full pl-12 pr-4 py-3 border rounded-xl"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
      </div>

      {/* 탭 (칩 형태) + 선택 삭제 버튼 */}
      <div className="flex items-center justify-between">
        <div className="flex gap-2">
          {tabs.map(tab => (
            <button
              key={tab.id}
              onClick={() => { setActiveTab(tab.id); clearSelection(); }}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${activeTab === tab.id
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
            >
              {tab.label} ({tab.count})
            </button>
          ))}
        </div>
        {isMultiSelect && (
          <button
            onClick={() => setShowDeleteModal(true)}
            className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 flex items-center gap-1"
          >
            <Trash2 className="w-4 h-4" />
            선택 삭제 ({selectedIds.length})
          </button>
        )}
      </div>

      {/* 테이블 */}
      <div className="bg-white rounded-lg shadow-sm border">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-center w-10">
                  <input
                    type="checkbox"
                    checked={isAllSelected}
                    onChange={handleSelectAll}
                    className="rounded border-gray-300"
                  />
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">발주번호</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목코드</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">공급업체</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">발주수량</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">입고수량</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">LOT번호</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
                {hasSelection && (
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
                )}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {filteredList.length === 0 ? (
                <tr>
                  <td colSpan={hasSelection ? 10 : 9} className="px-4 py-8 text-center text-gray-500">
                    해당 조건의 입고 내역이 없습니다.
                  </td>
                </tr>
              ) : (
                filteredList.map(po => {
                  const selected = isSelected(po.id);
                  return (
                    <tr
                      key={po.id}
                      className={`hover:bg-gray-50 cursor-pointer ${selected ? 'bg-blue-50' : ''}`}
                      onClick={() => onNavigate?.('inbound-detail', po)}
                    >
                      <td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                        <input
                          type="checkbox"
                          checked={selected}
                          onChange={(e) => handleSelectOne(po.id, e)}
                          className="rounded border-gray-300"
                        />
                      </td>
                      <td className="px-4 py-3 text-sm font-mono text-blue-600 font-medium">{po.poNo}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{po.materialCode}</td>
                      <td className="px-4 py-3 text-sm text-gray-900">{po.materialName}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{po.vendor}</td>
                      <td className="px-4 py-3 text-sm text-right">{po.requestQty} {po.unit}</td>
                      <td className="px-4 py-3 text-sm text-right font-medium">
                        {po.receivedQty ? `${po.receivedQty} ${po.unit}` : '-'}
                      </td>
                      <td className="px-4 py-3 text-sm text-center font-mono">
                        {po.inspectionLot || po.incomingLot || '-'}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusBadge(po.status)}`}>
                          {po.status}
                        </span>
                      </td>
                      {hasSelection && (
                        <td className="px-4 py-3 text-center">
                          {selected && (
                            <div className="flex items-center justify-center gap-1">
                              {(po.status === '발주완료' || po.status === '배송중') && (
                                <button
                                  onClick={() => handleOpenReceive(po)}
                                  className="px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600"
                                >
                                  입고처리
                                </button>
                              )}
                              {(po.status === '입고완료' || po.status === '검사대기' || po.status === '검사완료') && (
                                <button
                                  onClick={() => {
                                    setSlipData(po);
                                    setShowInboundSlip(true);
                                  }}
                                  className="px-2 py-1 bg-gray-600 text-white text-xs rounded hover:bg-gray-700 flex items-center gap-1"
                                >
                                  <Printer className="w-3 h-3" />
                                  입고증
                                </button>
                              )}
                              {po.status === '검사대기' && (
                                <button
                                  onClick={() => onNavigate?.('iqc-register', po)}
                                  className="px-2 py-1 bg-green-500 text-white text-xs rounded hover:bg-green-600"
                                >
                                  검사등록
                                </button>
                              )}
                              <button
                                onClick={() => setShowDeleteModal(true)}
                                className="p-1 text-red-600 hover:bg-red-50 rounded"
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </div>
                          )}
                        </td>
                      )}
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* 요약 */}
        {filteredList.length > 0 && (
          <div className="px-4 py-3 bg-gray-50 border-t text-sm text-gray-600">
            총 <span className="font-medium">{filteredList.length}</span>건 /
            입고대기 <span className="font-medium text-blue-600">{pendingList.length}</span>건 /
            검사대기 <span className="font-medium text-yellow-600">{purchaseOrders.filter(po => po.status === '검사대기').length}</span>건
          </div>
        )}
      </div>

      {/* 입고 처리 모달 */}
      {showReceiveModal && selectedPO && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b flex justify-between items-center sticky top-0 bg-white z-10">
              <h3 className="text-lg font-bold">입고 처리</h3>
              <button onClick={() => setShowReceiveModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6 space-y-4">
              {/* 발주 정보 */}
              <div className="bg-gray-50 rounded-lg p-4">
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-gray-500">발주번호:</span>
                    <span className="ml-2 font-medium">{selectedPO.poNo}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">공급업체:</span>
                    <span className="ml-2">{selectedPO.vendor}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">품목:</span>
                    <span className="ml-2">{selectedPO.materialName}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">발주수량:</span>
                    <span className="ml-2 font-medium">{selectedPO.requestQty} {selectedPO.unit}</span>
                  </div>
                </div>
              </div>

              {/* 입고 정보 입력 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    입고LOT <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={receiveForm.incomingLot}
                    onChange={(e) => setReceiveForm(prev => ({ ...prev, incomingLot: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg text-sm bg-gray-100"
                    readOnly
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">공급업체LOT</label>
                  <input
                    type="text"
                    value={receiveForm.supplierLot}
                    onChange={(e) => setReceiveForm(prev => ({ ...prev, supplierLot: e.target.value }))}
                    placeholder="예: 2402944"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    입고수량 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="number"
                    value={receiveForm.receivedQty}
                    onChange={(e) => setReceiveForm(prev => ({ ...prev, receivedQty: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    입고위치 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={receiveForm.location}
                    onChange={(e) => setReceiveForm(prev => ({ ...prev, location: e.target.value }))}
                    placeholder="예: A-01"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <textarea
                  value={receiveForm.note}
                  onChange={(e) => setReceiveForm(prev => ({ ...prev, note: e.target.value }))}
                  rows={2}
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
            </div>
            <div className="p-4 border-t flex justify-end gap-2">
              <button
                onClick={() => setShowReceiveModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleReceive}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
              >
                입고 처리
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 입고증 다이얼로그 */}
      {showInboundSlip && slipData && (
        <InboundSlipDialog
          inbound={slipData}
          onClose={() => {
            setShowInboundSlip(false);
            setSlipData(null);
          }}
        />
      )}

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
            <h3 className="text-lg font-bold mb-4">입고 내역 삭제</h3>
            <p className="text-gray-600 mb-6">
              선택한 {selectedIds.length}개의 입고 내역을 삭제하시겠습니까?
              <br />
              <span className="text-red-600 text-sm">이 작업은 되돌릴 수 없습니다.</span>
            </p>
            <div className="flex justify-end gap-2">
              <button
                onClick={() => setShowDeleteModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleDeleteConfirm}
                className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
              >
                삭제
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============================================================
// 입고 상세페이지 컴포넌트
// ============================================================
const InboundDetail = ({ inbound, onNavigate, onReceive, onUpdateStatus }) => {
  const [showReceiveModal, setShowReceiveModal] = useState(false);
  const [showInboundSlip, setShowInboundSlip] = useState(false);
  const [receiveForm, setReceiveForm] = useState({
    receivedQty: '',
    incomingLot: '',
    supplierLot: '',
    location: '',
    note: '',
  });

  // 입고 처리 모달 열기
  const handleOpenReceive = () => {
    const today = new Date();
    const dateStr = today.toISOString().slice(2, 10).replace(/-/g, '');
    const seq = String(Math.floor(Math.random() * 99) + 1).padStart(2, '0');
    setReceiveForm({
      receivedQty: inbound.requestQty,
      incomingLot: `${dateStr}-${seq}`,
      supplierLot: '',
      location: '',
      note: '',
    });
    setShowReceiveModal(true);
  };

  // 입고 처리 실행
  const handleReceive = () => {
    if (!receiveForm.receivedQty || !receiveForm.location) {
      alert('입고수량과 입고위치를 입력해주세요.');
      return;
    }

    const receiveData = {
      ...inbound,
      status: '검사대기',
      receivedQty: Number(receiveForm.receivedQty),
      incomingLot: receiveForm.incomingLot,
      supplierLot: receiveForm.supplierLot,
      location: receiveForm.location,
      receivedDate: new Date().toISOString().split('T')[0],
      note: receiveForm.note,
    };

    onReceive?.(receiveData);
    setShowReceiveModal(false);
    alert(`✅ 입고 처리되었습니다.\n\n입고LOT: ${receiveForm.incomingLot}\n수입검사가 필요합니다.`);
  };

  const getStatusBadge = (status) => {
    const styles = {
      '발주완료': 'bg-blue-100 text-blue-700',
      '배송중': 'bg-purple-100 text-purple-700',
      '입고완료': 'bg-green-100 text-green-700',
      '검사대기': 'bg-yellow-100 text-yellow-700',
      '검사완료': 'bg-green-100 text-green-700',
    };
    return styles[status] || 'bg-gray-100 text-gray-700';
  };

  return (
    <div className="space-y-6">
      {/* 헤더 - 타이틀/버튼 분리 */}
      <div className="space-y-3">
        {/* 타이틀 영역 */}
        <div className="flex items-center gap-4">
          <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
            <Package className="w-6 h-6 text-blue-500" />
            입고 상세
          </h1>
          <div className="flex items-center gap-2 text-sm text-gray-500">
            <span className="font-mono">{inbound.poNo}</span>
            <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusBadge(inbound.status)}`}>
              {inbound.status}
            </span>
          </div>
        </div>

        {/* 버튼 영역 - 좌측:문서버튼 / 우측:액션버튼 */}
        <div className="flex items-center justify-between">
          {/* 좌측: 문서 버튼 */}
          <div className="flex items-center gap-2">
            {(inbound.status === '입고완료' || inbound.status === '검사대기' || inbound.status === '검사완료') && (
              <button
                onClick={() => setShowInboundSlip(true)}
                className="flex items-center gap-1 px-3 py-1.5 text-sm border rounded hover:bg-gray-50"
              >
                <Printer className="w-4 h-4" />
                입고증
              </button>
            )}
          </div>

          {/* 우측: 액션 버튼 */}
          <div className="flex items-center gap-2">
            <button
              onClick={() => onNavigate?.('inbound-list')}
              className="flex items-center gap-1 px-4 py-2 border rounded hover:bg-gray-50"
            >
              목록
            </button>
            {(inbound.status === '발주완료' || inbound.status === '배송중') && (
              <button
                onClick={handleOpenReceive}
                className="flex items-center gap-1 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
              >
                <Download className="w-4 h-4" />
                입고처리
              </button>
            )}
            {inbound.status === '검사대기' && (
              <button
                onClick={() => onNavigate?.('iqc-register', inbound)}
                className="flex items-center gap-1 px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
              >
                <ClipboardList className="w-4 h-4" />
                검사등록
              </button>
            )}
          </div>
        </div>
      </div>

      {/* 발주 정보 */}
      <Card title="발주 정보">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div>
            <p className="text-sm text-gray-500 mb-1">발주번호</p>
            <p className="font-mono font-medium">{inbound.poNo}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">발주일자</p>
            <p className="font-medium">{inbound.poDate || '-'}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">공급업체</p>
            <p className="font-medium">{inbound.vendor}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">품목코드</p>
            <p className="font-mono">{inbound.materialCode}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">품목명</p>
            <p className="font-medium">{inbound.materialName}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">규격</p>
            <p>{inbound.spec || '-'}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">발주수량</p>
            <p className="font-bold text-blue-600">{inbound.requestQty} {inbound.unit}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">납기일</p>
            <p>{inbound.dueDate || '-'}</p>
          </div>
        </div>
      </Card>

      {/* 입고 정보 (입고 처리 후 표시) */}
      {(inbound.status === '입고완료' || inbound.status === '검사대기' || inbound.status === '검사완료') && (
        <Card title="입고 정보">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div>
              <p className="text-sm text-gray-500 mb-1">입고일자</p>
              <p className="font-medium">{inbound.receivedDate}</p>
            </div>
            <div>
              <p className="text-sm text-gray-500 mb-1">입고수량</p>
              <p className="font-bold text-green-600">{inbound.receivedQty} {inbound.unit}</p>
            </div>
            <div>
              <p className="text-sm text-gray-500 mb-1">입고LOT</p>
              <p className="font-mono text-blue-600">{inbound.incomingLot}</p>
            </div>
            <div>
              <p className="text-sm text-gray-500 mb-1">공급업체LOT</p>
              <p className="font-mono">{inbound.supplierLot || '-'}</p>
            </div>
            <div>
              <p className="text-sm text-gray-500 mb-1">입고위치</p>
              <p className="font-medium">{inbound.location}</p>
            </div>
            <div>
              <p className="text-sm text-gray-500 mb-1">입고담당</p>
              <p>{inbound.receiver || '자재팀'}</p>
            </div>
          </div>
          {inbound.note && (
            <div className="mt-4">
              <p className="text-sm text-gray-500 mb-1">비고</p>
              <p className="text-gray-700">{inbound.note}</p>
            </div>
          )}
        </Card>
      )}

      {/* 검사 정보 (검사 완료 후 표시) */}
      {inbound.status === '입고완료' && inbound.inspectionResult && (
        <Card title="검사 정보">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div>
              <p className="text-sm text-gray-500 mb-1">검사일자</p>
              <p className="font-medium">{inbound.inspectionResult.inspectionDate}</p>
            </div>
            <div>
              <p className="text-sm text-gray-500 mb-1">검사LOT</p>
              <p className="font-mono text-blue-600 font-bold">{inbound.inspectionLot}</p>
            </div>
            <div>
              <p className="text-sm text-gray-500 mb-1">검사결과</p>
              <p className={`font-bold ${inbound.inspectionResult.result === '합격' ? 'text-green-600' : 'text-red-600'}`}>
                {inbound.inspectionResult.result}
              </p>
            </div>
            <div>
              <p className="text-sm text-gray-500 mb-1">검사자</p>
              <p>{inbound.inspectionResult.inspector}</p>
            </div>
          </div>
        </Card>
      )}

      {/* 입고 처리 모달 */}
      {showReceiveModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b flex justify-between items-center sticky top-0 bg-white z-10">
              <h3 className="text-lg font-bold">입고 처리</h3>
              <button onClick={() => setShowReceiveModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6 space-y-4">
              {/* 발주 정보 */}
              <div className="bg-gray-50 rounded-lg p-4">
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-gray-500">발주번호:</span>
                    <span className="ml-2 font-medium">{inbound.poNo}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">공급업체:</span>
                    <span className="ml-2">{inbound.vendor}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">품목:</span>
                    <span className="ml-2">{inbound.materialName}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">발주수량:</span>
                    <span className="ml-2 font-medium">{inbound.requestQty} {inbound.unit}</span>
                  </div>
                </div>
              </div>

              {/* 입고 정보 입력 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    입고LOT <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={receiveForm.incomingLot}
                    className="w-full px-3 py-2 border rounded-lg text-sm bg-gray-100"
                    readOnly
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">공급업체LOT</label>
                  <input
                    type="text"
                    value={receiveForm.supplierLot}
                    onChange={(e) => setReceiveForm(prev => ({ ...prev, supplierLot: e.target.value }))}
                    placeholder="예: 2402944"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    입고수량 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="number"
                    value={receiveForm.receivedQty}
                    onChange={(e) => setReceiveForm(prev => ({ ...prev, receivedQty: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    입고위치 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={receiveForm.location}
                    onChange={(e) => setReceiveForm(prev => ({ ...prev, location: e.target.value }))}
                    placeholder="예: A-01"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <textarea
                  value={receiveForm.note}
                  onChange={(e) => setReceiveForm(prev => ({ ...prev, note: e.target.value }))}
                  rows={2}
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
            </div>
            <div className="p-4 border-t flex justify-end gap-2">
              <button
                onClick={() => setShowReceiveModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleReceive}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
              >
                입고 처리
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 입고증 다이얼로그 */}
      {showInboundSlip && (
        <InboundSlipDialog
          inbound={inbound}
          onClose={() => setShowInboundSlip(false)}
        />
      )}
    </div>
  );
};

// ============================================================
// 통합 검사 등록 폼 (검사 유형 선택 - 드롭다운)
// ============================================================
const InspectionRegisterForm = ({
  purchaseOrders = [],
  workOrders = [],
  shipments = [],
  onNavigate,
  onSave,
}) => {
  const [inspectionType, setInspectionType] = useState('IQC');
  const [selectedTarget, setSelectedTarget] = useState(null);
  const [templateType, setTemplateType] = useState('EGI'); // 템플릿 유형 (EGI, SCREEN 등)
  const [inspectionForm, setInspectionForm] = useState({
    inspectorName: '',
    inspectionDate: new Date().toISOString().split('T')[0],
    processStep: '', // PQC용
    inspectionItems: [],
    note: '',
  });

  // 검사 템플릿 불러오기 (품질기준관리 연동)
  const loadInspectionTemplate = (type, subType) => {
    const config = masterConfigs['quality'];
    const templates = config?.inspectionItemTemplates?.[type]?.[subType];

    if (!templates) {
      // 템플릿이 없는 경우 기본 항목
      return [
        { item: '겉모양', standard: '사용상 해로운 결함이 없을 것', method: '육안검사', result: '적', note: '' },
        { item: '두께', standard: '규격 참조', method: '마이크로미터', result: '적', note: '' },
        { item: '폭', standard: '규격 참조', method: '줄자', result: '적', note: '' },
        { item: '길이', standard: '규격 참조', method: '줄자', result: '적', note: '' },
      ];
    }

    // 배열 형태 템플릿 처리 (IQC, FQC)
    if (Array.isArray(templates)) {
      return templates.map(template => ({
        item: template.item,
        standard: template.standard,
        method: template.method,
        result: '적',
        note: '',
      }));
    }

    // 객체 형태 템플릿 처리 (PQC - 상세 구조)
    if (templates.inspectionStandard) {
      const items = [];

      // sections 항목 추가 (가공상태, 재봉상태 등)
      if (templates.inspectionStandard.sections) {
        templates.inspectionStandard.sections.forEach(section => {
          items.push({
            category: section.category,
            item: section.name,
            standard: section.standard,
            method: section.method,
            judgementType: section.judgementType,
            relatedStandard: section.relatedStandard,
            result: '적',
            note: '',
          });
        });
      }

      // measurements 항목 추가 (치수 측정)
      if (templates.inspectionStandard.measurements) {
        templates.inspectionStandard.measurements.forEach(measurement => {
          items.push({
            category: measurement.category,
            item: measurement.item,
            point: measurement.point,
            standard: measurement.standard,
            method: measurement.method,
            unit: measurement.unit,
            relatedStandard: measurement.relatedStandard,
            result: '',
            measurementValue: '', // 측정값 입력 필드
            note: '',
          });
        });
      }

      return items;
    }

    // 기본 배열 변환
    return [];
  };

  // 검사 유형 또는 템플릿 유형 변경 시 검사 항목 갱신
  React.useEffect(() => {
    const items = loadInspectionTemplate(inspectionType, templateType);
    setInspectionForm(prev => ({ ...prev, inspectionItems: Array.isArray(items) ? items : [] }));
  }, [inspectionType, templateType]);

  // 검사 유형별 대상 목록
  const getTargetList = () => {
    if (inspectionType === 'IQC') {
      return purchaseOrders.filter(po => po.status === '검사대기' || po.status === '입고대기');
    } else if (inspectionType === 'PQC') {
      return workOrders.filter(wo => wo.status === '작업중');
    } else if (inspectionType === 'FQC') {
      return workOrders.filter(wo => wo.status === '작업완료' && wo.inspectionStatus !== '검사완료');
    }
    return [];
  };

  const targetList = getTargetList();

  const handleSubmit = () => {
    if (!selectedTarget) {
      alert('검사 대상을 선택해주세요.');
      return;
    }
    if (!inspectionForm.inspectorName) {
      alert('검사자를 입력해주세요.');
      return;
    }

    const hasFailure = (inspectionForm.inspectionItems || []).some(item => item.result === '부');
    const lotNo = `LOT-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}-${String(Math.floor(Math.random() * 999) + 1).padStart(3, '0')}`;

    // 공정명 매핑 (템플릿 타입 → 공정명)
    const processNameMap = {
      'SCREEN': '스크린',
      'SLAT': '슬랫',
      'FOLD': '절곡',
      'STOCK': '재고',
      'PACK': '포장',
    };

    const inspectionData = {
      type: inspectionType === 'IQC' ? 'incoming' : inspectionType === 'PQC' ? 'process' : 'final',
      targetNo: selectedTarget.poNo || selectedTarget.woNo || selectedTarget.id,
      targetType: inspectionType,
      lotNo: lotNo,
      itemName: selectedTarget.itemName || selectedTarget.productName,
      qty: selectedTarget.qty || selectedTarget.orderQty,
      inspector: inspectionForm.inspectorName,
      inspectionDate: inspectionForm.inspectionDate,
      processStep: inspectionType === 'PQC' ? processNameMap[templateType] || templateType : '',
      processCode: inspectionType === 'PQC' ? templateType : '',
      result: hasFailure ? '불합격' : '합격',
      inspectionItems: inspectionForm.inspectionItems,
      note: inspectionForm.note,
    };

    onSave?.(inspectionData);
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <ShieldCheck className="w-6 h-6 text-blue-500" />
          검사 등록
        </h1>
        <div className="flex items-center justify-end gap-2">
          <button
            onClick={() => onNavigate?.('inspection-list')}
            className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            취소
          </button>
          <button
            onClick={handleSubmit}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-1"
          >
            <Save className="w-4 h-4" />
            검사 저장
          </button>
        </div>
      </div>

      {/* 검사 기본 정보 */}
      <div className="bg-white rounded-xl border p-6">
        <h2 className="font-bold text-lg mb-4">검사 기본 정보</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {/* 검사 유형 선택 */}
          <div>
            <label className="block text-sm font-medium mb-1">검사 유형</label>
            <select
              value={inspectionType}
              onChange={(e) => {
                setInspectionType(e.target.value);
                setSelectedTarget(null); // 유형 변경 시 선택 초기화
                // 유형별 기본 템플릿 설정
                if (e.target.value === 'IQC') setTemplateType('EGI');
                if (e.target.value === 'PQC') setTemplateType('SCREEN');
                if (e.target.value === 'FQC') setTemplateType('SCREEN_SHUTTER');
              }}
              className="w-full px-3 py-2 border rounded-lg"
            >
              <option value="IQC">수입검사 (IQC) - 자재 입고 시 검사</option>
              <option value="PQC">중간검사 (PQC) - 생산 중 품질검사</option>
              <option value="FQC">제품검사 (FQC) - 출하 후 고객요청 검사</option>
            </select>
          </div>

          {/* 검사 템플릿 선택 */}
          <div>
            <label className="block text-sm font-medium mb-1">검사 템플릿</label>
            <select
              value={templateType}
              onChange={(e) => setTemplateType(e.target.value)}
              className="w-full px-3 py-2 border rounded-lg"
            >
              {inspectionType === 'IQC' && (
                <>
                  <option value="EGI">EGI 철판 (전기아연도금강판)</option>
                  <option value="GI">GI 철판 (용융아연도금강판)</option>
                  <option value="CR">CR 철판 (냉간압연강판)</option>
                  <option value="STS">STS 스테인리스강판</option>
                  <option value="AL">AL 알루미늄판</option>
                </>
              )}
              {inspectionType === 'PQC' && (
                <>
                  <option value="SCREEN">스크린 공정</option>
                  <option value="SLAT">슬랫 공정</option>
                  <option value="FOLD">절곡 공정</option>
                  <option value="STOCK">재고 공정</option>
                  <option value="PACK">포장 공정</option>
                </>
              )}
              {inspectionType === 'FQC' && (
                <>
                  <option value="SCREEN_SHUTTER">스크린 셔터</option>
                  <option value="STEEL_SHUTTER">철재 셔터</option>
                  <option value="FIRE_DOOR">방화문</option>
                </>
              )}
            </select>
          </div>

          {/* 검사 대상 선택 */}
          <div>
            <label className="block text-sm font-medium mb-1">검사 대상</label>
            <select
              value={selectedTarget?.id || ''}
              onChange={(e) => {
                const target = targetList.find(t => String(t.id) === e.target.value);
                setSelectedTarget(target);
              }}
              className="w-full px-3 py-2 border rounded-lg"
            >
              <option value="">선택하세요</option>
              {targetList.map(target => (
                <option key={target.id} value={target.id}>
                  {target.poNo || target.woNo || target.id} - {target.itemName || target.productName}
                </option>
              ))}
            </select>
          </div>

          {/* 검사일자 */}
          <div>
            <label className="block text-sm font-medium mb-1">검사일자</label>
            <input
              type="date"
              value={inspectionForm.inspectionDate}
              onChange={(e) => setInspectionForm(prev => ({ ...prev, inspectionDate: e.target.value }))}
              className="w-full px-3 py-2 border rounded-lg"
            />
          </div>


          {/* 검사자 */}
          <div>
            <label className="block text-sm font-medium mb-1">검사자</label>
            <input
              type="text"
              value={inspectionForm.inspectorName}
              onChange={(e) => setInspectionForm(prev => ({ ...prev, inspectorName: e.target.value }))}
              placeholder="검사자 이름"
              className="w-full px-3 py-2 border rounded-lg"
            />
          </div>
        </div>
      </div>

      {/* 검사 항목 */}
      <div className="bg-white rounded-xl border p-6">
        <h2 className="font-bold text-lg mb-4">검사 항목</h2>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-2 text-left text-sm font-medium">검사항목</th>
                <th className="px-4 py-2 text-left text-sm font-medium">판정기준</th>
                <th className="px-4 py-2 text-left text-sm font-medium">검사방법</th>
                <th className="px-4 py-2 text-left text-sm font-medium">판정</th>
                <th className="px-4 py-2 text-left text-sm font-medium">비고</th>
              </tr>
            </thead>
            <tbody>
              {(inspectionForm.inspectionItems || []).map((item, idx) => (
                <tr key={idx} className="border-t">
                  <td className="px-4 py-2">
                    <input
                      type="text"
                      value={item.item}
                      onChange={(e) => {
                        const newItems = [...inspectionForm.inspectionItems];
                        newItems[idx].item = e.target.value;
                        setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                      }}
                      className="w-full px-2 py-1 border rounded"
                    />
                  </td>
                  <td className="px-4 py-2">
                    <input
                      type="text"
                      value={item.standard}
                      onChange={(e) => {
                        const newItems = [...inspectionForm.inspectionItems];
                        newItems[idx].standard = e.target.value;
                        setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                      }}
                      className="w-full px-2 py-1 border rounded"
                    />
                  </td>
                  <td className="px-4 py-2">
                    <input
                      type="text"
                      value={item.method}
                      onChange={(e) => {
                        const newItems = [...inspectionForm.inspectionItems];
                        newItems[idx].method = e.target.value;
                        setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                      }}
                      className="w-full px-2 py-1 border rounded"
                    />
                  </td>
                  <td className="px-4 py-2">
                    <select
                      value={item.result}
                      onChange={(e) => {
                        const newItems = [...inspectionForm.inspectionItems];
                        newItems[idx].result = e.target.value;
                        setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                      }}
                      className="w-full px-2 py-1 border rounded"
                    >
                      <option value="적">적</option>
                      <option value="부">부</option>
                    </select>
                  </td>
                  <td className="px-4 py-2">
                    <input
                      type="text"
                      value={item.note}
                      onChange={(e) => {
                        const newItems = [...inspectionForm.inspectionItems];
                        newItems[idx].note = e.target.value;
                        setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                      }}
                      className="w-full px-2 py-1 border rounded"
                      placeholder="비고"
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <button
          onClick={() => {
            setInspectionForm(prev => ({
              ...prev,
              inspectionItems: [...(prev.inspectionItems || []), { item: '', standard: '', method: '', result: '적', note: '' }]
            }));
          }}
          className="mt-4 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 flex items-center gap-1"
        >
          <Plus className="w-4 h-4" />
          항목 추가
        </button>
      </div>

      {/* 비고 */}
      <div className="bg-white rounded-xl border p-6">
        <h2 className="font-bold text-lg mb-4">비고</h2>
        <textarea
          value={inspectionForm.note}
          onChange={(e) => setInspectionForm(prev => ({ ...prev, note: e.target.value }))}
          placeholder="특이사항을 입력하세요"
          className="w-full px-3 py-2 border rounded-lg"
          rows={3}
        />
      </div>
    </div>
  );
};

// ============================================================
// 검사 성적서 문서 출력 컴포넌트
// ============================================================
const InspectionCertificateDocument = ({ inspectionData, onClose }) => {
  const handlePrint = () => {
    window.print();
  };

  // 템플릿 정보 가져오기
  const getTemplateInfo = () => {
    if (inspectionData.type === 'process' && inspectionData.processCode) {
      const config = masterConfigs['quality'];
      return config?.inspectionItemTemplates?.PQC?.[inspectionData.processCode];
    }
    return null;
  };

  const templateInfo = getTemplateInfo();

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-6xl w-full max-h-[90vh] overflow-y-auto">
        {/* 헤더 - 인쇄 시 숨김 */}
        <div className="sticky top-0 bg-white border-b px-6 py-4 flex items-center justify-between print:hidden">
          <h2 className="text-xl font-bold">검사 성적서</h2>
          <div className="flex gap-2">
            <button
              onClick={handlePrint}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
            >
              <Printer className="w-4 h-4" />
              인쇄
            </button>
            <button
              onClick={onClose}
              className="px-4 py-2 border rounded-lg hover:bg-gray-50"
            >
              닫기
            </button>
          </div>
        </div>

        {/* 문서 본문 */}
        <div className="p-8 print:p-6">
          {/* 문서 제목 */}
          <div className="text-center mb-8">
            <h1 className="text-2xl font-bold mb-2">
              {templateInfo?.templateName || '검사 성적서'}
            </h1>
            <p className="text-sm text-gray-600">
              {inspectionData.type === 'incoming' && '(수입검사 - IQC)'}
              {inspectionData.type === 'process' && '(중간검사 - PQC)'}
              {inspectionData.type === 'final' && '(제품검사 - FQC)'}
            </p>
          </div>

          {/* 기본 정보 */}
          <div className="mb-6 border rounded-lg overflow-hidden">
            <table className="w-full text-sm">
              <tbody>
                <tr className="border-b">
                  <td className="bg-gray-50 px-4 py-2 font-medium w-32">검사번호</td>
                  <td className="px-4 py-2">{inspectionData.id || '-'}</td>
                  <td className="bg-gray-50 px-4 py-2 font-medium w-32">검사일자</td>
                  <td className="px-4 py-2">{inspectionData.inspectionDate}</td>
                </tr>
                <tr className="border-b">
                  <td className="bg-gray-50 px-4 py-2 font-medium">대상번호</td>
                  <td className="px-4 py-2">{inspectionData.targetNo}</td>
                  <td className="bg-gray-50 px-4 py-2 font-medium">검사자</td>
                  <td className="px-4 py-2">{inspectionData.inspector}</td>
                </tr>
                <tr className="border-b">
                  <td className="bg-gray-50 px-4 py-2 font-medium">품목명</td>
                  <td className="px-4 py-2">{inspectionData.itemName}</td>
                  <td className="bg-gray-50 px-4 py-2 font-medium">수량</td>
                  <td className="px-4 py-2">{inspectionData.qty}</td>
                </tr>
                {inspectionData.processStep && (
                  <tr className="border-b">
                    <td className="bg-gray-50 px-4 py-2 font-medium">공정명</td>
                    <td className="px-4 py-2">{inspectionData.processStep}</td>
                    <td className="bg-gray-50 px-4 py-2 font-medium">검사시점</td>
                    <td className="px-4 py-2">{templateInfo?.checkPoint || '-'}</td>
                  </tr>
                )}
                <tr>
                  <td className="bg-gray-50 px-4 py-2 font-medium">LOT번호</td>
                  <td className="px-4 py-2">{inspectionData.lotNo}</td>
                  <td className="bg-gray-50 px-4 py-2 font-medium">판정결과</td>
                  <td className="px-4 py-2">
                    <span className={`font-bold ${inspectionData.result === '합격' ? 'text-green-600' : 'text-red-600'}`}>
                      {inspectionData.result}
                    </span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 도면 다이어그램 (PQC용) */}
          {templateInfo?.diagram && (
            <div className="mb-6 p-4 border rounded-lg bg-gray-50">
              <h3 className="font-bold mb-2">측정 위치 도면</h3>
              <div className="flex items-center justify-center p-8 bg-white rounded border-2 border-dashed">
                <div className="text-center text-gray-500">
                  <p className="mb-2">측정 포인트: {templateInfo.diagram.measurements?.join(', ')}</p>
                  <p className="text-sm">[도면은 실제 제품 도면을 첨부하세요]</p>
                </div>
              </div>
            </div>
          )}

          {/* 검사 항목 테이블 */}
          <div className="mb-6">
            <h3 className="font-bold text-lg mb-3">검사 항목 및 결과</h3>

            {/* 상세 구조 템플릿 (PQC) */}
            {templateInfo?.inspectionStandard ? (
              <div className="space-y-6">
                {/* 결모양 검사 섹션 */}
                {templateInfo.inspectionStandard.sections && templateInfo.inspectionStandard.sections.length > 0 && (
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-gray-100 px-4 py-2 font-bold">결모양 검사</div>
                    <table className="w-full text-sm">
                      <thead className="bg-gray-50">
                        <tr>
                          <th className="px-4 py-2 text-left border-r">항목</th>
                          <th className="px-4 py-2 text-left border-r">판정기준</th>
                          <th className="px-4 py-2 text-left border-r">검사방법</th>
                          <th className="px-4 py-2 text-left border-r">관련규격</th>
                          <th className="px-4 py-2 text-center">판정</th>
                        </tr>
                      </thead>
                      <tbody>
                        {(inspectionData.inspectionItems || [])
                          .filter(item => item.category === '가공상태' || item.category === '재봉상태' || item.category === '조립상태')
                          .map((item, idx) => (
                            <tr key={idx} className="border-t">
                              <td className="px-4 py-2 border-r">{item.item}</td>
                              <td className="px-4 py-2 border-r">{item.standard}</td>
                              <td className="px-4 py-2 border-r">{item.method}</td>
                              <td className="px-4 py-2 border-r text-xs">{item.relatedStandard || '-'}</td>
                              <td className="px-4 py-2 text-center font-medium">
                                <span className={item.result === '적' ? 'text-green-600' : 'text-red-600'}>
                                  {item.result}
                                </span>
                              </td>
                            </tr>
                          ))}
                      </tbody>
                    </table>
                  </div>
                )}

                {/* 치수 검사 섹션 */}
                {templateInfo.inspectionStandard.measurements && templateInfo.inspectionStandard.measurements.length > 0 && (
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-gray-100 px-4 py-2 font-bold">치수 검사</div>
                    <table className="w-full text-sm">
                      <thead className="bg-gray-50">
                        <tr>
                          <th className="px-4 py-2 text-left border-r">측정위치</th>
                          <th className="px-4 py-2 text-left border-r">항목</th>
                          <th className="px-4 py-2 text-left border-r">기준치수</th>
                          <th className="px-4 py-2 text-left border-r">측정값</th>
                          <th className="px-4 py-2 text-left border-r">검사방법</th>
                          <th className="px-4 py-2 text-left border-r">관련규격</th>
                          <th className="px-4 py-2 text-center">판정</th>
                        </tr>
                      </thead>
                      <tbody>
                        {(inspectionData.inspectionItems || [])
                          .filter(item => item.category === '치수')
                          .map((item, idx) => (
                            <tr key={idx} className="border-t">
                              <td className="px-4 py-2 border-r text-center font-bold">{item.point}</td>
                              <td className="px-4 py-2 border-r">{item.item}</td>
                              <td className="px-4 py-2 border-r">{item.standard} {item.unit}</td>
                              <td className="px-4 py-2 border-r font-medium">{item.measurementValue || '-'} {item.unit}</td>
                              <td className="px-4 py-2 border-r">{item.method}</td>
                              <td className="px-4 py-2 border-r text-xs">{item.relatedStandard || '-'}</td>
                              <td className="px-4 py-2 text-center font-medium">
                                <span className={item.result === '적' ? 'text-green-600' : item.result === '부' ? 'text-red-600' : ''}>
                                  {item.result || '-'}
                                </span>
                              </td>
                            </tr>
                          ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            ) : (
              /* 기본 테이블 (IQC, FQC) */
              <div className="border rounded-lg overflow-hidden">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-2 text-left border-r">검사항목</th>
                      <th className="px-4 py-2 text-left border-r">판정기준</th>
                      <th className="px-4 py-2 text-left border-r">검사방법</th>
                      <th className="px-4 py-2 text-center border-r">판정</th>
                      <th className="px-4 py-2 text-left">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(inspectionData.inspectionItems || []).map((item, idx) => (
                      <tr key={idx} className="border-t">
                        <td className="px-4 py-2 border-r">{item.item}</td>
                        <td className="px-4 py-2 border-r">{item.standard}</td>
                        <td className="px-4 py-2 border-r">{item.method}</td>
                        <td className="px-4 py-2 text-center border-r font-medium">
                          <span className={item.result === '적' ? 'text-green-600' : 'text-red-600'}>
                            {item.result}
                          </span>
                        </td>
                        <td className="px-4 py-2">{item.note || '-'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {/* 비고 */}
          {inspectionData.note && (
            <div className="mb-6 p-4 border rounded-lg bg-gray-50">
              <h3 className="font-bold mb-2">비고</h3>
              <p className="text-sm whitespace-pre-wrap">{inspectionData.note}</p>
            </div>
          )}

          {/* 서명란 */}
          <div className="mt-8 pt-6 border-t">
            <div className="grid grid-cols-3 gap-8 text-center">
              <div>
                <div className="mb-8 text-sm text-gray-600">검사자</div>
                <div className="border-t pt-2 font-medium">{inspectionData.inspector}</div>
              </div>
              <div>
                <div className="mb-8 text-sm text-gray-600">확인자</div>
                <div className="border-t pt-2">(인)</div>
              </div>
              <div>
                <div className="mb-8 text-sm text-gray-600">승인자</div>
                <div className="border-t pt-2">(인)</div>
              </div>
            </div>
          </div>

          {/* 발행일 */}
          <div className="mt-6 text-center text-sm text-gray-600">
            <p>발행일: {new Date().toLocaleDateString('ko-KR')}</p>
          </div>
        </div>
      </div>

      {/* 인쇄 스타일 */}
      <style>{`
        @media print {
          body * {
            visibility: hidden;
          }
          .print\\:hidden {
            display: none !important;
          }
          .fixed.inset-0 {
            position: static;
            background: white;
          }
          .fixed.inset-0 * {
            visibility: visible;
          }
          .max-h-\\[90vh\\] {
            max-height: none;
          }
          .overflow-y-auto {
            overflow: visible;
          }
        }
      `}</style>
    </div>
  );
};

// ============================================================
// 재고 상세페이지 컴포넌트
// ============================================================
const StockDetail = ({ stock, inventory = [], onNavigate }) => {
  // 품목별 LOT 데이터 생성 (실제로는 서버에서 조회)
  const generateLots = () => {
    const today = new Date();
    const lots = [];
    const lotCount = Math.min(Math.ceil(stock.stock / 30), 5); // 최대 5개 LOT
    let remainingStock = stock.stock;

    for (let i = 0; i < lotCount && remainingStock > 0; i++) {
      const daysAgo = (lotCount - i) * 7 + Math.floor(Math.random() * 5);
      const inboundDate = new Date(today);
      inboundDate.setDate(inboundDate.getDate() - daysAgo);

      const qty = i === lotCount - 1 ? remainingStock : Math.floor(remainingStock / (lotCount - i) * (0.8 + Math.random() * 0.4));
      remainingStock -= qty;

      const suppliers = ['포스코', '현대제철', '동국제강', '세아제강', '한국철강'];
      const locations = ['A-01', 'A-02', 'B-01', 'B-02', 'C-01'];

      lots.push({
        id: `${stock.materialCode}-LOT-${i + 1}`,
        lotNo: `${inboundDate.toISOString().slice(2, 10).replace(/-/g, '')}-${String(i + 1).padStart(2, '0')}`,
        inboundDate: inboundDate.toISOString().split('T')[0],
        supplier: suppliers[i % suppliers.length],
        qty: qty,
        remainingQty: qty,
        location: locations[i % locations.length],
        status: qty > 0 ? '사용가능' : '소진',
        daysInStock: daysAgo,
        poNo: `PO-${inboundDate.toISOString().slice(2, 10).replace(/-/g, '')}-${String(Math.floor(Math.random() * 99) + 1).padStart(2, '0')}`,
      });
    }

    // FIFO 순서 (입고일 오름차순)
    return lots.sort((a, b) => new Date(a.inboundDate) - new Date(b.inboundDate));
  };

  const lots = generateLots();

  const getStockStatus = () => {
    if (stock.stock === 0) return { label: '재고없음', color: 'bg-red-100 text-red-700' };
    if (stock.stock <= stock.minStock) return { label: '부족', color: 'bg-orange-100 text-orange-700' };
    return { label: '정상', color: 'bg-green-100 text-green-700' };
  };

  const status = getStockStatus();

  return (
    <div className="space-y-6">
      {/* 헤더 - 타이틀/버튼 분리 */}
      <div className="space-y-3">
        {/* 타이틀 영역 */}
        <div className="flex items-center gap-4">
          <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
            <Package className="w-6 h-6 text-blue-500" />
            재고 상세
          </h1>
          <div className="flex items-center gap-2 text-sm text-gray-500">
            <span className="font-mono">{stock.materialCode}</span>
            <span className={`px-2 py-1 rounded-full text-xs font-medium ${status.color}`}>
              {status.label}
            </span>
          </div>
        </div>

        {/* 버튼 영역 */}
        <div className="flex items-center justify-end gap-2">
          <button
            onClick={() => onNavigate?.('stock-list')}
            className="flex items-center gap-1 px-4 py-2 border rounded hover:bg-gray-50"
          >
            목록
          </button>
        </div>
      </div>

      {/* 기본 정보 */}
      <Card title="기본 정보">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div>
            <p className="text-sm text-gray-500 mb-1">품목코드</p>
            <p className="font-mono font-medium">{stock.materialCode}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">품목명</p>
            <p className="font-medium">{stock.materialName}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">품목유형</p>
            <p>{stock.itemType || '-'}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">카테고리</p>
            <p>{stock.category || '-'}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">규격</p>
            <p>{stock.spec || '-'}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">단위</p>
            <p>{stock.unit}</p>
          </div>
        </div>
      </Card>

      {/* 재고 현황 */}
      <Card title="재고 현황">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div>
            <p className="text-sm text-gray-500 mb-1">현재 재고량</p>
            <p className="font-bold text-2xl text-blue-600">{stock.stock.toLocaleString()} {stock.unit}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">안전 재고</p>
            <p className="font-bold text-lg text-gray-700">{stock.minStock.toLocaleString()} {stock.unit}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">재고 위치</p>
            <p className="font-medium">{stock.location}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">LOT 개수</p>
            <p className="font-medium">{lots.length}개</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">최근 입고일</p>
            <p>{lots.length > 0 ? lots[lots.length - 1].inboundDate : '-'}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">재고 상태</p>
            <p className={`inline-block px-3 py-1 rounded-full text-sm font-medium ${status.color}`}>
              {status.label}
            </p>
          </div>
        </div>
      </Card>

      {/* LOT별 상세 재고 */}
      <Card title="LOT별 상세 재고">
        {lots.length > 0 ? (
          <>
            <div className="mb-4 flex items-center gap-2 text-sm">
              <span className="px-2 py-1 bg-green-100 text-green-700 rounded">FIFO 순서</span>
              <span className="text-gray-500">오래된 LOT부터 사용 권장</span>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm border">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 border-b">FIFO</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 border-b">LOT번호</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 border-b">입고일</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 border-b">경과일</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 border-b">공급업체</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 border-b">발주번호</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 border-b">수량</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 border-b">위치</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 border-b">상태</th>
                  </tr>
                </thead>
                <tbody>
                  {lots.map((lot, idx) => (
                    <tr key={lot.id} className={`border-b hover:bg-gray-50 ${idx === 0 ? 'bg-green-50' : ''}`}>
                      <td className="px-4 py-3 text-center">
                        {idx === 0 ? (
                          <span className="inline-flex items-center justify-center w-6 h-6 bg-green-500 text-white rounded-full text-xs font-bold">1</span>
                        ) : (
                          <span className="inline-flex items-center justify-center w-6 h-6 bg-gray-200 text-gray-600 rounded-full text-xs">{idx + 1}</span>
                        )}
                      </td>
                      <td className="px-4 py-3 font-mono text-blue-600 font-medium">{lot.lotNo}</td>
                      <td className="px-4 py-3 text-gray-700">{lot.inboundDate}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded text-xs font-medium ${
                          lot.daysInStock > 30 ? 'bg-orange-100 text-orange-700' :
                          lot.daysInStock > 14 ? 'bg-yellow-100 text-yellow-700' :
                          'bg-green-100 text-green-700'
                        }`}>
                          {lot.daysInStock}일
                        </span>
                      </td>
                      <td className="px-4 py-3 text-gray-600">{lot.supplier}</td>
                      <td className="px-4 py-3 font-mono text-gray-500">{lot.poNo}</td>
                      <td className="px-4 py-3 text-right font-medium">{lot.remainingQty.toLocaleString()} {stock.unit}</td>
                      <td className="px-4 py-3 text-center text-gray-500">{lot.location}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded text-xs font-medium ${
                          lot.status === '사용가능' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'
                        }`}>
                          {lot.status}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
                <tfoot className="bg-gray-50">
                  <tr>
                    <td colSpan={6} className="px-4 py-3 text-right text-sm font-medium text-gray-600 border-t">합계:</td>
                    <td className="px-4 py-3 text-right font-bold text-gray-900 border-t">
                      {lots.reduce((sum, l) => sum + l.remainingQty, 0).toLocaleString()} {stock.unit}
                    </td>
                    <td colSpan={2} className="border-t"></td>
                  </tr>
                </tfoot>
              </table>
            </div>

            {/* FIFO 권장 안내 */}
            {lots.length > 0 && lots[0].daysInStock > 14 && (
              <div className="mt-4 flex items-center gap-2 p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-sm">
                <AlertCircle className="w-5 h-5 text-yellow-600 flex-shrink-0" />
                <span className="text-yellow-800">
                  <strong>FIFO 권장:</strong> LOT {lots[0].lotNo}가 {lots[0].daysInStock}일 경과되었습니다. 우선 사용을 권장합니다.
                </span>
              </div>
            )}
          </>
        ) : (
          <div className="text-center py-8 text-gray-500">
            LOT 정보가 없습니다.
          </div>
        )}
      </Card>
    </div>
  );
};

// ============================================================
// 수입검사 등록 폼 (IQC)
// ============================================================
const IQCRegisterForm = ({
  purchaseOrders = [],
  initialData = null, // 입고관리에서 전달한 입고 데이터
  onNavigate,
  onSave,
}) => {
  const [selectedPO, setSelectedPO] = useState(initialData || null);

  // LOT 번호 생성 함수 (채번 규칙: YYMMDD-##)
  const generateLotNo = () => {
    const now = new Date();
    const yy = String(now.getFullYear()).slice(-2);
    const mm = String(now.getMonth() + 1).padStart(2, '0');
    const dd = String(now.getDate()).padStart(2, '0');
    const seq = String(Math.floor(Math.random() * 99) + 1).padStart(2, '0'); // 실제로는 당일 순번 조회 필요
    return `${yy}${mm}${dd}-${seq}`;
  };

  const [inspectionForm, setInspectionForm] = useState({
    lotNo: initialData?.incomingLot || generateLotNo(),
    inspectorName: '',
    inspectionDate: new Date().toISOString().split('T')[0],
    result: '합격',
    inspectionItems: [
      { item: '겉모양', standard: '사용상 해로운 결함이 없을 것', method: '육안검사', result: '적', note: '' },
      { item: '두께', standard: '규격 참조', method: '마이크로미터', result: '적', note: '' },
      { item: '폭', standard: '규격 참조', method: '줄자', result: '적', note: '' },
      { item: '길이', standard: '규격 참조', method: '줄자', result: '적', note: '' },
    ],
    note: '',
  });

  // 검사대기 목록
  const pendingPOs = purchaseOrders.filter(po => po.status === '검사대기' || po.status === '입고대기');

  const handleSubmit = () => {
    if (!selectedPO) {
      alert('검사 대상을 선택해주세요.');
      return;
    }
    if (!inspectionForm.inspectorName) {
      alert('검사자를 입력해주세요.');
      return;
    }

    const hasFailure = inspectionForm.inspectionItems.some(item => item.result === '부');
    const lotNo = inspectionForm.lotNo || generateLotNo(); // 입력된 LOT 또는 새로 생성

    const inspectionData = {
      targetNo: selectedPO.poNo || selectedPO.id,
      targetType: 'incoming',
      lotNo: lotNo,
      itemName: selectedPO.itemName || selectedPO.productName,
      qty: selectedPO.qty || selectedPO.orderQty,
      inspector: inspectionForm.inspectorName,
      inspectionDate: inspectionForm.inspectionDate,
      result: hasFailure ? '불합격' : '합격',
      inspectionItems: inspectionForm.inspectionItems,
      note: inspectionForm.note,
    };

    onSave?.(inspectionData);
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <ShieldCheck className="w-6 h-6 text-blue-500" />
          수입검사 등록 (IQC)
        </h1>
        <div className="flex items-center justify-end gap-2">
          <button
            onClick={() => onNavigate?.('inspection-list')}
            className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            취소
          </button>
          <button
            onClick={handleSubmit}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-1"
          >
            <Save className="w-4 h-4" />
            검사 저장
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 검사 대상 선택 */}
        <div className="bg-white rounded-xl border p-4">
          <h3 className="font-bold text-gray-900 mb-4">검사 대상 선택</h3>
          {pendingPOs.length === 0 ? (
            <p className="text-gray-500 text-sm">검사 대기중인 입고가 없습니다.</p>
          ) : (
            <div className="space-y-2">
              {pendingPOs.map(po => (
                <div
                  key={po.id}
                  onClick={() => setSelectedPO(po)}
                  className={`p-3 rounded-lg cursor-pointer transition-all ${selectedPO?.id === po.id
                      ? 'bg-blue-50 border-2 border-blue-500'
                      : 'bg-gray-50 hover:bg-gray-100 border border-transparent'
                    }`}
                >
                  <p className="font-mono text-sm font-medium">{po.poNo || po.id}</p>
                  <p className="text-sm text-gray-600">{po.itemName || po.productName}</p>
                  <p className="text-xs text-gray-500">{po.supplierName || po.vendorName} · {po.qty || po.orderQty}EA</p>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 검사 정보 입력 */}
        <div className="lg:col-span-2 bg-white rounded-xl border p-4">
          <h3 className="font-bold text-gray-900 mb-4">검사 정보</h3>
          {selectedPO ? (
            <div className="space-y-4">
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">검사일</label>
                  <input
                    type="date"
                    value={inspectionForm.inspectionDate}
                    onChange={(e) => setInspectionForm(prev => ({ ...prev, inspectionDate: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">검사자 <span className="text-red-500">*</span></label>
                  <input
                    type="text"
                    value={inspectionForm.inspectorName}
                    onChange={(e) => setInspectionForm(prev => ({ ...prev, inspectorName: e.target.value }))}
                    placeholder="검사자명 입력"
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">LOT번호 (YYMMDD-##)</label>
                  <input
                    type="text"
                    value={inspectionForm.lotNo}
                    placeholder="자동생성"
                    className="w-full px-3 py-2 border rounded-lg bg-gray-100 font-mono text-gray-500 cursor-not-allowed"
                    readOnly
                    disabled
                  />
                </div>
              </div>

              {/* 검사 항목 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">검사 항목</label>
                <table className="w-full text-sm border">
                  <thead>
                    <tr className="bg-gray-50">
                      <th className="p-2 text-left border">검사항목</th>
                      <th className="p-2 text-left border">규격</th>
                      <th className="p-2 text-left border">검사방법</th>
                      <th className="p-2 text-center border w-24">판정</th>
                      <th className="p-2 text-left border">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {inspectionForm.inspectionItems.map((item, idx) => (
                      <tr key={idx}>
                        <td className="p-2 border">{item.item}</td>
                        <td className="p-2 border">{item.standard}</td>
                        <td className="p-2 border">{item.method}</td>
                        <td className="p-2 border text-center">
                          <select
                            value={item.result}
                            onChange={(e) => {
                              const newItems = [...inspectionForm.inspectionItems];
                              newItems[idx].result = e.target.value;
                              setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                            }}
                            className={`px-2 py-1 rounded border ${item.result === '적' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
                              }`}
                          >
                            <option value="적">적</option>
                            <option value="부">부</option>
                          </select>
                        </td>
                        <td className="p-2 border">
                          <input
                            type="text"
                            value={item.note}
                            onChange={(e) => {
                              const newItems = [...inspectionForm.inspectionItems];
                              newItems[idx].note = e.target.value;
                              setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                            }}
                            className="w-full px-2 py-1 border rounded"
                            placeholder="비고"
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">종합 의견</label>
                <textarea
                  value={inspectionForm.note}
                  onChange={(e) => setInspectionForm(prev => ({ ...prev, note: e.target.value }))}
                  rows={3}
                  className="w-full px-3 py-2 border rounded-lg"
                  placeholder="검사 관련 특이사항 입력"
                />
              </div>
            </div>
          ) : (
            <div className="flex items-center justify-center h-48 text-gray-500">
              좌측에서 검사 대상을 선택해주세요.
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ============================================================
// 중간검사 등록 폼 (PQC)
// ============================================================
const PQCRegisterForm = ({
  workOrders = [],
  onNavigate,
  onSave,
}) => {
  const [selectedWO, setSelectedWO] = useState(null);
  const [inspectionForm, setInspectionForm] = useState({
    inspectorName: '',
    inspectionDate: new Date().toISOString().split('T')[0],
    processStep: '',
    inspectionItems: [
      { item: '외관상태', standard: '이상 없을 것', method: '육안검사', result: '적', note: '' },
      { item: '치수', standard: '도면 기준', method: '측정기', result: '적', note: '' },
      { item: '작업상태', standard: '기준서 준수', method: '확인', result: '적', note: '' },
    ],
    note: '',
  });

  // 검사대기 작업지시 (작업중)
  const pendingWOs = workOrders.filter(wo => wo.status === '작업중');

  const handleSubmit = () => {
    if (!selectedWO) {
      alert('검사 대상을 선택해주세요.');
      return;
    }
    if (!inspectionForm.inspectorName) {
      alert('검사자를 입력해주세요.');
      return;
    }

    const hasFailure = inspectionForm.inspectionItems.some(item => item.result === '부');

    const inspectionData = {
      targetNo: selectedWO.workOrderNo,
      targetType: 'process',
      processStep: inspectionForm.processStep || selectedWO.currentStep,
      itemName: selectedWO.productName,
      qty: selectedWO.totalQty,
      inspector: inspectionForm.inspectorName,
      inspectionDate: inspectionForm.inspectionDate,
      result: hasFailure ? '불합격' : '합격',
      inspectionItems: inspectionForm.inspectionItems,
      note: inspectionForm.note,
    };

    onSave?.(inspectionData);
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <ShieldCheck className="w-6 h-6 text-yellow-500" />
          중간검사 등록 (PQC)
        </h1>
        <div className="flex items-center justify-end gap-2">
          <button
            onClick={() => onNavigate?.('inspection-list')}
            className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            취소
          </button>
          <button
            onClick={handleSubmit}
            className="px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 flex items-center gap-1"
          >
            <Save className="w-4 h-4" />
            검사 저장
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 검사 대상 선택 */}
        <div className="bg-white rounded-xl border p-4">
          <h3 className="font-bold text-gray-900 mb-4">검사 대상 선택</h3>
          {pendingWOs.length === 0 ? (
            <p className="text-gray-500 text-sm">검사 대기중인 작업지시가 없습니다.</p>
          ) : (
            <div className="space-y-2">
              {pendingWOs.map(wo => (
                <div
                  key={wo.id}
                  onClick={() => setSelectedWO(wo)}
                  className={`p-3 rounded-lg cursor-pointer transition-all ${selectedWO?.id === wo.id
                      ? 'bg-yellow-50 border-2 border-yellow-500'
                      : 'bg-gray-50 hover:bg-gray-100 border border-transparent'
                    }`}
                >
                  <p className="font-mono text-sm font-medium">{wo.workOrderNo}</p>
                  <p className="text-sm text-gray-600">{wo.customerName} · {wo.processType}</p>
                  <p className="text-xs text-gray-500">{wo.currentStep || '진행중'} · {wo.totalQty}EA</p>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 검사 정보 입력 */}
        <div className="lg:col-span-2 bg-white rounded-xl border p-4">
          <h3 className="font-bold text-gray-900 mb-4">검사 정보</h3>
          {selectedWO ? (
            <div className="space-y-4">
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">검사일</label>
                  <input
                    type="date"
                    value={inspectionForm.inspectionDate}
                    onChange={(e) => setInspectionForm(prev => ({ ...prev, inspectionDate: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">검사공정</label>
                  <input
                    type="text"
                    value={inspectionForm.processStep || selectedWO.currentStep}
                    onChange={(e) => setInspectionForm(prev => ({ ...prev, processStep: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">검사자 <span className="text-red-500">*</span></label>
                  <input
                    type="text"
                    value={inspectionForm.inspectorName}
                    onChange={(e) => setInspectionForm(prev => ({ ...prev, inspectorName: e.target.value }))}
                    placeholder="검사자명 입력"
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
              </div>

              {/* 검사 항목 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">검사 항목</label>
                <table className="w-full text-sm border">
                  <thead>
                    <tr className="bg-gray-50">
                      <th className="p-2 text-left border">검사항목</th>
                      <th className="p-2 text-left border">규격</th>
                      <th className="p-2 text-left border">검사방법</th>
                      <th className="p-2 text-center border w-24">판정</th>
                      <th className="p-2 text-left border">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {inspectionForm.inspectionItems.map((item, idx) => (
                      <tr key={idx}>
                        <td className="p-2 border">{item.item}</td>
                        <td className="p-2 border">{item.standard}</td>
                        <td className="p-2 border">{item.method}</td>
                        <td className="p-2 border text-center">
                          <select
                            value={item.result}
                            onChange={(e) => {
                              const newItems = [...inspectionForm.inspectionItems];
                              newItems[idx].result = e.target.value;
                              setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                            }}
                            className={`px-2 py-1 rounded border ${item.result === '적' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
                              }`}
                          >
                            <option value="적">적</option>
                            <option value="부">부</option>
                          </select>
                        </td>
                        <td className="p-2 border">
                          <input
                            type="text"
                            value={item.note}
                            onChange={(e) => {
                              const newItems = [...inspectionForm.inspectionItems];
                              newItems[idx].note = e.target.value;
                              setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                            }}
                            className="w-full px-2 py-1 border rounded"
                            placeholder="비고"
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">종합 의견</label>
                <textarea
                  value={inspectionForm.note}
                  onChange={(e) => setInspectionForm(prev => ({ ...prev, note: e.target.value }))}
                  rows={3}
                  className="w-full px-3 py-2 border rounded-lg"
                  placeholder="검사 관련 특이사항 입력"
                />
              </div>
            </div>
          ) : (
            <div className="flex items-center justify-center h-48 text-gray-500">
              좌측에서 검사 대상을 선택해주세요.
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ============================================================
// 제품검사 등록 폼 (FQC)
// ============================================================
const FQCRegisterForm = ({
  workOrders = [],
  shipments = [],
  onNavigate,
  onSave,
}) => {
  const [selectedWO, setSelectedWO] = useState(null);
  const [inspectionForm, setInspectionForm] = useState({
    inspectorName: '',
    inspectionDate: new Date().toISOString().split('T')[0],
    inspectionItems: [
      { item: '외관검사', standard: '이상 없을 것', method: '육안검사', result: '적', note: '' },
      { item: '치수검사', standard: '도면 기준 ±2mm', method: '측정기', result: '적', note: '' },
      { item: '작동검사', standard: '정상 작동', method: '작동 테스트', result: '적', note: '' },
      { item: '포장상태', standard: '파손 방지 포장', method: '확인', result: '적', note: '' },
    ],
    note: '',
  });

  // 제품검사 대기 (작업완료, 검사 미완료)
  const pendingWOs = workOrders.filter(wo =>
    wo.status === '작업완료' && wo.inspectionStatus !== '검사완료'
  );

  const handleSubmit = () => {
    if (!selectedWO) {
      alert('검사 대상을 선택해주세요.');
      return;
    }
    if (!inspectionForm.inspectorName) {
      alert('검사자를 입력해주세요.');
      return;
    }

    const hasFailure = inspectionForm.inspectionItems.some(item => item.result === '부');

    const inspectionData = {
      targetNo: selectedWO.workOrderNo,
      targetType: 'final',
      itemName: selectedWO.productName,
      qty: selectedWO.completedQty || selectedWO.totalQty,
      inspector: inspectionForm.inspectorName,
      inspectionDate: inspectionForm.inspectionDate,
      result: hasFailure ? '불합격' : '합격',
      inspectionItems: inspectionForm.inspectionItems,
      note: inspectionForm.note,
    };

    onSave?.(inspectionData);
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <ShieldCheck className="w-6 h-6 text-green-500" />
          제품검사 등록 (FQC)
        </h1>
        <div className="flex items-center justify-end gap-2">
          <button
            onClick={() => onNavigate?.('inspection-list')}
            className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            취소
          </button>
          <button
            onClick={handleSubmit}
            className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-1"
          >
            <Save className="w-4 h-4" />
            검사 저장
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 검사 대상 선택 */}
        <div className="bg-white rounded-xl border p-4">
          <h3 className="font-bold text-gray-900 mb-4">검사 대상 선택</h3>
          {pendingWOs.length === 0 ? (
            <p className="text-gray-500 text-sm">검사 대기중인 제품이 없습니다.</p>
          ) : (
            <div className="space-y-2">
              {pendingWOs.map(wo => (
                <div
                  key={wo.id}
                  onClick={() => setSelectedWO(wo)}
                  className={`p-3 rounded-lg cursor-pointer transition-all ${selectedWO?.id === wo.id
                      ? 'bg-green-50 border-2 border-green-500'
                      : 'bg-gray-50 hover:bg-gray-100 border border-transparent'
                    }`}
                >
                  <p className="font-mono text-sm font-medium">{wo.workOrderNo}</p>
                  <p className="text-sm text-gray-600">{wo.customerName} · {wo.processType}</p>
                  <p className="text-xs text-gray-500">완료수량: {wo.completedQty || 0}/{wo.totalQty}EA</p>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 검사 정보 입력 */}
        <div className="lg:col-span-2 bg-white rounded-xl border p-4">
          <h3 className="font-bold text-gray-900 mb-4">검사 정보</h3>
          {selectedWO ? (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">검사일</label>
                  <input
                    type="date"
                    value={inspectionForm.inspectionDate}
                    onChange={(e) => setInspectionForm(prev => ({ ...prev, inspectionDate: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">검사자 <span className="text-red-500">*</span></label>
                  <input
                    type="text"
                    value={inspectionForm.inspectorName}
                    onChange={(e) => setInspectionForm(prev => ({ ...prev, inspectorName: e.target.value }))}
                    placeholder="검사자명 입력"
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
              </div>

              {/* 검사 항목 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">검사 항목</label>
                <table className="w-full text-sm border">
                  <thead>
                    <tr className="bg-gray-50">
                      <th className="p-2 text-left border">검사항목</th>
                      <th className="p-2 text-left border">규격</th>
                      <th className="p-2 text-left border">검사방법</th>
                      <th className="p-2 text-center border w-24">판정</th>
                      <th className="p-2 text-left border">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {inspectionForm.inspectionItems.map((item, idx) => (
                      <tr key={idx}>
                        <td className="p-2 border">{item.item}</td>
                        <td className="p-2 border">{item.standard}</td>
                        <td className="p-2 border">{item.method}</td>
                        <td className="p-2 border text-center">
                          <select
                            value={item.result}
                            onChange={(e) => {
                              const newItems = [...inspectionForm.inspectionItems];
                              newItems[idx].result = e.target.value;
                              setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                            }}
                            className={`px-2 py-1 rounded border ${item.result === '적' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
                              }`}
                          >
                            <option value="적">적</option>
                            <option value="부">부</option>
                          </select>
                        </td>
                        <td className="p-2 border">
                          <input
                            type="text"
                            value={item.note}
                            onChange={(e) => {
                              const newItems = [...inspectionForm.inspectionItems];
                              newItems[idx].note = e.target.value;
                              setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                            }}
                            className="w-full px-2 py-1 border rounded"
                            placeholder="비고"
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">종합 의견</label>
                <textarea
                  value={inspectionForm.note}
                  onChange={(e) => setInspectionForm(prev => ({ ...prev, note: e.target.value }))}
                  rows={3}
                  className="w-full px-3 py-2 border rounded-lg"
                  placeholder="검사 관련 특이사항 입력"
                />
              </div>
            </div>
          ) : (
            <div className="flex items-center justify-center h-48 text-gray-500">
              좌측에서 검사 대상을 선택해주세요.
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ============================================================
// 수입검사 컴포넌트
// ============================================================
const IncomingInspectionList = ({
  inspections = [],
  purchaseOrders = [],
  onSave,
  onNavigate,
  onApprovalRequest, // 결재요청 콜백
  onStockRegister,   // 재고등록 콜백
}) => {
  const [activeTab, setActiveTab] = useState('pending');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showApprovalModal, setShowApprovalModal] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);
  const [selectedForApproval, setSelectedForApproval] = useState(null);
  const [inspectionForm, setInspectionForm] = useState({
    result: '합격',
    inspectorName: '',
    inspectionItems: [],
    note: '',
    // 결재라인 (APR-2LINE: 담당 → 부서장)
    approvalLine: {
      type: 'APR-2LINE',
      roles: [
        { id: 'staff', label: '담당', name: '', date: '', status: 'pending' },
        { id: 'manager', label: '부서장', name: '', date: '', status: 'pending' },
      ]
    }
  });

  // 검사대기 목록 (입고완료 but 검사 미완료)
  const pendingInspections = purchaseOrders.filter(po => po.status === '검사대기');

  // 검사완료 목록
  const completedInspections = inspections.filter(insp => insp.type === 'incoming');

  const handleOpenInspection = (po) => {
    setSelectedItem(po);
    // 자재 유형에 따른 검사항목 자동 설정 (KS 규격 기반)
    const materialType = po.materialType || 'EGI'; // EGI, SUS, AL 등

    // 샘플링 기준 (n=3, c=0)
    const sampleCount = 3;

    // KS D 3528 기반 수입검사 항목
    const defaultInspectionItems = [
      {
        item: '겉모양',
        standard: '사용상 해로운 결함이 없을 것',
        method: '육안검사',
        sampleValues: Array(sampleCount).fill({ value: '', result: 'OK' }),
        result: '적',
        note: ''
      },
      {
        item: '두께',
        standard: po.thickness ? `${po.thickness}mm` : '규격 참조',
        method: '체크검사',
        tolerance: po.thickness >= 1.6 ? '± 0.12' : po.thickness >= 1.25 ? '± 0.10' : '± 0.08',
        sampleValues: Array(sampleCount).fill({ value: '', result: '' }),
        result: '적',
        note: ''
      },
      {
        item: '너비',
        standard: po.width ? `${po.width}mm` : '규격 참조',
        method: '체크검사',
        tolerance: po.width && po.width < 1250 ? '+7/-0' : '+10/-0',
        sampleValues: Array(sampleCount).fill({ value: '', result: '' }),
        result: '적',
        note: ''
      },
      {
        item: '길이',
        standard: po.length ? `${po.length}mm` : '규격 참조',
        method: '체크검사',
        tolerance: '+15/-0',
        sampleValues: Array(sampleCount).fill({ value: '', result: '' }),
        result: '적',
        note: ''
      },
      {
        item: '인장강도',
        standard: '270 이상 (N/㎟)',
        method: '공급업체 밀시트',
        sampleValues: [{ value: '', result: '' }],
        result: '적',
        note: ''
      },
      {
        item: '연신율',
        standard: po.thickness >= 1.6 ? '38 이상 (%)' : po.thickness >= 1.0 ? '37 이상 (%)' : '36 이상 (%)',
        method: '공급업체 밀시트',
        sampleValues: [{ value: '', result: '' }],
        result: '적',
        note: ''
      },
      {
        item: '아연의 최소 부착량',
        standard: '한면 17 이상 (g/㎡)',
        method: '공급업체 밀시트',
        sampleValues: [{ value: '', result: '' }],
        result: '적',
        note: ''
      },
    ];

    setInspectionForm({
      result: '합격',
      inspectorName: '',
      lotSize: po.receivedQty || 200,
      sampleSize: sampleCount,
      acceptanceNumber: 0, // c=0
      inspectionItems: defaultInspectionItems,
      note: '',
      standardRef: 'KS F 4510', // 관련 KS 규격
    });
    setShowCreateModal(true);
  };

  const handleSaveInspection = () => {
    if (!inspectionForm.inspectorName) {
      alert('검사자를 입력해주세요.');
      return;
    }

    // 새로운 '적/부' 구조에 맞게 불합격 판정 (result가 '부'인 항목이 하나라도 있으면 불합격)
    const hasFailure = inspectionForm.inspectionItems.some(item => item.result === '부');
    const today = new Date();
    // LOT번호: YYMMDD-순번 형식
    const lotNo = `${today.toISOString().slice(2, 10).replace(/-/g, '')}-${String(Math.floor(Math.random() * 99) + 1).padStart(2, '0')}`;

    const inspectionData = {
      id: Date.now(),
      type: 'incoming',
      lotNo: lotNo,
      poNo: selectedItem.poNo,
      materialCode: selectedItem.materialCode,
      materialName: selectedItem.materialName,
      specification: selectedItem.specification,
      thickness: selectedItem.thickness,
      vendor: selectedItem.vendor,
      incomingLot: selectedItem.incomingLot,
      receivedQty: selectedItem.receivedQty,
      unit: selectedItem.unit,
      // KS규격 기반 검사 정보
      standardRef: inspectionForm.standardRef || 'KS D 3528',
      lotSize: inspectionForm.lotSize,
      sampleSize: inspectionForm.sampleSize,
      acceptanceNumber: inspectionForm.acceptanceNumber,
      inspectorName: inspectionForm.inspectorName,
      inspectionDate: today.toISOString().split('T')[0],
      result: hasFailure ? '불합격' : '합격',
      judgement: hasFailure ? '부적합' : '적합',
      inspectionItems: inspectionForm.inspectionItems,
      note: inspectionForm.note,
      // ★ 결재 및 프로세스 연동 정보 추가
      approvalStatus: '결재대기', // 결재대기 → 결재완료
      approvalLine: {
        type: 'APR-2LINE',
        roles: [
          { id: 'staff', label: '담당', name: inspectionForm.inspectorName, date: today.toISOString().split('T')[0], status: 'approved' },
          { id: 'manager', label: '부서장', name: '', date: '', status: 'pending' },
        ]
      },
      // 프로세스 연동
      processFlow: {
        trigger: '자재입고',
        currentStep: hasFailure ? '부적합품처리' : '재고등록대기',
        nextAction: hasFailure ? 'NCR발행' : '결재완료시재고등록',
      },
      // NCR 정보 (불합격 시)
      ncrInfo: hasFailure ? {
        ncrNo: `NCR-IQC-${today.toISOString().slice(2, 10).replace(/-/g, '')}-${String(Math.floor(Math.random() * 99) + 1).padStart(2, '0')}`,
        defectType: inspectionForm.inspectionItems.filter(i => i.result === '부').map(i => i.item).join(', '),
        status: '발행대기',
      } : null,
    };

    onSave?.(inspectionData, selectedItem.id);
    setShowCreateModal(false);
    setSelectedItem(null);

    if (hasFailure) {
      alert(`⚠️ 수입검사 불합격!\n\n검사LOT: ${lotNo}\n품명: ${selectedItem.materialName}\n판정: 부적합 (c>${inspectionForm.acceptanceNumber})\nNCR번호: ${inspectionData.ncrInfo.ncrNo}\n\n▶ 부서장 결재 후 부적합품 처리가 진행됩니다.`);
    } else {
      alert(`✅ 수입검사 합격!\n\n검사LOT: ${lotNo}\n품명: ${selectedItem.materialName}\n판정: 적합 (c≤${inspectionForm.acceptanceNumber})\n\n▶ 부서장 결재 후 재고에 반영됩니다.`);
    }
  };

  // 결재 처리 함수
  const handleApproval = (inspection, approverName) => {
    const updatedApprovalLine = {
      ...inspection.approvalLine,
      roles: inspection.approvalLine.roles.map(role =>
        role.status === 'pending'
          ? { ...role, name: approverName, date: new Date().toISOString().split('T')[0], status: 'approved' }
          : role
      )
    };

    const allApproved = updatedApprovalLine.roles.every(r => r.status === 'approved');

    const updatedInspection = {
      ...inspection,
      approvalLine: updatedApprovalLine,
      approvalStatus: allApproved ? '결재완료' : '결재중',
      processFlow: {
        ...inspection.processFlow,
        currentStep: allApproved
          ? (inspection.result === '합격' ? '재고등록완료' : 'NCR처리중')
          : inspection.processFlow.currentStep,
      }
    };

    // 결재 완료 시 후속 처리
    if (allApproved && inspection.result === '합격') {
      // 재고 등록 트리거
      onStockRegister?.({
        materialCode: inspection.materialCode,
        materialName: inspection.materialName,
        quantity: inspection.receivedQty,
        unit: inspection.unit,
        lotNo: inspection.incomingLot,
        inspectionLot: inspection.lotNo,
        location: '원자재창고',
        registeredAt: new Date().toISOString(),
      });
      alert(`✅ 결재 완료!\n\n${inspection.materialName}\n수량: ${inspection.receivedQty} ${inspection.unit}\n\n▶ 재고에 등록되었습니다.`);
    } else if (allApproved && inspection.result === '불합격') {
      // NCR 처리 트리거
      alert(`⚠️ 결재 완료!\n\nNCR번호: ${inspection.ncrInfo?.ncrNo}\n\n▶ 부적합품 관리에서 처리해주세요.\n(반품/폐기/특채)`);
    }

    onSave?.(updatedInspection, inspection.id);
    setShowApprovalModal(false);
    setSelectedForApproval(null);
  };

  const getResultBadge = (result) => {
    return result === '합격'
      ? 'bg-green-100 text-green-700'
      : 'bg-red-100 text-red-700';
  };

  return (
    <div className="space-y-4">
      {/* 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <Download className="w-6 h-6 text-blue-500" />
          수입검사(IQC) 목록
        </h1>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">검사대기</div>
          <div className="text-2xl font-bold text-yellow-600 mt-1">{pendingInspections.length}</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">금일완료</div>
          <div className="text-2xl font-bold text-blue-600 mt-1">
            {completedInspections.filter(i => i.inspectionDate === new Date().toISOString().split('T')[0]).length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">합격</div>
          <div className="text-2xl font-bold text-green-600 mt-1">
            {completedInspections.filter(i => i.result === '합격').length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">불합격</div>
          <div className="text-2xl font-bold text-red-600 mt-1">
            {completedInspections.filter(i => i.result === '불합격').length}
          </div>
        </div>
      </div>

      {/* 탭 */}
      <div className="bg-white rounded-lg shadow-sm border">
        <div className="border-b">
          <div className="flex gap-2 p-2">
            {[
              { id: 'pending', label: '검사대기', count: pendingInspections.length },
              { id: 'completed', label: '검사완료', count: completedInspections.length },
            ].map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${activeTab === tab.id
                    ? 'bg-green-600 text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
              >
                {tab.label} ({tab.count})
              </button>
            ))}
          </div>
        </div>

        {/* 테이블 */}
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                {activeTab === 'pending' ? (
                  <>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">입고LOT</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">발주번호</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">공급업체</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">입고수량</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">입고일</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
                  </>
                ) : (
                  <>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">검사LOT</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">입고LOT</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">공급업체</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">검사수량</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">검사일</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">검사자</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">결과</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
                  </>
                )}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {activeTab === 'pending' ? (
                pendingInspections.length === 0 ? (
                  <tr>
                    <td colSpan="7" className="px-4 py-8 text-center text-gray-500">
                      검사 대기 중인 입고건이 없습니다.
                    </td>
                  </tr>
                ) : (
                  pendingInspections.map(po => (
                    <tr key={po.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3 text-sm font-mono text-blue-600 font-medium">{po.incomingLot}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{po.poNo}</td>
                      <td className="px-4 py-3 text-sm text-gray-900">{po.materialName}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{po.vendor}</td>
                      <td className="px-4 py-3 text-sm text-right">{po.receivedQty} {po.unit}</td>
                      <td className="px-4 py-3 text-sm text-center text-gray-500">{po.receivedDate}</td>
                      <td className="px-4 py-3 text-center">
                        <button
                          onClick={() => handleOpenInspection(po)}
                          className="px-3 py-1 bg-green-500 text-white text-xs rounded hover:bg-green-600"
                        >
                          검사실시
                        </button>
                      </td>
                    </tr>
                  ))
                )
              ) : (
                completedInspections.length === 0 ? (
                  <tr>
                    <td colSpan="8" className="px-4 py-8 text-center text-gray-500">
                      완료된 검사가 없습니다.
                    </td>
                  </tr>
                ) : (
                  completedInspections.map(insp => (
                    <tr key={insp.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3 text-sm font-mono text-blue-600 font-medium">{insp.lotNo}</td>
                      <td className="px-4 py-3 text-sm font-mono text-gray-600">{insp.incomingLot}</td>
                      <td className="px-4 py-3 text-sm text-gray-900">{insp.materialName}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{insp.vendor}</td>
                      <td className="px-4 py-3 text-sm text-right">{insp.receivedQty} {insp.unit}</td>
                      <td className="px-4 py-3 text-sm text-center text-gray-500">{insp.inspectionDate}</td>
                      <td className="px-4 py-3 text-sm text-center">{insp.inspectorName}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded-full text-xs font-medium ${getResultBadge(insp.result)}`}>
                          {insp.result}
                        </span>
                      </td>
                      {/* 작업 버튼 */}
                      <td className="px-4 py-3 text-center">
                        <div className="flex items-center justify-center gap-1">
                          {insp.result === '불합격' && insp.ncrInfo && (
                            <button
                              onClick={() => onNavigate?.('defect-list')}
                              className="px-2 py-1 bg-red-500 text-white text-xs rounded hover:bg-red-600"
                            >
                              NCR
                            </button>
                          )}
                          <button
                            onClick={() => window.print()}
                            className="px-2 py-1 bg-gray-500 text-white text-xs rounded hover:bg-gray-600"
                          >
                            출력
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* 검사 실시 모달 */}
      {showCreateModal && selectedItem && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-5xl max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b flex justify-between items-center sticky top-0 bg-white">
              <h3 className="text-lg font-bold">수입검사 성적서</h3>
              <button onClick={() => setShowCreateModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6 space-y-4">
              {/* 품목 기본 정보 */}
              <div className="bg-blue-50 rounded-lg p-4">
                <div className="flex justify-between items-start mb-3">
                  <h4 className="text-sm font-medium text-blue-800">품목 정보</h4>
                  <span className="text-xs text-blue-600 font-mono">입고일자: {selectedItem.receivedDate || new Date().toISOString().split('T')[0]}</span>
                </div>
                <div className="grid grid-cols-3 gap-3 text-sm">
                  <div className="col-span-2">
                    <span className="text-gray-500">품명:</span>
                    <span className="font-medium ml-1">{selectedItem.materialName}</span>
                    <span className="text-xs text-gray-400 ml-2">({selectedItem.standard || 'KS D 3528, SECC'})</span>
                  </div>
                  <div>
                    <span className="text-gray-500">납품업체:</span>
                    <span className="ml-1">{selectedItem.vendor}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">규격 (두께*너비*길이):</span>
                    <span className="font-mono ml-1">{selectedItem.spec || `${selectedItem.thickness || '1.55'} * ${selectedItem.width || '1218'} * ${selectedItem.length || '480'}`}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">로트번호:</span>
                    <span className="font-mono font-medium text-blue-600 ml-1">{selectedItem.incomingLot}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">제조업체:</span>
                    <span className="ml-1">{selectedItem.manufacturer || '-'}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">자재번호:</span>
                    <span className="font-mono ml-1">{selectedItem.materialCode}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">로트크기:</span>
                    <span className="ml-1">{inspectionForm.lotSize || selectedItem.receivedQty} 매</span>
                  </div>
                </div>
              </div>

              {/* 샘플링 정보 */}
              <div className="flex items-center gap-4 p-3 bg-yellow-50 rounded-lg text-sm">
                <span className="text-yellow-800 font-medium">샘플링:</span>
                <span>n = {inspectionForm.sampleSize || 3}</span>
                <span>c = {inspectionForm.acceptanceNumber || 0}</span>
                <span className="text-xs text-yellow-600">({inspectionForm.standardRef || 'KS F 4510'} 기준)</span>
              </div>

              {/* KS 규격 기반 검사 항목 테이블 */}
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2">검사 항목</h4>
                <div className="border rounded-lg overflow-hidden">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-100">
                      <tr>
                        <th rowSpan="2" className="px-2 py-2 text-left text-xs font-medium text-gray-600 border-r w-8">NO</th>
                        <th rowSpan="2" className="px-2 py-2 text-left text-xs font-medium text-gray-600 border-r">검사항목</th>
                        <th rowSpan="2" className="px-2 py-2 text-left text-xs font-medium text-gray-600 border-r">검사기준</th>
                        <th rowSpan="2" className="px-2 py-2 text-center text-xs font-medium text-gray-600 border-r w-20">검사방식</th>
                        <th rowSpan="2" className="px-2 py-2 text-center text-xs font-medium text-gray-600 border-r w-16">검사주기</th>
                        <th colSpan="3" className="px-2 py-1 text-center text-xs font-medium text-gray-600 border-r border-b">측정치</th>
                        <th rowSpan="2" className="px-2 py-2 text-center text-xs font-medium text-gray-600 w-16">판정<br />(적/부)</th>
                      </tr>
                      <tr className="bg-gray-50">
                        <th className="px-2 py-1 text-center text-xs font-medium text-gray-500 border-r w-20">n1<br />양호/불량</th>
                        <th className="px-2 py-1 text-center text-xs font-medium text-gray-500 border-r w-20">n2<br />양호/불량</th>
                        <th className="px-2 py-1 text-center text-xs font-medium text-gray-500 border-r w-20">n3<br />양호/불량</th>
                      </tr>
                    </thead>
                    <tbody>
                      {inspectionForm.inspectionItems.map((item, idx) => (
                        <tr key={idx} className="border-t hover:bg-gray-50">
                          <td className="px-2 py-2 text-center border-r text-gray-500">{idx + 1}</td>
                          <td className="px-2 py-2 border-r">
                            <div className="font-medium">{item.item}</div>
                            {item.tolerance && <div className="text-xs text-gray-400">{item.tolerance}</div>}
                          </td>
                          <td className="px-2 py-2 border-r text-gray-600">{item.standard}</td>
                          <td className="px-2 py-2 text-center border-r text-xs">{item.method}</td>
                          <td className="px-2 py-2 text-center border-r text-xs">n={item.sampleValues?.length || 3}<br />c=0</td>
                          {/* 측정치 n1, n2, n3 */}
                          {(item.sampleValues || [{}, {}, {}]).slice(0, 3).map((sample, sIdx) => (
                            <td key={sIdx} className="px-1 py-1 border-r">
                              {item.item === '겉모양' ? (
                                <div className="flex items-center justify-center gap-1">
                                  <button
                                    onClick={() => {
                                      const newItems = [...inspectionForm.inspectionItems];
                                      if (!newItems[idx].sampleValues) newItems[idx].sampleValues = [{}, {}, {}];
                                      newItems[idx].sampleValues[sIdx] = { value: 'OK', result: 'OK' };
                                      setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                                    }}
                                    className={`px-1 py-0.5 text-xs rounded ${sample.result === 'OK' ? 'bg-green-500 text-white' : 'bg-gray-200'}`}
                                  >OK</button>
                                  <button
                                    onClick={() => {
                                      const newItems = [...inspectionForm.inspectionItems];
                                      if (!newItems[idx].sampleValues) newItems[idx].sampleValues = [{}, {}, {}];
                                      newItems[idx].sampleValues[sIdx] = { value: 'NG', result: 'NG' };
                                      setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                                    }}
                                    className={`px-1 py-0.5 text-xs rounded ${sample.result === 'NG' ? 'bg-red-500 text-white' : 'bg-gray-200'}`}
                                  >NG</button>
                                </div>
                              ) : item.method === '공급업체 밀시트' && sIdx > 0 ? (
                                <div className="text-center text-gray-300">-</div>
                              ) : (
                                <input
                                  type="text"
                                  value={sample.value || ''}
                                  onChange={(e) => {
                                    const newItems = [...inspectionForm.inspectionItems];
                                    if (!newItems[idx].sampleValues) newItems[idx].sampleValues = [{}, {}, {}];
                                    newItems[idx].sampleValues[sIdx] = { ...newItems[idx].sampleValues[sIdx], value: e.target.value };
                                    setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                                  }}
                                  className="w-full px-1 py-1 border rounded text-xs text-center"
                                  placeholder="-"
                                />
                              )}
                            </td>
                          ))}
                          <td className="px-2 py-2 text-center">
                            <select
                              value={item.result}
                              onChange={(e) => {
                                const newItems = [...inspectionForm.inspectionItems];
                                newItems[idx].result = e.target.value;
                                setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                              }}
                              className={`px-2 py-1 border rounded text-xs font-medium ${item.result === '적' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
                                }`}
                            >
                              <option value="적">적</option>
                              <option value="부">부</option>
                            </select>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* 비고 및 종합판정 */}
              <div className="grid grid-cols-3 gap-4">
                <div className="col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-1">부적합 내용</label>
                  <textarea
                    value={inspectionForm.note}
                    onChange={(e) => setInspectionForm(prev => ({ ...prev, note: e.target.value }))}
                    rows={2}
                    placeholder="부적합 사항이 있을 경우 기록"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
                <div className="flex flex-col items-center justify-center p-4 bg-gray-50 rounded-lg">
                  <span className="text-sm text-gray-500 mb-2">종합판정</span>
                  <span className={`text-2xl font-bold ${inspectionForm.inspectionItems.every(i => i.result === '적') ? 'text-green-600' : 'text-red-600'
                    }`}>
                    {inspectionForm.inspectionItems.every(i => i.result === '적') ? '합격' : '불합격'}
                  </span>
                </div>
              </div>

              {/* 검사자 정보 */}
              <div className="grid grid-cols-3 gap-4 pt-4 border-t">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    검사자 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={inspectionForm.inspectorName}
                    onChange={(e) => setInspectionForm(prev => ({ ...prev, inspectorName: e.target.value }))}
                    placeholder="검사자 이름"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">검사일자</label>
                  <input
                    type="text"
                    value={new Date().toISOString().split('T')[0]}
                    className="w-full px-3 py-2 border rounded-lg text-sm bg-gray-100"
                    readOnly
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">담당/부서장</label>
                  <div className="flex gap-2">
                    <input type="text" placeholder="담당" className="w-1/2 px-3 py-2 border rounded-lg text-sm bg-gray-50" readOnly />
                    <input type="text" placeholder="부서장" className="w-1/2 px-3 py-2 border rounded-lg text-sm bg-gray-50" readOnly />
                  </div>
                </div>
              </div>
            </div>
            <div className="p-4 border-t flex justify-end gap-2 sticky bottom-0 bg-white">
              <button
                onClick={() => setShowCreateModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleSaveInspection}
                className="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600"
              >
                검사 완료
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 결재 모달 */}
      {showApprovalModal && selectedForApproval && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-md">
            <div className="p-4 border-b flex justify-between items-center">
              <h3 className="text-lg font-bold">수입검사 결재</h3>
              <button onClick={() => setShowApprovalModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6 space-y-4">
              {/* 검사 정보 요약 */}
              <div className="bg-gray-50 rounded-lg p-4 text-sm space-y-2">
                <div className="flex justify-between">
                  <span className="text-gray-500">검사LOT:</span>
                  <span className="font-mono font-medium">{selectedForApproval.lotNo}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">품목:</span>
                  <span className="font-medium">{selectedForApproval.materialName}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">검사결과:</span>
                  <span className={`font-medium ${selectedForApproval.result === '합격' ? 'text-green-600' : 'text-red-600'}`}>
                    {selectedForApproval.result}
                  </span>
                </div>
                {selectedForApproval.ncrInfo && (
                  <div className="flex justify-between">
                    <span className="text-gray-500">NCR번호:</span>
                    <span className="font-mono text-red-600">{selectedForApproval.ncrInfo.ncrNo}</span>
                  </div>
                )}
              </div>

              {/* 결재라인 표시 */}
              <div>
                <div className="text-sm font-medium text-gray-700 mb-2">결재라인 (APR-2LINE)</div>
                <div className="border rounded-lg overflow-hidden">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-100">
                      <tr>
                        {selectedForApproval.approvalLine?.roles?.map(role => (
                          <th key={role.id} className="px-4 py-2 text-center border-r last:border-r-0">{role.label}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        {selectedForApproval.approvalLine?.roles?.map(role => (
                          <td key={role.id} className="px-4 py-3 text-center border-r last:border-r-0">
                            {role.status === 'approved' ? (
                              <div>
                                <div className="text-green-600 font-medium">{role.name}</div>
                                <div className="text-xs text-gray-400">{role.date}</div>
                              </div>
                            ) : (
                              <div className="text-gray-400">대기중</div>
                            )}
                          </td>
                        ))}
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

              {/* 결재자 입력 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">결재자 (부서장) <span className="text-red-500">*</span></label>
                <input
                  type="text"
                  id="approver-name"
                  placeholder="결재자 이름 입력"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>

              {/* 결재 후 처리 안내 */}
              <div className={`p-3 rounded-lg text-sm ${selectedForApproval.result === '합격' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
                <div className="font-medium mb-1">결재 후 처리:</div>
                {selectedForApproval.result === '합격' ? (
                  <div>▶ 재고 자동 등록 (원자재창고)</div>
                ) : (
                  <div>▶ 부적합품 관리로 이동 (NCR 처리)</div>
                )}
              </div>
            </div>
            <div className="p-4 border-t flex justify-end gap-2">
              <button
                onClick={() => setShowApprovalModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={() => {
                  const approverName = document.getElementById('approver-name')?.value;
                  if (!approverName) {
                    alert('결재자 이름을 입력해주세요.');
                    return;
                  }
                  handleApproval(selectedForApproval, approverName);
                }}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
              >
                결재 승인
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============================================================
// 중간검사 컴포넌트 (PQC)
// ============================================================
const ProcessInspectionList = ({
  inspections = [],
  workOrders = [],
  onSave,
  onNavigate,
  onApprovalRequest, // 결재요청 콜백
  onProcessPermit,   // 다음 공정 허용 콜백
  inspectionRequests = [], // 작업자화면에서 온 검사요청 목록
}) => {
  const [activeTab, setActiveTab] = useState('pending');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showApprovalModal, setShowApprovalModal] = useState(false);
  const [selectedWorkOrder, setSelectedWorkOrder] = useState(null);
  const [selectedForApproval, setSelectedForApproval] = useState(null);
  const [inspectionForm, setInspectionForm] = useState({
    processStep: '',
    inspectorName: '',
    inspectionItems: [],
    note: '',
    // 결재라인 (APR-3LINE: 작성 → 검토 → 승인)
    approvalLine: {
      type: 'APR-3LINE',
      roles: [
        { id: 'writer', label: '작성', name: '', date: '', status: 'pending' },
        { id: 'reviewer', label: '검토', name: '', date: '', status: 'pending' },
        { id: 'approver', label: '승인', name: '', date: '', status: 'pending' },
      ]
    }
  });

  // 검사가 필요한 작업지시 (작업중 상태)
  const pendingWorkOrders = workOrders.filter(wo =>
    wo.status === '작업중' && wo.approvalStatus === '승인완료'
  );

  // 완료된 중간검사
  const completedInspections = inspections.filter(insp => insp.type === 'process');

  // 공정단계 옵션
  const processSteps = [
    { code: '1', name: '원단절단' },
    { code: '2', name: '미싱' },
    { code: '3', name: '앤드락작업' },
    { code: '4', name: '중간검사' },
    { code: '5', name: '포장' },
  ];

  const handleOpenInspection = (wo) => {
    setSelectedWorkOrder(wo);

    // 제품 유형에 따른 측정 포인트 수 결정 (스크린/절곡 등)
    const measurementPoints = 5; // ①~⑤ 측정 포인트

    // 기본 검사항목 with 다중 측정 포인트 구조
    const defaultInspectionItems = [
      {
        item: '치수검사(폭)',
        standard: wo.items?.[0]?.width ? `${wo.items[0].width}mm` : '도면규격',
        tolerance: '± 3mm',
        result: '합격',
        measurements: Array(measurementPoints).fill(''),  // ①~⑤ 측정값
        average: '',
        judgement: '적'
      },
      {
        item: '치수검사(길이)',
        standard: wo.items?.[0]?.height ? `${wo.items[0].height}mm` : '도면규격',
        tolerance: '± 5mm',
        result: '합격',
        measurements: Array(measurementPoints).fill(''),
        average: '',
        judgement: '적'
      },
      {
        item: '외관검사',
        standard: '스크래치/오염/변형 없음',
        tolerance: '-',
        result: '합격',
        measurements: Array(measurementPoints).fill('OK'),
        average: '-',
        judgement: '적'
      },
      {
        item: '직각도',
        standard: '90°',
        tolerance: '± 1°',
        result: '합격',
        measurements: Array(measurementPoints).fill(''),
        average: '',
        judgement: '적'
      },
      {
        item: '평탄도',
        standard: '평탄',
        tolerance: '굴곡 3mm 이하',
        result: '합격',
        measurements: Array(measurementPoints).fill('OK'),
        average: '-',
        judgement: '적'
      },
    ];

    setInspectionForm({
      processStep: '4', // 기본값: 중간검사 단계
      inspectorName: '',
      measurementPoints: measurementPoints,
      lotSize: wo.totalQty || wo.items?.[0]?.quantity || 10,
      sampleSize: measurementPoints,
      standardRef: 'KS F 4510',
      inspectionItems: defaultInspectionItems,
      note: '',
    });
    setShowCreateModal(true);
  };

  const handleSaveInspection = () => {
    if (!inspectionForm.inspectorName || !inspectionForm.processStep) {
      alert('검사자와 공정단계를 입력해주세요.');
      return;
    }

    // 새로운 '적/부' 구조에 맞게 불합격 판정 (judgement가 '부'인 항목이 있으면 불합격)
    const hasFailure = inspectionForm.inspectionItems.some(item => item.judgement === '부' || item.result === '불합격');
    const today = new Date();
    const dateStr = today.toISOString().slice(2, 10).replace(/-/g, '');
    const seq = String(Math.floor(Math.random() * 99) + 1).padStart(2, '0');
    const stepName = processSteps.find(s => s.code === inspectionForm.processStep)?.name || '';
    const lotNo = `KD-SC-${dateStr}-${seq}-(${inspectionForm.processStep})`;

    const inspectionData = {
      id: Date.now(),
      type: 'process',
      lotNo: lotNo,
      workOrderNo: selectedWorkOrder.workOrderNo,
      orderNo: selectedWorkOrder.orderNo,
      productName: selectedWorkOrder.productName || selectedWorkOrder.items?.[0]?.productName,
      specification: selectedWorkOrder.items?.[0] ? `${selectedWorkOrder.items[0].width}×${selectedWorkOrder.items[0].height}` : '',
      processStep: inspectionForm.processStep,
      processStepName: stepName,
      // KS규격 기반 검사 정보
      standardRef: inspectionForm.standardRef || 'KS F 4510',
      lotSize: inspectionForm.lotSize,
      sampleSize: inspectionForm.sampleSize,
      measurementPoints: inspectionForm.measurementPoints,
      inspectorName: inspectionForm.inspectorName,
      inspectionDate: today.toISOString().split('T')[0],
      result: hasFailure ? '불합격' : '합격',
      judgement: hasFailure ? '부적합' : '적합',
      inspectionItems: inspectionForm.inspectionItems,
      note: inspectionForm.note,
      // ★ 결재 및 프로세스 연동 정보 추가
      approvalStatus: '결재대기',
      approvalLine: {
        type: 'APR-3LINE',
        roles: [
          { id: 'writer', label: '작성', name: inspectionForm.inspectorName, date: today.toISOString().split('T')[0], status: 'approved' },
          { id: 'reviewer', label: '검토', name: '', date: '', status: 'pending' },
          { id: 'approver', label: '승인', name: '', date: '', status: 'pending' },
        ]
      },
      processFlow: {
        trigger: '작업자검사요청',
        currentStep: hasFailure ? '재작업대기' : '다음공정허용대기',
        nextAction: hasFailure ? '재작업지시' : '결재완료시다음공정허용',
        requestedFrom: selectedWorkOrder.assignee || '작업자',
        requestedAt: today.toISOString(),
      },
      // 불합격 시 NCR 자동 발행
      ncrInfo: hasFailure ? {
        ncrNo: `NCR-PQC-${dateStr}-${seq}`,
        defectType: inspectionForm.inspectionItems.filter(i => i.judgement === '부').map(i => i.item).join(', '),
        status: '발행대기',
        defectiveQty: selectedWorkOrder.totalQty || 1,
        action: '재작업',
      } : null,
    };

    onSave?.(inspectionData);
    setShowCreateModal(false);
    setSelectedWorkOrder(null);

    if (hasFailure) {
      alert(`⚠️ 중간검사 불합격!\n\n검사LOT: ${lotNo}\n공정: ${stepName}\n판정: 부적합\n\nNCR번호: NCR-PQC-${dateStr}-${seq}\n재작업이 필요합니다.`);
    } else {
      alert(`✅ 중간검사 합격!\n\n검사LOT: ${lotNo}\n공정: ${stepName}\n판정: 적합\n\n결재완료 후 다음 공정이 허용됩니다.`);
    }
  };

  // ★ 결재 처리 핸들러
  const handleApproval = (inspection, approverName, approverRole) => {
    const today = new Date();
    const updatedApprovalLine = {
      ...inspection.approvalLine,
      roles: inspection.approvalLine.roles.map(role => {
        // 현재 결재 순서에 해당하는 역할 찾기
        if (role.status === 'pending') {
          const pendingRoles = inspection.approvalLine.roles.filter(r => r.status === 'pending');
          if (pendingRoles[0]?.id === role.id) {
            return { ...role, name: approverName, date: today.toISOString().split('T')[0], status: 'approved' };
          }
        }
        return role;
      })
    };

    const allApproved = updatedApprovalLine.roles.every(r => r.status === 'approved');

    // 결재 완료 시 후속 처리
    if (allApproved && inspection.result === '합격') {
      // 다음 공정 허용 콜백
      onProcessPermit?.({
        workOrderNo: inspection.workOrderNo,
        processStep: inspection.processStep,
        inspectionLot: inspection.lotNo,
        permittedAt: today.toISOString(),
      });
    }

    // 결재 요청 콜백
    onApprovalRequest?.({
      ...inspection,
      approvalStatus: allApproved ? '결재완료' : '결재중',
      approvalLine: updatedApprovalLine,
      processFlow: {
        ...inspection.processFlow,
        currentStep: allApproved ? (inspection.result === '합격' ? '다음공정허용완료' : '재작업진행중') : '결재진행중',
      }
    });

    setShowApprovalModal(false);
    setSelectedForApproval(null);

    if (allApproved) {
      alert(`✅ 결재가 완료되었습니다.\n\n검사LOT: ${inspection.lotNo}\n${inspection.result === '합격' ? '다음 공정이 허용되었습니다.' : '재작업을 진행해주세요.'}`);
    }
  };

  // 현재 결재 단계 확인
  const getCurrentApprovalStep = (approvalLine) => {
    if (!approvalLine?.roles) return null;
    return approvalLine.roles.find(r => r.status === 'pending');
  };

  const getResultBadge = (result) => {
    return result === '합격'
      ? 'bg-green-100 text-green-700'
      : 'bg-red-100 text-red-700';
  };

  return (
    <div className="space-y-4">
      {/* 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <ClipboardList className="w-6 h-6 text-blue-500" />
          중간검사(PQC) 목록
        </h1>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">검사가능</div>
          <div className="text-2xl font-bold text-blue-600 mt-1">{pendingWorkOrders.length}</div>
          <div className="text-xs text-gray-400 mt-1">작업중인 작업지시</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">금일검사</div>
          <div className="text-2xl font-bold text-purple-600 mt-1">
            {completedInspections.filter(i => i.inspectionDate === new Date().toISOString().split('T')[0]).length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">합격</div>
          <div className="text-2xl font-bold text-green-600 mt-1">
            {completedInspections.filter(i => i.result === '합격').length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">불합격</div>
          <div className="text-2xl font-bold text-red-600 mt-1">
            {completedInspections.filter(i => i.result === '불합격').length}
          </div>
        </div>
      </div>

      {/* 탭 */}
      <div className="bg-white rounded-lg shadow-sm border">
        <div className="border-b">
          <div className="flex gap-2 p-2">
            {[
              { id: 'pending', label: '검사가능', count: pendingWorkOrders.length },
              { id: 'completed', label: '검사이력', count: completedInspections.length },
            ].map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${activeTab === tab.id
                    ? 'bg-purple-600 text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
              >
                {tab.label} ({tab.count})
              </button>
            ))}
          </div>
        </div>

        {/* 테이블 */}
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                {activeTab === 'pending' ? (
                  <>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">작업지시번호</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">수주번호</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">수량</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">현재공정</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
                  </>
                ) : (
                  <>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">검사LOT</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">작업지시번호</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">공정단계</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">검사일</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">검사자</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">결과</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
                  </>
                )}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {activeTab === 'pending' ? (
                pendingWorkOrders.length === 0 ? (
                  <tr>
                    <td colSpan="7" className="px-4 py-8 text-center text-gray-500">
                      검사 가능한 작업지시가 없습니다.
                    </td>
                  </tr>
                ) : (
                  pendingWorkOrders.map(wo => (
                    <tr key={wo.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3 text-sm font-mono text-blue-600 font-medium">{wo.workOrderNo}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{wo.orderNo}</td>
                      <td className="px-4 py-3 text-sm text-gray-900">
                        {wo.productName || wo.items?.[0]?.productName || '-'}
                      </td>
                      <td className="px-4 py-3 text-sm text-right">{wo.totalQty || wo.items?.[0]?.quantity}</td>
                      <td className="px-4 py-3 text-sm text-center">
                        <span className="px-2 py-0.5 bg-purple-100 text-purple-700 rounded text-xs">
                          {wo.currentStep || '미싱'}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-center">
                        <span className="px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-700">
                          {wo.status}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-center">
                        <button
                          onClick={() => handleOpenInspection(wo)}
                          className="px-3 py-1 bg-purple-500 text-white text-xs rounded hover:bg-purple-600"
                        >
                          검사실시
                        </button>
                      </td>
                    </tr>
                  ))
                )
              ) : (
                completedInspections.length === 0 ? (
                  <tr>
                    <td colSpan="9" className="px-4 py-8 text-center text-gray-500">
                      완료된 검사가 없습니다.
                    </td>
                  </tr>
                ) : (
                  completedInspections.map(insp => (
                    <tr key={insp.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3 text-sm font-mono text-blue-600 font-medium">{insp.lotNo}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{insp.workOrderNo}</td>
                      <td className="px-4 py-3 text-sm text-gray-900">{insp.productName}</td>
                      <td className="px-4 py-3 text-sm text-center">
                        <span className="px-2 py-0.5 bg-gray-100 text-gray-700 rounded text-xs">
                          {insp.processStepName}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-sm text-center text-gray-500">{insp.inspectionDate}</td>
                      <td className="px-4 py-3 text-sm text-center">{insp.inspectorName}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded-full text-xs font-medium ${getResultBadge(insp.result)}`}>
                          {insp.result}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-center">
                        <div className="flex gap-1 justify-center">
                          {insp.ncrInfo && (
                            <button
                              onClick={() => onNavigate?.('defect', { ncrNo: insp.ncrInfo.ncrNo })}
                              className="px-2 py-1 bg-red-500 text-white text-xs rounded hover:bg-red-600"
                            >
                              NCR
                            </button>
                          )}
                          <button
                            onClick={() => alert(`검사성적서 출력: ${insp.lotNo}`)}
                            className="px-2 py-1 bg-gray-500 text-white text-xs rounded hover:bg-gray-600"
                          >
                            출력
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* 검사 실시 모달 - 다중 측정 포인트 지원 */}
      {showCreateModal && selectedWorkOrder && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-5xl max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b flex justify-between items-center sticky top-0 bg-white z-10">
              <h3 className="text-lg font-bold">중간검사성적서</h3>
              <button onClick={() => setShowCreateModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6 space-y-4">
              {/* 품목 및 작업지시 정보 */}
              <div className="bg-purple-50 rounded-lg p-4">
                <h4 className="text-sm font-medium text-purple-800 mb-3">품목 정보</h4>
                <div className="grid grid-cols-4 gap-3 text-sm">
                  <div><span className="text-gray-500">작업지시번호:</span> <span className="font-mono font-medium">{selectedWorkOrder.workOrderNo}</span></div>
                  <div><span className="text-gray-500">수주번호:</span> <span>{selectedWorkOrder.orderNo}</span></div>
                  <div><span className="text-gray-500">품목:</span> <span className="font-medium">{selectedWorkOrder.productName || selectedWorkOrder.items?.[0]?.productName}</span></div>
                  <div><span className="text-gray-500">생산수량:</span> <span className="font-medium">{selectedWorkOrder.totalQty || selectedWorkOrder.items?.[0]?.quantity}EA</span></div>
                  {selectedWorkOrder.items?.[0] && (
                    <>
                      <div><span className="text-gray-500">규격(폭):</span> <span>{selectedWorkOrder.items[0].width}mm</span></div>
                      <div><span className="text-gray-500">규격(길이):</span> <span>{selectedWorkOrder.items[0].height}mm</span></div>
                    </>
                  )}
                </div>
              </div>

              {/* 공정단계 및 샘플링 정보 */}
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    검사 공정단계 <span className="text-red-500">*</span>
                  </label>
                  <select
                    value={inspectionForm.processStep}
                    onChange={(e) => setInspectionForm(prev => ({ ...prev, processStep: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  >
                    {processSteps.map(step => (
                      <option key={step.code} value={step.code}>
                        {step.code}단계 - {step.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="bg-yellow-50 rounded-lg p-3 text-center">
                  <div className="text-xs text-gray-500">적용규격</div>
                  <div className="font-medium text-sm">{inspectionForm.standardRef}</div>
                </div>
                <div className="bg-blue-50 rounded-lg p-3 text-center">
                  <div className="text-xs text-gray-500">샘플수</div>
                  <div className="font-medium text-sm">n={inspectionForm.measurementPoints} (①~⑤)</div>
                </div>
              </div>

              {/* 검사 항목 - 다중 측정 포인트 테이블 */}
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2">검사 항목 (다중 측정)</h4>
                <div className="border rounded-lg overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-100">
                      <tr>
                        <th rowSpan="2" className="px-2 py-2 border-r text-xs font-medium text-gray-600 w-24">검사항목</th>
                        <th rowSpan="2" className="px-2 py-2 border-r text-xs font-medium text-gray-600 w-20">규격</th>
                        <th rowSpan="2" className="px-2 py-2 border-r text-xs font-medium text-gray-600 w-16">허용차</th>
                        <th colSpan="5" className="px-2 py-1 border-r text-xs font-medium text-gray-600 bg-blue-50">측정값</th>
                        <th rowSpan="2" className="px-2 py-2 border-r text-xs font-medium text-gray-600 w-16">평균</th>
                        <th rowSpan="2" className="px-2 py-2 text-xs font-medium text-gray-600 w-14">판정</th>
                      </tr>
                      <tr className="bg-blue-50">
                        <th className="px-1 py-1 border-r text-xs w-14">①</th>
                        <th className="px-1 py-1 border-r text-xs w-14">②</th>
                        <th className="px-1 py-1 border-r text-xs w-14">③</th>
                        <th className="px-1 py-1 border-r text-xs w-14">④</th>
                        <th className="px-1 py-1 border-r text-xs w-14">⑤</th>
                      </tr>
                    </thead>
                    <tbody>
                      {inspectionForm.inspectionItems.map((item, idx) => (
                        <tr key={idx} className="border-t hover:bg-gray-50">
                          <td className="px-2 py-2 border-r font-medium text-gray-800">{item.item}</td>
                          <td className="px-2 py-2 border-r text-center text-gray-600">{item.standard}</td>
                          <td className="px-2 py-2 border-r text-center text-gray-500 text-xs">{item.tolerance}</td>
                          {/* ①~⑤ 측정값 입력 */}
                          {item.measurements.map((val, mIdx) => (
                            <td key={mIdx} className="px-1 py-1 border-r">
                              <input
                                type="text"
                                value={val}
                                onChange={(e) => {
                                  const newItems = [...inspectionForm.inspectionItems];
                                  newItems[idx].measurements[mIdx] = e.target.value;
                                  // 평균 계산 (숫자인 경우만)
                                  const numVals = newItems[idx].measurements.filter(v => !isNaN(parseFloat(v)) && v !== '');
                                  if (numVals.length > 0 && item.item.includes('치수') || item.item.includes('직각도')) {
                                    const avg = numVals.reduce((sum, v) => sum + parseFloat(v), 0) / numVals.length;
                                    newItems[idx].average = avg.toFixed(1);
                                  }
                                  setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                                }}
                                className="w-full px-1 py-1 border rounded text-xs text-center"
                                placeholder="-"
                              />
                            </td>
                          ))}
                          <td className="px-2 py-2 border-r text-center font-medium bg-gray-50">{item.average || '-'}</td>
                          <td className="px-2 py-2 text-center">
                            <select
                              value={item.judgement}
                              onChange={(e) => {
                                const newItems = [...inspectionForm.inspectionItems];
                                newItems[idx].judgement = e.target.value;
                                newItems[idx].result = e.target.value === '적' ? '합격' : '불합격';
                                setInspectionForm(prev => ({ ...prev, inspectionItems: newItems }));
                              }}
                              className={`px-1 py-1 border rounded text-xs font-bold ${item.judgement === '적' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                                }`}
                            >
                              <option value="적">적</option>
                              <option value="부">부</option>
                            </select>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* 종합 판정 */}
              <div className="bg-gray-50 rounded-lg p-4">
                <div className="flex items-center justify-between">
                  <div className="text-sm font-medium text-gray-700">종합판정</div>
                  <div className={`text-lg font-bold px-4 py-2 rounded-lg ${inspectionForm.inspectionItems.some(i => i.judgement === '부')
                      ? 'bg-red-100 text-red-700'
                      : 'bg-green-100 text-green-700'
                    }`}>
                    {inspectionForm.inspectionItems.some(i => i.judgement === '부') ? '부적합' : '적합'}
                  </div>
                </div>
              </div>

              {/* 검사자 정보 */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    검사자 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={inspectionForm.inspectorName}
                    onChange={(e) => setInspectionForm(prev => ({ ...prev, inspectorName: e.target.value }))}
                    placeholder="검사자 이름"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">검사일</label>
                  <input
                    type="text"
                    value={new Date().toISOString().split('T')[0]}
                    className="w-full px-3 py-2 border rounded-lg text-sm bg-gray-100"
                    readOnly
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">부서장확인</label>
                  <input
                    type="text"
                    placeholder="부서장"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">품질팀확인</label>
                  <input
                    type="text"
                    placeholder="품질팀"
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <textarea
                  value={inspectionForm.note}
                  onChange={(e) => setInspectionForm(prev => ({ ...prev, note: e.target.value }))}
                  rows={2}
                  placeholder="특이사항 기록"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
            </div>
            <div className="p-4 border-t flex justify-end gap-2 sticky bottom-0 bg-white">
              <button
                onClick={() => setShowCreateModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleSaveInspection}
                className="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600"
              >
                검사 완료
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ★ 결재 모달 (APR-3LINE) */}
      {showApprovalModal && selectedForApproval && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-lg">
            <div className="p-4 border-b flex justify-between items-center">
              <h3 className="text-lg font-bold">중간검사 결재</h3>
              <button onClick={() => setShowApprovalModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6 space-y-4">
              {/* 검사 정보 */}
              <div className="bg-purple-50 rounded-lg p-4">
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div><span className="text-gray-500">검사LOT:</span> <span className="font-mono font-medium">{selectedForApproval.lotNo}</span></div>
                  <div><span className="text-gray-500">작업지시:</span> <span>{selectedForApproval.workOrderNo}</span></div>
                  <div><span className="text-gray-500">품목:</span> <span className="font-medium">{selectedForApproval.productName}</span></div>
                  <div><span className="text-gray-500">공정:</span> <span>{selectedForApproval.processStepName}</span></div>
                  <div>
                    <span className="text-gray-500">검사결과:</span>
                    <span className={`ml-1 px-2 py-0.5 rounded text-xs font-medium ${selectedForApproval.result === '합격' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                      }`}>
                      {selectedForApproval.result}
                    </span>
                  </div>
                  {selectedForApproval.ncrInfo && (
                    <div><span className="text-gray-500">NCR:</span> <span className="text-red-600 font-medium">{selectedForApproval.ncrInfo.ncrNo}</span></div>
                  )}
                </div>
              </div>

              {/* 결재라인 표시 (APR-3LINE: 작성 → 검토 → 승인) */}
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2">결재라인 (3단계)</h4>
                <div className="flex items-center justify-center gap-2">
                  {selectedForApproval.approvalLine?.roles.map((role, idx) => (
                    <React.Fragment key={role.id}>
                      <div className={`text-center p-3 rounded-lg border-2 min-w-[80px] ${role.status === 'approved' ? 'border-green-500 bg-green-50' :
                          role.status === 'pending' && idx === selectedForApproval.approvalLine.roles.findIndex(r => r.status === 'pending')
                            ? 'border-blue-500 bg-blue-50' : 'border-gray-200 bg-gray-50'
                        }`}>
                        <div className="text-xs text-gray-500 mb-1">{role.label}</div>
                        <div className="font-medium text-sm">{role.name || '-'}</div>
                        <div className="text-xs text-gray-400 mt-1">
                          {role.status === 'approved' ? role.date : role.status === 'pending' ? '대기' : ''}
                        </div>
                        {role.status === 'approved' && (
                          <CheckCircle className="w-4 h-4 text-green-600 mx-auto mt-1" />
                        )}
                      </div>
                      {idx < selectedForApproval.approvalLine.roles.length - 1 && (
                        <ChevronRight className="w-5 h-5 text-gray-400" />
                      )}
                    </React.Fragment>
                  ))}
                </div>
              </div>

              {/* 현재 결재자 입력 */}
              {getCurrentApprovalStep(selectedForApproval.approvalLine) && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {getCurrentApprovalStep(selectedForApproval.approvalLine).label}자 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    id="pqc-approver-name"
                    placeholder={`${getCurrentApprovalStep(selectedForApproval.approvalLine).label}자 이름`}
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  />
                </div>
              )}

              {/* 프로세스 플로우 정보 */}
              {selectedForApproval.processFlow && (
                <div className="bg-gray-50 rounded-lg p-3 text-sm">
                  <div className="flex items-center gap-2 text-gray-600">
                    <span className="font-medium">진행상태:</span>
                    <span className="px-2 py-0.5 bg-blue-100 text-blue-700 rounded text-xs">
                      {selectedForApproval.processFlow.currentStep}
                    </span>
                  </div>
                  <div className="text-xs text-gray-500 mt-1">
                    결재완료 시: {selectedForApproval.result === '합격' ? '다음 공정 진행 허용' : '재작업 지시'}
                  </div>
                </div>
              )}
            </div>
            <div className="p-4 border-t flex justify-end gap-2">
              <button
                onClick={() => setShowApprovalModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={() => {
                  const approverInput = document.getElementById('pqc-approver-name');
                  if (!approverInput?.value) {
                    alert('결재자 이름을 입력해주세요.');
                    return;
                  }
                  handleApproval(selectedForApproval, approverInput.value);
                }}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
              >
                결재승인
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============================================================
// 검사관리 통합 허브 (IQC/PQC/FQC 통합)
// ============================================================
const InspectionManagementHub = ({
  inspections = [],
  workOrders = [],
  purchaseOrders = [],
  shipments = [],
  onNavigate,
}) => {
  const [activeTab, setActiveTab] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedIds, setSelectedIds] = useState([]);
  const [certificateData, setCertificateData] = useState(null);

  // 수입검사 대기
  const iqcPending = purchaseOrders.filter(po => po.status === '검사대기' || po.status === '입고대기');

  // 중간검사 대기 (작업중인 작업지시서)
  const pqcPending = workOrders.filter(wo => wo.status === '작업중');

  // 제품검사 대기 (작업완료, 검사 미완료)
  const fqcPending = workOrders.filter(wo =>
    wo.status === '작업완료' && wo.inspectionStatus !== '검사완료'
  );

  // 전체 대기 건수
  const totalPending = iqcPending.length + pqcPending.length + fqcPending.length;

  // 완료 검사 건수
  const completedCount = inspections.filter(i => i.result === '합격' || i.result === 'pass').length;

  // 불합격 건수
  const failedCount = inspections.filter(i => i.result === '불합격' || i.result === 'fail').length;

  // 검색 필터링된 검사 이력
  const filteredInspections = inspections.filter(insp => {
    const matchesSearch = !searchTerm ||
      (insp.targetNo || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
      (insp.lotNo || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
      (insp.inspector || '').toLowerCase().includes(searchTerm.toLowerCase());

    const matchesTab = activeTab === 'all' ||
      (activeTab === 'iqc' && insp.type === 'incoming') ||
      (activeTab === 'pqc' && insp.type === 'process') ||
      (activeTab === 'fqc' && insp.type === 'final');

    return matchesSearch && matchesTab;
  }).sort((a, b) => new Date(b.inspectionDate) - new Date(a.inspectionDate));

  // 선택 관련 함수
  const handleSelect = (id) => {
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
    );
  };

  const handleSelectAll = (e) => {
    if (e.target.checked) {
      setSelectedIds(filteredInspections.map((_, idx) => idx));
    } else {
      setSelectedIds([]);
    }
  };

  const isSelected = (id) => selectedIds.includes(id);
  const hasSelection = selectedIds.length > 0;
  const isAllSelected = filteredInspections.length > 0 && selectedIds.length === filteredInspections.length;

  return (
    <div className="space-y-6">
      {/* 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <ShieldCheck className="w-6 h-6 text-blue-500" />
          검사 목록
        </h1>
        {/* 버튼 영역 - 우측 정렬 */}
        <div className="flex items-center justify-end gap-2">
          <button
            onClick={() => onNavigate?.('inspection-register')}
            className="flex items-center gap-1 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700"
          >
            <Plus className="w-4 h-4" />
            검사 등록
          </button>
        </div>
      </div>

      {/* 리포트 카드 4개 */}
      <div className="grid grid-cols-4 gap-4">
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">전체 대기</p>
          <p className="text-2xl font-bold">{totalPending}건</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">이번 달 검사 완료</p>
          <p className="text-2xl font-bold">{completedCount}건</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">불합격 건수</p>
          <p className="text-2xl font-bold text-red-600">{failedCount}건</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">합격률</p>
          <p className="text-2xl font-bold text-green-600">
            {inspections.length > 0 ? Math.round((completedCount / inspections.length) * 100) : 0}%
          </p>
        </div>
      </div>

      {/* 검색바 */}
      <div className="relative">
        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
        <input
          type="text"
          placeholder="검사번호, LOT번호, 검사자 검색..."
          className="w-full pl-12 pr-4 py-3 border rounded-xl"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
        />
      </div>

      {/* 검사유형별 탭 + 대기 현황 */}
      <div className="flex items-center gap-2">
        <button
          onClick={() => setActiveTab('all')}
          className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${activeTab === 'all' ? 'bg-gray-900 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
        >
          전체
        </button>
        <button
          onClick={() => setActiveTab('iqc')}
          className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${activeTab === 'iqc' ? 'bg-blue-600 text-white' : 'bg-blue-50 text-blue-700 hover:bg-blue-100'
            }`}
        >
          수입검사 (IQC) <span className="ml-1 px-1.5 py-0.5 bg-white/20 rounded">{iqcPending.length}</span>
        </button>
        <button
          onClick={() => setActiveTab('pqc')}
          className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${activeTab === 'pqc' ? 'bg-yellow-500 text-white' : 'bg-yellow-50 text-yellow-700 hover:bg-yellow-100'
            }`}
        >
          중간검사 (PQC) <span className="ml-1 px-1.5 py-0.5 bg-white/20 rounded">{pqcPending.length}</span>
        </button>
        <button
          onClick={() => setActiveTab('fqc')}
          className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${activeTab === 'fqc' ? 'bg-green-600 text-white' : 'bg-green-50 text-green-700 hover:bg-green-100'
            }`}
        >
          제품검사 (FQC) <span className="ml-1 px-1.5 py-0.5 bg-white/20 rounded">{fqcPending.length}</span>
        </button>
      </div>

      {/* 검사 대기 목록 (탭별) */}
      {(activeTab === 'iqc' || activeTab === 'all') && iqcPending.length > 0 && (
        <div className="bg-white rounded-xl border shadow-sm p-4">
          <h3 className="font-bold text-gray-900 mb-4">수입검사 대기 목록</h3>
          <div className="space-y-2">
            {iqcPending.map(po => (
              <div key={po.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-all">
                <div>
                  <p className="font-mono text-sm font-medium">{po.poNo || po.id}</p>
                  <p className="text-sm text-gray-600">{po.itemName || po.productName}</p>
                  <p className="text-xs text-gray-500">{po.supplierName || po.vendorName} · {po.qty || po.orderQty}EA</p>
                </div>
                <div className="flex items-center gap-2">
                  <span className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs font-medium">
                    {po.status}
                  </span>
                  <button
                    onClick={() => onNavigate?.('iqc-register')}
                    className="px-3 py-1.5 bg-blue-500 text-white rounded-lg text-sm font-medium hover:bg-blue-600"
                  >
                    검사하기
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {(activeTab === 'pqc' || activeTab === 'all') && pqcPending.length > 0 && (
        <div className="bg-white rounded-xl border shadow-sm p-4">
          <h3 className="font-bold text-gray-900 mb-4">중간검사 대기 목록</h3>
          <div className="space-y-2">
            {pqcPending.map(wo => (
              <div key={wo.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-all">
                <div>
                  <p className="font-mono text-sm font-medium">{wo.workOrderNo}</p>
                  <p className="text-sm text-gray-600">{wo.customerName} · {wo.processType}</p>
                  <p className="text-xs text-gray-500">{wo.currentStep || '진행중'} · {wo.totalQty}EA</p>
                </div>
                <div className="flex items-center gap-2">
                  <span className="px-2 py-1 bg-yellow-100 text-yellow-700 rounded text-xs font-medium">
                    {wo.status}
                  </span>
                  <button
                    onClick={() => onNavigate?.('pqc-register')}
                    className="px-3 py-1.5 bg-yellow-500 text-white rounded-lg text-sm font-medium hover:bg-yellow-600"
                  >
                    검사하기
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {(activeTab === 'fqc' || activeTab === 'all') && fqcPending.length > 0 && (
        <div className="bg-white rounded-xl border shadow-sm p-4">
          <h3 className="font-bold text-gray-900 mb-4">제품검사 대기 목록</h3>
          <div className="space-y-2">
            {fqcPending.map(wo => (
              <div key={wo.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-all">
                <div>
                  <p className="font-mono text-sm font-medium">{wo.workOrderNo}</p>
                  <p className="text-sm text-gray-600">{wo.customerName} · {wo.processType}</p>
                  <p className="text-xs text-gray-500">완료수량: {wo.completedQty || 0}/{wo.totalQty}EA</p>
                </div>
                <div className="flex items-center gap-2">
                  <span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs font-medium">
                    작업완료
                  </span>
                  <button
                    onClick={() => onNavigate?.('fqc-register')}
                    className="px-3 py-1.5 bg-green-500 text-white rounded-lg text-sm font-medium hover:bg-green-600"
                  >
                    검사하기
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 검사 이력 테이블 (체크박스 + 작업 컬럼) */}
      <div className="bg-white rounded-xl border shadow-sm">
        <div className="p-4 border-b flex items-center justify-between">
          <h3 className="font-bold text-gray-900">검사 이력</h3>
          {selectedIds.length > 1 && (
            <button className="px-3 py-1.5 bg-red-500 text-white rounded text-sm hover:bg-red-600">
              선택 삭제 ({selectedIds.length})
            </button>
          )}
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b bg-gray-50">
                <th className="p-3 w-10">
                  <input
                    type="checkbox"
                    checked={isAllSelected}
                    onChange={handleSelectAll}
                    className="rounded"
                  />
                </th>
                <th className="text-left p-3">검사일</th>
                <th className="text-left p-3">검사유형</th>
                <th className="text-left p-3">검사번호</th>
                <th className="text-left p-3">대상</th>
                <th className="text-left p-3">결과</th>
                <th className="text-left p-3">검사자</th>
                {hasSelection && <th className="text-left p-3">작업</th>}
              </tr>
            </thead>
            <tbody>
              {filteredInspections.map((insp, idx) => (
                <tr
                  key={idx}
                  className={`border-b hover:bg-gray-50 ${isSelected(idx) ? 'bg-blue-50' : ''}`}
                >
                  <td className="p-3">
                    <input
                      type="checkbox"
                      checked={isSelected(idx)}
                      onChange={() => handleSelect(idx)}
                      className="rounded"
                    />
                  </td>
                  <td className="p-3">{insp.inspectionDate || '-'}</td>
                  <td className="p-3">
                    <span className={`px-2 py-0.5 rounded text-xs ${insp.type === 'incoming' ? 'bg-blue-100 text-blue-700' :
                        insp.type === 'process' ? 'bg-yellow-100 text-yellow-700' :
                          'bg-green-100 text-green-700'
                      }`}>
                      {insp.type === 'incoming' ? 'IQC' :
                        insp.type === 'process' ? 'PQC' : 'FQC'}
                    </span>
                  </td>
                  <td className="p-3 font-mono">{insp.inspectionNo || `INS-${String(idx + 1).padStart(3, '0')}`}</td>
                  <td className="p-3">{insp.targetNo || insp.lotNo || '-'}</td>
                  <td className="p-3">
                    <span className={`px-2 py-0.5 rounded text-xs ${insp.result === '합격' || insp.result === 'pass' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                      }`}>
                      {insp.result === 'pass' ? '합격' : insp.result === 'fail' ? '불합격' : insp.result || '-'}
                    </span>
                  </td>
                  <td className="p-3">{insp.inspector || '-'}</td>
                  {hasSelection && (
                    <td className="p-3">
                      {isSelected(idx) && (
                        <div className="flex items-center gap-1">
                          <button
                            onClick={() => setCertificateData(insp)}
                            className="px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded hover:bg-blue-200 flex items-center gap-1"
                            title="검사 성적서 출력"
                          >
                            <Printer className="w-3 h-3" />
                            성적서
                          </button>
                          <button
                            onClick={() => onNavigate?.('inspection-detail')}
                            className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200"
                          >
                            상세
                          </button>
                          <button className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded hover:bg-red-200">
                            삭제
                          </button>
                        </div>
                      )}
                    </td>
                  )}
                </tr>
              ))}
              {filteredInspections.length === 0 && (
                <tr>
                  <td colSpan={hasSelection ? 8 : 7} className="p-8 text-center text-gray-500">
                    검사 이력이 없습니다
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* 검사 성적서 출력 모달 */}
      {certificateData && (
        <InspectionCertificateDocument
          inspectionData={certificateData}
          onClose={() => setCertificateData(null)}
        />
      )}
    </div>
  );
};

// ============================================================
// 부적합품관리 컴포넌트
// ============================================================
const DefectManagement = ({
  defects = [],
  inspections = [],
  onSave,
  onDispose,
  onRework,
  onNavigate,
  onApprovalRequest, // NCR 결재요청 콜백
  onVendorClaim, // 업체 클레임 콜백
}) => {
  const [activeTab, setActiveTab] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedIds, setSelectedIds] = useState([]);
  const [selectedDefect, setSelectedDefect] = useState(null);
  const [showActionModal, setShowActionModal] = useState(false);
  const [showApprovalModal, setShowApprovalModal] = useState(false);
  const [selectedForApproval, setSelectedForApproval] = useState(null);
  const [actionForm, setActionForm] = useState({
    action: 'rework', // rework, dispose, accept
    handler: '',
    note: '',
    // NCR 결재라인 (APR-3LINE)
    approvalLine: {
      type: 'APR-3LINE',
      roles: [
        { id: 'writer', label: '작성', name: '', date: '', status: 'pending' },
        { id: 'reviewer', label: '검토', name: '', date: '', status: 'pending' },
        { id: 'approver', label: '승인', name: '', date: '', status: 'pending' },
      ]
    }
  });

  // ★ NCR 결재 처리 핸들러
  const handleNCRApproval = (defect, approverName) => {
    const today = new Date();
    const updatedApprovalLine = {
      ...defect.approvalLine,
      roles: (defect.approvalLine?.roles || []).map(role => {
        if (role.status === 'pending') {
          const pendingRoles = defect.approvalLine.roles.filter(r => r.status === 'pending');
          if (pendingRoles[0]?.id === role.id) {
            return { ...role, name: approverName, date: today.toISOString().split('T')[0], status: 'approved' };
          }
        }
        return role;
      })
    };

    const allApproved = updatedApprovalLine.roles?.every(r => r.status === 'approved');

    // 결재 완료 시 후속 처리
    if (allApproved) {
      // 처리 방식에 따른 후속 액션
      if (defect.action === 'dispose' && defect.sourceType === '수입검사') {
        // 업체 클레임 발행
        onVendorClaim?.({
          ncrNo: defect.ncrNo || defect.defectNo,
          vendor: defect.vendor,
          defectType: defect.defectReason,
          quantity: defect.quantity,
          claimDate: today.toISOString().split('T')[0],
        });
      }
    }

    // 결재 요청 콜백
    onApprovalRequest?.({
      ...defect,
      approvalStatus: allApproved ? '결재완료' : '결재중',
      approvalLine: updatedApprovalLine,
    });

    setShowApprovalModal(false);
    setSelectedForApproval(null);

    if (allApproved) {
      alert(`✅ NCR 결재가 완료되었습니다.\n\nNCR번호: ${defect.ncrNo || defect.defectNo}\n처리방식: ${defect.status}\n${defect.action === 'dispose' && defect.sourceType === '수입검사' ? '업체 클레임이 발행됩니다.' : ''}`);
    }
  };

  // 현재 결재 단계 확인
  const getCurrentApprovalStep = (approvalLine) => {
    if (!approvalLine?.roles) return null;
    return approvalLine.roles.find(r => r.status === 'pending');
  };

  // 불합격 검사 목록에서 부적합품 추출 (NCR 정보 포함)
  const allDefects = [
    ...defects,
    ...inspections.filter(insp => insp.result === '불합격').map(insp => ({
      id: `insp-${insp.id}`,
      defectNo: `DF-${insp.lotNo}`,
      // ★ NCR 정보 연동
      ncrNo: insp.ncrInfo?.ncrNo || `NCR-${insp.type === 'incoming' ? 'IQC' : insp.type === 'process' ? 'PQC' : 'FQC'}-${insp.lotNo}`,
      sourceType: insp.type === 'incoming' ? '수입검사' : insp.type === 'process' ? '중간검사' : '제품검사',
      sourceLot: insp.lotNo,
      itemName: insp.materialName || insp.productName,
      quantity: insp.receivedQty || insp.ncrInfo?.defectiveQty || 1,
      unit: insp.unit || 'EA',
      defectReason: insp.ncrInfo?.defectType || insp.inspectionItems?.filter(i => i.result === '불합격' || i.judgement === '부').map(i => i.item).join(', ') || '검사 불합격',
      detectedDate: insp.inspectionDate,
      inspector: insp.inspectorName,
      status: insp.ncrInfo?.status === '처리완료' ? (insp.ncrInfo.action || '처리완료') : '처리대기',
      vendor: insp.vendor,
      // ★ 결재 정보
      approvalStatus: insp.ncrInfo?.approvalStatus || '결재대기',
      approvalLine: insp.ncrInfo?.approvalLine || {
        type: 'APR-3LINE',
        roles: [
          { id: 'writer', label: '작성', name: insp.inspectorName, date: insp.inspectionDate, status: 'approved' },
          { id: 'reviewer', label: '검토', name: '', date: '', status: 'pending' },
          { id: 'approver', label: '승인', name: '', date: '', status: 'pending' },
        ]
      },
      // ★ 프로세스 플로우
      processFlow: {
        trigger: insp.type === 'incoming' ? '수입검사불합격' : insp.type === 'process' ? '중간검사불합격' : '제품검사불합격',
        currentStep: '처리방법결정대기',
        nextAction: '처리결정후결재',
      },
    }))
  ];

  const pendingDefects = allDefects.filter(d => d.status === '처리대기');
  const processedDefects = allDefects.filter(d => d.status !== '처리대기');
  const reworkDefects = allDefects.filter(d => d.status === '재작업');
  const disposeDefects = allDefects.filter(d => d.status === '폐기');

  // 검색 및 탭 필터링
  const filteredDefects = allDefects
    .filter(d => {
      if (activeTab === 'pending') return d.status === '처리대기';
      if (activeTab === 'processed') return d.status !== '처리대기';
      return true;
    })
    .filter(d => {
      if (!searchTerm) return true;
      const term = searchTerm.toLowerCase();
      return (d.ncrNo || d.defectNo || '').toLowerCase().includes(term) ||
        (d.itemName || '').toLowerCase().includes(term) ||
        (d.sourceLot || '').toLowerCase().includes(term) ||
        (d.defectReason || '').toLowerCase().includes(term);
    })
    .sort((a, b) => {
      const aId = typeof a.id === 'string' ? parseInt(a.id.replace(/\D/g, '')) : a.id;
      const bId = typeof b.id === 'string' ? parseInt(b.id.replace(/\D/g, '')) : b.id;
      return bId - aId;
    });

  // 선택 핸들러
  const handleSelect = (id) => {
    setSelectedIds(prev => prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]);
  };
  const handleSelectAll = (e) => {
    if (e.target.checked) {
      setSelectedIds(filteredDefects.map(d => d.id));
    } else {
      setSelectedIds([]);
    }
  };
  const isSelected = (id) => selectedIds.includes(id);
  const hasSelection = selectedIds.length > 0;
  const isAllSelected = filteredDefects.length > 0 && selectedIds.length === filteredDefects.length;
  const isMultiSelect = selectedIds.length > 1;

  const handleOpenAction = (defect) => {
    setSelectedDefect(defect);
    setActionForm({
      action: 'rework',
      handler: '',
      note: '',
    });
    setShowActionModal(true);
  };

  const handleProcessDefect = () => {
    if (!actionForm.handler) {
      alert('처리자를 입력해주세요.');
      return;
    }

    const actionLabels = {
      rework: '재작업',
      dispose: '폐기',
      accept: '특채(조건부합격)',
    };

    const processedData = {
      ...selectedDefect,
      status: actionLabels[actionForm.action],
      action: actionForm.action,
      handler: actionForm.handler,
      processedDate: new Date().toISOString().split('T')[0],
      processNote: actionForm.note,
    };

    if (actionForm.action === 'rework') {
      onRework?.(processedData);
      alert(`🔄 재작업 처리되었습니다.\n\n부적합번호: ${selectedDefect.defectNo}\n재작업 후 재검사가 필요합니다.`);
    } else if (actionForm.action === 'dispose') {
      onDispose?.(processedData);
      alert(`🗑️ 폐기 처리되었습니다.\n\n부적합번호: ${selectedDefect.defectNo}\n재고에서 차감됩니다.`);
    } else {
      onSave?.(processedData);
      alert(`✅ 특채 처리되었습니다.\n\n부적합번호: ${selectedDefect.defectNo}\n조건부로 사용 가능합니다.`);
    }

    setShowActionModal(false);
    setSelectedDefect(null);
  };

  const getStatusBadge = (status) => {
    const styles = {
      '처리대기': 'bg-red-100 text-red-700',
      '재작업': 'bg-yellow-100 text-yellow-700',
      '폐기': 'bg-gray-100 text-gray-700',
      '특채(조건부합격)': 'bg-blue-100 text-blue-700',
    };
    return styles[status] || 'bg-gray-100 text-gray-700';
  };

  const getSourceBadge = (sourceType) => {
    const styles = {
      '수입검사': 'bg-blue-100 text-blue-700',
      '중간검사': 'bg-purple-100 text-purple-700',
      '제품검사': 'bg-green-100 text-green-700',
    };
    return styles[sourceType] || 'bg-gray-100 text-gray-700';
  };

  return (
    <div className="space-y-6">
      {/* 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <XCircle className="w-6 h-6 text-blue-500" />
          부적합품 목록
        </h1>
        <div className="flex items-center justify-end">
          <Button variant="primary" onClick={() => alert('NCR 등록 화면으로 이동')}>
            <Plus className="w-4 h-4" /> NCR 등록
          </Button>
        </div>
      </div>

      {/* 리포트 카드 4개 */}
      <div className="grid grid-cols-4 gap-4">
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">처리대기</p>
          <p className="text-2xl font-bold text-red-600">{pendingDefects.length}건</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">재작업</p>
          <p className="text-2xl font-bold text-yellow-600">{reworkDefects.length}건</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">폐기</p>
          <p className="text-2xl font-bold">{disposeDefects.length}건</p>
        </div>
        <div className="bg-white rounded-xl p-4 border">
          <p className="text-sm text-gray-500 mb-1">처리완료</p>
          <p className="text-2xl font-bold text-green-600">{processedDefects.length}건</p>
        </div>
      </div>

      {/* 검색바 */}
      <div className="relative">
        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
        <input
          type="text"
          placeholder="NCR번호, 품목명, LOT번호, 불량원인 검색..."
          className="w-full pl-12 pr-4 py-3 border rounded-xl"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
        />
      </div>

      {/* 탭 */}
      <div className="flex items-center gap-2">
        {[
          { id: 'all', label: '전체', count: allDefects.length },
          { id: 'pending', label: '처리대기', count: pendingDefects.length },
          { id: 'processed', label: '처리완료', count: processedDefects.length },
        ].map(tab => (
          <button
            key={tab.id}
            onClick={() => { setActiveTab(tab.id); setSelectedIds([]); }}
            className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-full border transition-colors ${activeTab === tab.id
                ? 'bg-gray-900 text-white border-gray-900'
                : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
              }`}
          >
            {tab.label} ({tab.count})
          </button>
        ))}
      </div>

      {/* 선택 삭제 버튼 */}
      {isMultiSelect && (
        <div className="flex justify-end">
          <Button variant="outline" size="sm" onClick={() => alert(`${selectedIds.length}건 선택 삭제`)}>
            선택 삭제 ({selectedIds.length})
          </Button>
        </div>
      )}

      {/* 테이블 */}
      <Card>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 border-b">
              <tr>
                <th className="p-3 text-left w-10">
                  <input type="checkbox" checked={isAllSelected} onChange={handleSelectAll} />
                </th>
                <th className="p-3 text-left">NCR번호</th>
                <th className="p-3 text-left">발생구분</th>
                <th className="p-3 text-left">검사LOT</th>
                <th className="p-3 text-left">품목명</th>
                <th className="p-3 text-right">수량</th>
                <th className="p-3 text-left">불량원인</th>
                <th className="p-3 text-center">발생일</th>
                <th className="p-3 text-center">처리상태</th>
                {hasSelection && <th className="p-3 text-center">작업</th>}
              </tr>
            </thead>
            <tbody>
              {filteredDefects.length === 0 ? (
                <tr>
                  <td colSpan={hasSelection ? 10 : 9} className="p-8 text-center text-gray-500">
                    데이터가 없습니다.
                  </td>
                </tr>
              ) : (
                filteredDefects.map(defect => (
                  <tr key={defect.id} className={`border-b hover:bg-gray-50 ${isSelected(defect.id) ? 'bg-blue-50' : ''}`}>
                    <td className="p-3" onClick={e => e.stopPropagation()}>
                      <input type="checkbox" checked={isSelected(defect.id)} onChange={() => handleSelect(defect.id)} />
                    </td>
                    <td className="p-3 font-mono text-red-600 font-medium">{defect.ncrNo || defect.defectNo}</td>
                    <td className="p-3">
                      <span className={`px-2 py-0.5 rounded text-xs font-medium ${getSourceBadge(defect.sourceType)}`}>
                        {defect.sourceType}
                      </span>
                    </td>
                    <td className="p-3 font-mono text-gray-600">{defect.sourceLot}</td>
                    <td className="p-3 text-gray-900">{defect.itemName}</td>
                    <td className="p-3 text-right">{defect.quantity} {defect.unit}</td>
                    <td className="p-3 text-gray-600 max-w-[200px] truncate" title={defect.defectReason}>
                      {defect.defectReason}
                    </td>
                    <td className="p-3 text-center text-gray-500">{defect.detectedDate}</td>
                    <td className="p-3 text-center">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusBadge(defect.status)}`}>
                        {defect.status}
                      </span>
                    </td>
                    {hasSelection && (
                      <td className="p-3 text-center" onClick={e => e.stopPropagation()}>
                        {isSelected(defect.id) && (
                          <div className="flex gap-1 justify-center">
                            {defect.status === '처리대기' && (
                              <Button size="xs" variant="outline" onClick={() => handleOpenAction(defect)}>처리</Button>
                            )}
                            <Button size="xs" variant="outline" onClick={() => alert(`NCR 출력: ${defect.ncrNo || defect.defectNo}`)}>출력</Button>
                          </div>
                        )}
                      </td>
                    )}
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </Card>

      {/* 처리 모달 */}
      {showActionModal && selectedDefect && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b flex justify-between items-center sticky top-0 bg-white z-10">
              <h3 className="text-lg font-bold">부적합품 처리</h3>
              <button onClick={() => setShowActionModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6 space-y-4">
              {/* 부적합 정보 */}
              <div className="bg-red-50 rounded-lg p-4">
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div><span className="text-gray-500">부적합번호:</span> <span className="font-mono font-medium">{selectedDefect.defectNo}</span></div>
                  <div><span className="text-gray-500">발생구분:</span> <span>{selectedDefect.sourceType}</span></div>
                  <div><span className="text-gray-500">품목:</span> <span>{selectedDefect.itemName}</span></div>
                  <div><span className="text-gray-500">수량:</span> <span className="font-medium">{selectedDefect.quantity} {selectedDefect.unit}</span></div>
                  <div className="col-span-2"><span className="text-gray-500">불량원인:</span> <span className="text-red-700">{selectedDefect.defectReason}</span></div>
                </div>
              </div>

              {/* 처리 방법 선택 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">처리 방법</label>
                <div className="grid grid-cols-3 gap-3">
                  {[
                    { value: 'rework', label: '재작업', icon: '🔄', color: 'yellow' },
                    { value: 'dispose', label: '폐기', icon: '🗑️', color: 'gray' },
                    { value: 'accept', label: '특채', icon: '✅', color: 'blue' },
                  ].map(option => (
                    <button
                      key={option.value}
                      onClick={() => setActionForm(prev => ({ ...prev, action: option.value }))}
                      className={`p-3 border rounded-lg text-center transition-colors ${actionForm.action === option.value
                          ? `border-${option.color}-500 bg-${option.color}-50 ring-2 ring-${option.color}-500`
                          : 'border-gray-200 hover:border-gray-300'
                        }`}
                    >
                      <div className="text-2xl">{option.icon}</div>
                      <div className="text-sm font-medium mt-1">{option.label}</div>
                    </button>
                  ))}
                </div>
              </div>

              {/* 처리자 및 비고 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  처리자 <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={actionForm.handler}
                  onChange={(e) => setActionForm(prev => ({ ...prev, handler: e.target.value }))}
                  placeholder="처리자 이름"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">처리 사유 / 비고</label>
                <textarea
                  value={actionForm.note}
                  onChange={(e) => setActionForm(prev => ({ ...prev, note: e.target.value }))}
                  rows={3}
                  placeholder="처리 사유 및 특이사항 기록"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
            </div>
            <div className="p-4 border-t flex justify-end gap-2">
              <button
                onClick={() => setShowActionModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleProcessDefect}
                className={`px-4 py-2 text-white rounded-lg ${actionForm.action === 'dispose' ? 'bg-gray-500 hover:bg-gray-600' :
                    actionForm.action === 'rework' ? 'bg-yellow-500 hover:bg-yellow-600' :
                      'bg-blue-500 hover:bg-blue-600'
                  }`}
              >
                처리 확정
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ★ NCR 결재 모달 (APR-3LINE) */}
      {showApprovalModal && selectedForApproval && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-lg">
            <div className="p-4 border-b flex justify-between items-center">
              <h3 className="text-lg font-bold">NCR 결재</h3>
              <button onClick={() => setShowApprovalModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6 space-y-4">
              {/* NCR 정보 */}
              <div className="bg-red-50 rounded-lg p-4">
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div><span className="text-gray-500">NCR번호:</span> <span className="font-mono font-medium text-red-600">{selectedForApproval.ncrNo || selectedForApproval.defectNo}</span></div>
                  <div><span className="text-gray-500">발생구분:</span> <span>{selectedForApproval.sourceType}</span></div>
                  <div><span className="text-gray-500">품목:</span> <span className="font-medium">{selectedForApproval.itemName}</span></div>
                  <div><span className="text-gray-500">수량:</span> <span>{selectedForApproval.quantity} {selectedForApproval.unit}</span></div>
                  <div>
                    <span className="text-gray-500">처리방식:</span>
                    <span className={`ml-1 px-2 py-0.5 rounded text-xs font-medium ${getStatusBadge(selectedForApproval.status)}`}>
                      {selectedForApproval.status}
                    </span>
                  </div>
                  <div><span className="text-gray-500">처리자:</span> <span>{selectedForApproval.handler}</span></div>
                </div>
                <div className="mt-2 pt-2 border-t border-red-200">
                  <span className="text-gray-500 text-sm">불량원인:</span>
                  <span className="text-red-700 text-sm ml-1">{selectedForApproval.defectReason}</span>
                </div>
              </div>

              {/* 결재라인 표시 (APR-3LINE: 작성 → 검토 → 승인) */}
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2">결재라인 (3단계)</h4>
                <div className="flex items-center justify-center gap-2">
                  {(selectedForApproval.approvalLine?.roles || [
                    { id: 'writer', label: '작성', name: '', status: 'pending' },
                    { id: 'reviewer', label: '검토', name: '', status: 'pending' },
                    { id: 'approver', label: '승인', name: '', status: 'pending' },
                  ]).map((role, idx, arr) => (
                    <React.Fragment key={role.id}>
                      <div className={`text-center p-3 rounded-lg border-2 min-w-[80px] ${role.status === 'approved' ? 'border-green-500 bg-green-50' :
                          role.status === 'pending' && idx === arr.findIndex(r => r.status === 'pending')
                            ? 'border-blue-500 bg-blue-50' : 'border-gray-200 bg-gray-50'
                        }`}>
                        <div className="text-xs text-gray-500 mb-1">{role.label}</div>
                        <div className="font-medium text-sm">{role.name || '-'}</div>
                        <div className="text-xs text-gray-400 mt-1">
                          {role.status === 'approved' ? role.date : role.status === 'pending' ? '대기' : ''}
                        </div>
                        {role.status === 'approved' && (
                          <CheckCircle className="w-4 h-4 text-green-600 mx-auto mt-1" />
                        )}
                      </div>
                      {idx < arr.length - 1 && (
                        <ChevronRight className="w-5 h-5 text-gray-400" />
                      )}
                    </React.Fragment>
                  ))}
                </div>
              </div>

              {/* 현재 결재자 입력 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  결재자 <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  id="ncr-approver-name"
                  placeholder="결재자 이름"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>

              {/* 프로세스 플로우 정보 */}
              <div className="bg-gray-50 rounded-lg p-3 text-sm">
                <div className="flex items-center gap-2 text-gray-600">
                  <span className="font-medium">후속처리:</span>
                  <span className="px-2 py-0.5 bg-orange-100 text-orange-700 rounded text-xs">
                    {selectedForApproval.status === '폐기' && selectedForApproval.sourceType === '수입검사' ? '업체 클레임 발행' :
                      selectedForApproval.status === '재작업' ? '재작업 지시' :
                        selectedForApproval.status === '특채(조건부합격)' ? '조건부 사용 허가' : '처리 완료'}
                  </span>
                </div>
                <div className="text-xs text-gray-500 mt-1">
                  결재완료 시 해당 후속처리가 자동으로 진행됩니다.
                </div>
              </div>
            </div>
            <div className="p-4 border-t flex justify-end gap-2">
              <button
                onClick={() => setShowApprovalModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={() => {
                  const approverInput = document.getElementById('ncr-approver-name');
                  if (!approverInput?.value) {
                    alert('결재자 이름을 입력해주세요.');
                    return;
                  }
                  handleNCRApproval(selectedForApproval, approverInput.value);
                }}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
              >
                결재승인
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============================================================
// 배송현황 컴포넌트
// ============================================================
const DeliveryStatusList = ({
  shipments = [],
  onUpdateStatus,
  onNavigate
}) => {
  const [activeTab, setActiveTab] = useState('in-progress');
  const [selectedShipment, setSelectedShipment] = useState(null);
  const [showDetailModal, setShowDetailModal] = useState(false);

  // 배송 진행중
  const inProgressShipments = shipments.filter(s =>
    s.status === '출하준비' || s.status === '상차완료' || s.status === '배송중'
  );

  // 배송완료
  const completedShipments = shipments.filter(s => s.status === '배송완료');

  // 금일 배송
  const todayShipments = shipments.filter(s =>
    s.deliveryDate === new Date().toISOString().split('T')[0]
  );

  const getStatusBadge = (status) => {
    const styles = {
      '출고지시': 'bg-gray-100 text-gray-700',
      '출하준비': 'bg-yellow-100 text-yellow-700',
      '상차완료': 'bg-blue-100 text-blue-700',
      '배송중': 'bg-purple-100 text-purple-700',
      '배송완료': 'bg-green-100 text-green-700',
    };
    return styles[status] || 'bg-gray-100 text-gray-700';
  };

  const getStatusProgress = (status) => {
    const steps = ['출고지시', '출하준비', '상차완료', '배송중', '배송완료'];
    const currentIndex = steps.indexOf(status);
    return { current: currentIndex + 1, total: steps.length };
  };

  const handleOpenDetail = (shipment) => {
    setSelectedShipment(shipment);
    setShowDetailModal(true);
  };

  const handleUpdateDeliveryStatus = (shipmentId, newStatus) => {
    onUpdateStatus?.(shipmentId, newStatus);
    if (newStatus === '배송완료') {
      alert('✅ 배송이 완료되었습니다.');
    }
    setShowDetailModal(false);
  };

  return (
    <div className="space-y-4">
      {/* 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <Truck className="w-6 h-6 text-blue-500" />
          배송현황
        </h1>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-5 gap-4">
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">금일배송</div>
          <div className="text-2xl font-bold text-blue-600 mt-1">{todayShipments.length}</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">출하준비</div>
          <div className="text-2xl font-bold text-yellow-600 mt-1">
            {shipments.filter(s => s.status === '출하준비').length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">배송중</div>
          <div className="text-2xl font-bold text-purple-600 mt-1">
            {shipments.filter(s => s.status === '배송중').length}
          </div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">배송완료</div>
          <div className="text-2xl font-bold text-green-600 mt-1">{completedShipments.length}</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <div className="text-sm text-gray-500">전체</div>
          <div className="text-2xl font-bold text-gray-900 mt-1">{shipments.length}</div>
        </div>
      </div>

      {/* 배송중 카드 뷰 */}
      {inProgressShipments.length > 0 && (
        <div className="bg-white rounded-lg shadow-sm border p-4">
          <h3 className="text-sm font-medium text-gray-700 mb-3">🚚 현재 배송중</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {inProgressShipments.slice(0, 6).map(shipment => {
              const progress = getStatusProgress(shipment.status);
              return (
                <div
                  key={shipment.id}
                  onClick={() => handleOpenDetail(shipment)}
                  className="border rounded-lg p-4 cursor-pointer hover:shadow-md transition-shadow"
                >
                  <div className="flex justify-between items-start mb-3">
                    <div>
                      <div className="text-sm font-medium text-gray-900">{shipment.customerName}</div>
                      <div className="text-xs text-gray-500">{shipment.siteName}</div>
                    </div>
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusBadge(shipment.status)}`}>
                      {shipment.status}
                    </span>
                  </div>
                  <div className="text-xs text-gray-500 mb-2">
                    분할번호: <span className="font-mono">{shipment.splitNo}</span>
                  </div>
                  {/* 진행 바 */}
                  <div className="relative pt-1">
                    <div className="flex mb-2 items-center justify-between">
                      <span className="text-xs text-gray-500">진행상태</span>
                      <span className="text-xs font-semibold text-blue-600">
                        {Math.round((progress.current / progress.total) * 100)}%
                      </span>
                    </div>
                    <div className="overflow-hidden h-2 text-xs flex rounded bg-gray-200">
                      <div
                        style={{ width: `${(progress.current / progress.total) * 100}%` }}
                        className="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-blue-500"
                      />
                    </div>
                  </div>
                  <div className="mt-3 text-xs text-gray-500">
                    <div className="flex items-center gap-1">
                      <Truck className="w-3 h-3" />
                      {shipment.driver || '미정'} / {shipment.vehicle || '미정'}
                    </div>
                    <div className="flex items-center gap-1 mt-1">
                      <Calendar className="w-3 h-3" />
                      배송예정: {shipment.deliveryDate || '-'}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* 탭 (칩 형태) */}
      <div className="flex gap-2 mb-4">
        {[
          { id: 'in-progress', label: '진행중', count: inProgressShipments.length },
          { id: 'completed', label: '배송완료', count: completedShipments.length },
          { id: 'today', label: '금일배송', count: todayShipments.length },
          { id: 'all', label: '전체', count: shipments.length },
        ].map(tab => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${activeTab === tab.id
                ? 'bg-blue-600 text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
          >
            {tab.label} ({tab.count})
          </button>
        ))}
      </div>

      {/* 테이블 */}
      <div className="bg-white rounded-lg shadow-sm border">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">분할번호</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">고객사</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">현장</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">배송지</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">배송예정일</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">차량/기사</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {(() => {
                const filteredList =
                  activeTab === 'in-progress' ? inProgressShipments :
                    activeTab === 'completed' ? completedShipments :
                      activeTab === 'today' ? todayShipments :
                        shipments;

                return filteredList.length === 0 ? (
                  <tr>
                    <td colSpan="8" className="px-4 py-8 text-center text-gray-500">
                      데이터가 없습니다.
                    </td>
                  </tr>
                ) : (
                  filteredList.map(shipment => (
                    <tr key={shipment.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3 text-sm font-mono text-blue-600 font-medium">{shipment.splitNo}</td>
                      <td className="px-4 py-3 text-sm text-gray-900">{shipment.customerName}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{shipment.siteName}</td>
                      <td className="px-4 py-3 text-sm text-gray-600 max-w-[200px] truncate" title={shipment.address}>
                        {shipment.address || '-'}
                      </td>
                      <td className="px-4 py-3 text-sm text-center text-gray-500">{shipment.deliveryDate || '-'}</td>
                      <td className="px-4 py-3 text-sm text-center">
                        {shipment.driver || '-'} / {shipment.vehicle || '-'}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusBadge(shipment.status)}`}>
                          {shipment.status}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-center">
                        <button
                          onClick={() => handleOpenDetail(shipment)}
                          className="px-3 py-1 bg-gray-100 text-gray-700 text-xs rounded hover:bg-gray-200"
                        >
                          상세
                        </button>
                      </td>
                    </tr>
                  ))
                );
              })()}
            </tbody>
          </table>
        </div>
      </div>

      {/* 상세 모달 */}
      {showDetailModal && selectedShipment && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b flex justify-between items-center sticky top-0 bg-white z-10">
              <h3 className="text-lg font-bold">배송 상세</h3>
              <button onClick={() => setShowDetailModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6 space-y-4">
              {/* 배송 진행 상태 */}
              <div className="bg-blue-50 rounded-lg p-4">
                <div className="flex items-center justify-between mb-4">
                  {['출고지시', '출하준비', '상차완료', '배송중', '배송완료'].map((step, idx) => {
                    const progress = getStatusProgress(selectedShipment.status);
                    const isActive = idx < progress.current;
                    const isCurrent = idx === progress.current - 1;
                    return (
                      <div key={step} className="flex flex-col items-center">
                        <div className={`w-8 h-8 rounded-full flex items-center justify-center ${isActive ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-400'
                          } ${isCurrent ? 'ring-2 ring-blue-300' : ''}`}>
                          {isActive ? <Check className="w-4 h-4" /> : idx + 1}
                        </div>
                        <span className={`text-xs mt-1 ${isActive ? 'text-blue-600 font-medium' : 'text-gray-400'}`}>
                          {step}
                        </span>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* 배송 정보 */}
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-gray-500">분할번호:</span>
                  <span className="ml-2 font-mono font-medium">{selectedShipment.splitNo}</span>
                </div>
                <div>
                  <span className="text-gray-500">고객사:</span>
                  <span className="ml-2">{selectedShipment.customerName}</span>
                </div>
                <div>
                  <span className="text-gray-500">현장명:</span>
                  <span className="ml-2">{selectedShipment.siteName}</span>
                </div>
                <div>
                  <span className="text-gray-500">배송예정일:</span>
                  <span className="ml-2">{selectedShipment.deliveryDate || '-'}</span>
                </div>
                <div className="col-span-2">
                  <span className="text-gray-500">배송지:</span>
                  <span className="ml-2">{selectedShipment.address || '-'}</span>
                </div>
                <div>
                  <span className="text-gray-500">차량:</span>
                  <span className="ml-2">{selectedShipment.vehicle || '-'}</span>
                </div>
                <div>
                  <span className="text-gray-500">기사:</span>
                  <span className="ml-2">{selectedShipment.driver || '-'}</span>
                </div>
              </div>

              {/* 상태 변경 버튼 */}
              {selectedShipment.status !== '배송완료' && (
                <div className="pt-4 border-t">
                  <label className="block text-sm font-medium text-gray-700 mb-2">배송 상태 변경</label>
                  <div className="flex gap-2 flex-wrap">
                    {['출하준비', '상차완료', '배송중', '배송완료'].map(status => (
                      <button
                        key={status}
                        onClick={() => handleUpdateDeliveryStatus(selectedShipment.id, status)}
                        disabled={getStatusProgress(status).current <= getStatusProgress(selectedShipment.status).current}
                        className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${getStatusProgress(status).current <= getStatusProgress(selectedShipment.status).current
                            ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                            : status === '배송완료'
                              ? 'bg-green-500 text-white hover:bg-green-600'
                              : 'bg-blue-500 text-white hover:bg-blue-600'
                          }`}
                      >
                        {status}
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>
            <div className="p-4 border-t flex justify-end">
              <button
                onClick={() => setShowDetailModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                닫기
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============================================================
// 납품확인서 문서 컴포넌트 (출하완료 후 발행)
// ============================================================
const DeliveryConfirmationDoc = ({
  shipment,
  order,
  customer,
  onClose,
  onPrint
}) => {
  if (!shipment || !order) return null;

  const today = new Date().toLocaleDateString('ko-KR');
  const lotNo = shipment.lotNo || `KD-WE-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-01-(${shipment.splitIndex || 1})`;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] overflow-auto">
        {/* 문서 헤더 */}
        <div className="p-6 border-b flex justify-between items-center bg-gray-50">
          <h2 className="text-xl font-bold">납품확인서</h2>
          <div className="flex gap-2">
            <button
              onClick={onPrint}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
            >
              <Printer className="w-4 h-4" />
              인쇄
            </button>
            <button
              onClick={onClose}
              className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100"
            >
              닫기
            </button>
          </div>
        </div>

        {/* 문서 내용 */}
        <div className="p-6" id="delivery-confirmation-print">
          {/* 회사 로고 및 제목 */}
          <div className="flex justify-between items-start mb-6 border-b pb-4">
            <div>
              <h1 className="text-2xl font-bold text-gray-800">KD 경동기업</h1>
              <p className="text-sm text-gray-500 mt-1">
                전화: 031-938-5130 | 팩스: 02-6911-6315 | 이메일: kd5130@naver.com
              </p>
            </div>
            <div className="text-right">
              <h2 className="text-xl font-bold">납 품 확 인 서</h2>
              <p className="text-sm mt-2">로트번호: <span className="font-mono font-bold">{lotNo}</span></p>
            </div>
          </div>

          {/* 기본 정보 테이블 */}
          <div className="grid grid-cols-2 gap-6 mb-6">
            <div className="border rounded-lg overflow-hidden">
              <div className="bg-gray-100 px-3 py-2 font-medium text-sm">신청업체</div>
              <table className="w-full text-sm">
                <tbody>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2 w-24">발주일</td>
                    <td className="px-3 py-2">{order.orderDate || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">발주처</td>
                    <td className="px-3 py-2">{customer?.name || order.customerName || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">발주 담당자</td>
                    <td className="px-3 py-2">{order.contactPerson || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">담당자 연락처</td>
                    <td className="px-3 py-2">{order.contactPhone || '-'}</td>
                  </tr>
                </tbody>
              </table>
            </div>

            <div className="border rounded-lg overflow-hidden">
              <div className="bg-gray-100 px-3 py-2 font-medium text-sm">신청내용 / 납품정보</div>
              <table className="w-full text-sm">
                <tbody>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2 w-24">현장명</td>
                    <td className="px-3 py-2 font-medium">{order.siteName || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">납기요청일</td>
                    <td className="px-3 py-2">{order.dueDate || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">출고일</td>
                    <td className="px-3 py-2">{shipment.shipDate || today}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">셔터총수량</td>
                    <td className="px-3 py-2">{shipment.totalQty || order.totalQty || '-'} 개소</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* 배송지 주소 */}
          <div className="mb-6 p-3 bg-blue-50 rounded-lg">
            <span className="text-sm font-medium text-blue-800">배송지 주소: </span>
            <span className="text-sm text-blue-900">{order.deliveryAddress || order.siteAddress || '-'}</span>
          </div>

          {/* 부호별 자재내역 */}
          <div className="mb-6">
            <h3 className="font-medium mb-3 text-gray-700">1. 부호별 자재내역</h3>
            <div className="border rounded-lg overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-yellow-100">
                  <tr>
                    <th className="px-3 py-2 border-r">일련번호</th>
                    <th className="px-3 py-2 border-r">종류</th>
                    <th className="px-3 py-2 border-r">도면부호</th>
                    <th className="px-3 py-2 border-r" colSpan="2">오픈사이즈(mm)</th>
                    <th className="px-3 py-2 border-r" colSpan="2">제작사이즈(mm)</th>
                    <th className="px-3 py-2 border-r">가이드레일유형</th>
                    <th className="px-3 py-2 border-r">샤프트(인치)</th>
                    <th className="px-3 py-2 border-r">케이스(규격)</th>
                    <th className="px-3 py-2" colSpan="2">모터</th>
                  </tr>
                  <tr className="bg-yellow-50">
                    <th className="px-3 py-1 border-r"></th>
                    <th className="px-3 py-1 border-r"></th>
                    <th className="px-3 py-1 border-r"></th>
                    <th className="px-3 py-1 border-r text-xs">가로</th>
                    <th className="px-3 py-1 border-r text-xs">세로</th>
                    <th className="px-3 py-1 border-r text-xs">가로</th>
                    <th className="px-3 py-1 border-r text-xs">세로</th>
                    <th className="px-3 py-1 border-r"></th>
                    <th className="px-3 py-1 border-r"></th>
                    <th className="px-3 py-1 border-r"></th>
                    <th className="px-3 py-1 border-r text-xs">브라켓트</th>
                    <th className="px-3 py-1 text-xs">용량(KG)</th>
                  </tr>
                </thead>
                <tbody>
                  {(order.items || []).slice(0, 5).map((item, idx) => (
                    <tr key={idx} className="border-t">
                      <td className="px-3 py-2 text-center border-r">{String(idx + 1).padStart(2, '0')}</td>
                      <td className="px-3 py-2 text-center border-r">{item.productType || '와이어'}</td>
                      <td className="px-3 py-2 text-center border-r">{item.drawingNo || `4층 FSS${idx + 1}`}</td>
                      <td className="px-3 py-2 text-center border-r">{item.openWidth || '-'}</td>
                      <td className="px-3 py-2 text-center border-r">{item.openHeight || '-'}</td>
                      <td className="px-3 py-2 text-center border-r">{item.prodWidth || '-'}</td>
                      <td className="px-3 py-2 text-center border-r">{item.prodHeight || '-'}</td>
                      <td className="px-3 py-2 text-center border-r">{item.guideRailType || '벽면형(120-70)'}</td>
                      <td className="px-3 py-2 text-center border-r">{item.shaftSize || '5'}</td>
                      <td className="px-3 py-2 text-center border-r">{item.caseSpec || '500-330'}</td>
                      <td className="px-3 py-2 text-center border-r">{item.bracketSpec || '380-180'}</td>
                      <td className="px-3 py-2 text-center">{item.motorCapacity || '300'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* 2. 부호별 절곡내역 */}
          <div className="mb-6">
            <h3 className="font-bold mb-2 text-sm">2. 부호별 절곡내역</h3>
            <div className="overflow-x-auto">
              <table className="w-full border text-xs">
                <thead>
                  <tr className="bg-gray-100">
                    <th rowSpan="2" className="px-2 py-1 border text-center">도면부호</th>
                    <th colSpan="7" className="px-2 py-1 border text-center bg-blue-50">케이스(셔터박스) 길이별 수량</th>
                    <th colSpan="5" className="px-2 py-1 border text-center bg-green-50">가이드레일 길이별 수량</th>
                  </tr>
                  <tr className="bg-gray-50">
                    {/* 케이스 컬럼 */}
                    <th className="px-2 py-1 border text-center">규격</th>
                    <th className="px-2 py-1 border text-center">1219</th>
                    <th className="px-2 py-1 border text-center">2438</th>
                    <th className="px-2 py-1 border text-center">3000</th>
                    <th className="px-2 py-1 border text-center">3500</th>
                    <th className="px-2 py-1 border text-center">4000</th>
                    <th className="px-2 py-1 border text-center">4150</th>
                    {/* 가이드레일 컬럼 */}
                    <th className="px-2 py-1 border text-center">유형</th>
                    <th className="px-2 py-1 border text-center">2438</th>
                    <th className="px-2 py-1 border text-center">3000</th>
                    <th className="px-2 py-1 border text-center">3500</th>
                    <th className="px-2 py-1 border text-center">4000</th>
                  </tr>
                </thead>
                <tbody>
                  {(order.items || []).map((item, idx) => {
                    const drawingNo = item.productionSpec?.drawingNo || item.drawingNo || `FSS${idx + 1}`;
                    const caseSpec = item.productionSpec?.caseSpec || item.caseSpec || '500-330';
                    const grType = item.productionSpec?.guideRailType || item.guideRailType || '벽면형';
                    const prodWidth = parseInt(item.prodWidth) || parseInt(item.openWidth) || 0;

                    // 케이스 길이 결정 (prodWidth 기준)
                    const caseLength = prodWidth <= 1219 ? 1219 :
                      prodWidth <= 2438 ? 2438 :
                        prodWidth <= 3000 ? 3000 :
                          prodWidth <= 3500 ? 3500 :
                            prodWidth <= 4000 ? 4000 : 4150;

                    // 가이드레일 길이 결정 (prodHeight 기준)
                    const prodHeight = parseInt(item.prodHeight) || parseInt(item.openHeight) || 0;
                    const grLength = prodHeight <= 2438 ? 2438 :
                      prodHeight <= 3000 ? 3000 :
                        prodHeight <= 3500 ? 3500 : 4000;

                    return (
                      <tr key={idx} className="border-t hover:bg-gray-50">
                        <td className="px-2 py-1 border text-center font-medium">{drawingNo}</td>
                        {/* 케이스 데이터 */}
                        <td className="px-2 py-1 border text-center text-xs">{caseSpec}</td>
                        <td className="px-2 py-1 border text-center">{caseLength === 1219 ? 1 : '-'}</td>
                        <td className="px-2 py-1 border text-center">{caseLength === 2438 ? 1 : '-'}</td>
                        <td className="px-2 py-1 border text-center">{caseLength === 3000 ? 1 : '-'}</td>
                        <td className="px-2 py-1 border text-center">{caseLength === 3500 ? 1 : '-'}</td>
                        <td className="px-2 py-1 border text-center">{caseLength === 4000 ? 1 : '-'}</td>
                        <td className="px-2 py-1 border text-center">{caseLength === 4150 ? 1 : '-'}</td>
                        {/* 가이드레일 데이터 */}
                        <td className="px-2 py-1 border text-center text-xs">{grType}</td>
                        <td className="px-2 py-1 border text-center">{grLength === 2438 ? 2 : '-'}</td>
                        <td className="px-2 py-1 border text-center">{grLength === 3000 ? 2 : '-'}</td>
                        <td className="px-2 py-1 border text-center">{grLength === 3500 ? 2 : '-'}</td>
                        <td className="px-2 py-1 border text-center">{grLength === 4000 ? 2 : '-'}</td>
                      </tr>
                    );
                  })}
                  {/* 소계 행 */}
                  <tr className="bg-yellow-50 font-bold border-t-2">
                    <td className="px-2 py-1 border text-center">소계</td>
                    <td className="px-2 py-1 border text-center">-</td>
                    {[1219, 2438, 3000, 3500, 4000, 4150].map(len => {
                      const count = (order.items || []).filter(item => {
                        const pw = parseInt(item.prodWidth) || parseInt(item.openWidth) || 0;
                        const cl = pw <= 1219 ? 1219 : pw <= 2438 ? 2438 : pw <= 3000 ? 3000 : pw <= 3500 ? 3500 : pw <= 4000 ? 4000 : 4150;
                        return cl === len;
                      }).length;
                      return <td key={len} className="px-2 py-1 border text-center">{count || '-'}</td>;
                    })}
                    <td className="px-2 py-1 border text-center">-</td>
                    {[2438, 3000, 3500, 4000].map(len => {
                      const count = (order.items || []).filter(item => {
                        const ph = parseInt(item.prodHeight) || parseInt(item.openHeight) || 0;
                        const gl = ph <= 2438 ? 2438 : ph <= 3000 ? 3000 : ph <= 3500 ? 3500 : 4000;
                        return gl === len;
                      }).length * 2; // 가이드레일은 좌우 2개
                      return <td key={len} className="px-2 py-1 border text-center">{count || '-'}</td>;
                    })}
                  </tr>
                </tbody>
              </table>
            </div>

            {/* 부자재 (상부덮개, 하단마감재, 연기차단재) 요약 */}
            <div className="mt-3 grid grid-cols-3 gap-4">
              <div className="border rounded p-2 bg-gray-50">
                <div className="text-xs text-gray-600 mb-1">상부덮개 (1219-389)</div>
                <div className="font-medium">{(order.items || []).length}개</div>
              </div>
              <div className="border rounded p-2 bg-gray-50">
                <div className="text-xs text-gray-600 mb-1">하단마감재</div>
                <div className="font-medium">
                  {(order.items || []).reduce((acc, item) => {
                    const pw = parseInt(item.prodWidth) || parseInt(item.openWidth) || 0;
                    return acc + (pw > 0 ? 1 : 0);
                  }, 0)}개
                </div>
              </div>
              <div className="border rounded p-2 bg-gray-50">
                <div className="text-xs text-gray-600 mb-1">연기차단재</div>
                <div className="font-medium">
                  {(order.items || []).reduce((acc, item) => {
                    const pw = parseInt(item.prodWidth) || parseInt(item.openWidth) || 0;
                    return acc + (pw > 0 ? 1 : 0);
                  }, 0)}개
                </div>
              </div>
            </div>
          </div>

          {/* 3. 절곡품 도면 */}
          <div className="mb-6">
            <h3 className="font-bold mb-2 text-sm">3. 절곡품 도면</h3>
            <div className="grid grid-cols-2 gap-4">
              {/* 벽면형 도면 */}
              <div className="border rounded-lg p-4 bg-gray-50">
                <div className="text-center font-medium text-sm mb-3 bg-gray-200 py-1 rounded">벽면형 (120-70)</div>
                <div className="relative h-32 border-2 border-gray-400 rounded bg-white flex items-center justify-center">
                  {/* 도면 SVG */}
                  <svg viewBox="0 0 200 100" className="w-full h-full p-2">
                    {/* 벽면형 절곡 형태 */}
                    <path d="M 20 80 L 20 30 L 50 30 L 50 20 L 180 20 L 180 30 L 180 80"
                      fill="none" stroke="#333" strokeWidth="2" />
                    {/* 치수선 - 가로 */}
                    <line x1="50" y1="10" x2="180" y2="10" stroke="#666" strokeWidth="1" />
                    <line x1="50" y1="8" x2="50" y2="12" stroke="#666" strokeWidth="1" />
                    <line x1="180" y1="8" x2="180" y2="12" stroke="#666" strokeWidth="1" />
                    <text x="115" y="8" textAnchor="middle" className="text-xs" fill="#333">120</text>
                    {/* 치수선 - 세로 */}
                    <line x1="12" y1="30" x2="12" y2="80" stroke="#666" strokeWidth="1" />
                    <line x1="10" y1="30" x2="14" y2="30" stroke="#666" strokeWidth="1" />
                    <line x1="10" y1="80" x2="14" y2="80" stroke="#666" strokeWidth="1" />
                    <text x="8" y="58" textAnchor="middle" className="text-xs" fill="#333" transform="rotate(-90, 8, 58)">70</text>
                  </svg>
                </div>
                <div className="mt-2 text-xs text-gray-600 text-center">
                  벽면 설치용 가이드레일 절곡 형태
                </div>
              </div>

              {/* 측면형 도면 */}
              <div className="border rounded-lg p-4 bg-gray-50">
                <div className="text-center font-medium text-sm mb-3 bg-gray-200 py-1 rounded">측면형 (120-120)</div>
                <div className="relative h-32 border-2 border-gray-400 rounded bg-white flex items-center justify-center">
                  {/* 도면 SVG */}
                  <svg viewBox="0 0 200 100" className="w-full h-full p-2">
                    {/* 측면형 절곡 형태 (L자형) */}
                    <path d="M 30 80 L 30 20 L 170 20 L 170 80"
                      fill="none" stroke="#333" strokeWidth="2" />
                    {/* 치수선 - 가로 */}
                    <line x1="30" y1="10" x2="170" y2="10" stroke="#666" strokeWidth="1" />
                    <line x1="30" y1="8" x2="30" y2="12" stroke="#666" strokeWidth="1" />
                    <line x1="170" y1="8" x2="170" y2="12" stroke="#666" strokeWidth="1" />
                    <text x="100" y="8" textAnchor="middle" className="text-xs" fill="#333">120</text>
                    {/* 치수선 - 세로 (왼쪽) */}
                    <line x1="22" y1="20" x2="22" y2="80" stroke="#666" strokeWidth="1" />
                    <line x1="20" y1="20" x2="24" y2="20" stroke="#666" strokeWidth="1" />
                    <line x1="20" y1="80" x2="24" y2="80" stroke="#666" strokeWidth="1" />
                    <text x="18" y="53" textAnchor="middle" className="text-xs" fill="#333" transform="rotate(-90, 18, 53)">120</text>
                  </svg>
                </div>
                <div className="mt-2 text-xs text-gray-600 text-center">
                  측면 설치용 가이드레일 절곡 형태
                </div>
              </div>
            </div>
          </div>

          {/* 4. 부자재 목록 */}
          <div className="mb-6">
            <h3 className="font-bold mb-2 text-sm">4. 부자재</h3>
            <div className="border rounded-lg overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-gray-100">
                  <tr>
                    <th className="px-3 py-2 border-r text-center w-12">NO</th>
                    <th className="px-3 py-2 border-r text-left">품명</th>
                    <th className="px-3 py-2 border-r text-center w-24">규격</th>
                    <th className="px-3 py-2 border-r text-center w-16">단위</th>
                    <th className="px-3 py-2 border-r text-center w-16 bg-yellow-100">수량</th>
                    <th className="px-3 py-2 text-left">비고</th>
                  </tr>
                </thead>
                <tbody>
                  {[
                    { name: '감기샤프트', spec: 'ø25', unit: 'EA', qty: (order.items || []).length, remark: '셔터 수량과 동일' },
                    { name: '각파이프', spec: '30x30', unit: 'M', qty: Math.ceil((order.items || []).length * 2.5), remark: '케이스 프레임용' },
                    { name: '앵글', spec: '30x30x3t', unit: 'M', qty: Math.ceil((order.items || []).length * 1.5), remark: '브라켓 제작용' },
                    { name: '모터브라켓', spec: '-', unit: 'EA', qty: (order.items || []).length, remark: '셔터당 1개' },
                    { name: '스톱퍼', spec: '-', unit: 'EA', qty: (order.items || []).length * 2, remark: '상하 각 1개' },
                    { name: '리미트스위치', spec: '-', unit: 'EA', qty: (order.items || []).length * 2, remark: '상하 각 1개' },
                    { name: '스프링', spec: '-', unit: 'EA', qty: (order.items || []).length, remark: '텐션 스프링' },
                    { name: '볼트/너트세트', spec: 'M8', unit: 'SET', qty: (order.items || []).length * 4, remark: '고정용' },
                  ].map((item, idx) => (
                    <tr key={idx} className="border-t hover:bg-gray-50">
                      <td className="px-3 py-2 border-r text-center">{String(idx + 1).padStart(2, '0')}</td>
                      <td className="px-3 py-2 border-r">{item.name}</td>
                      <td className="px-3 py-2 border-r text-center">{item.spec}</td>
                      <td className="px-3 py-2 border-r text-center">{item.unit}</td>
                      <td className="px-3 py-2 border-r text-center font-medium bg-yellow-50">{item.qty}</td>
                      <td className="px-3 py-2 text-xs text-gray-500">{item.remark}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* 수령확인 서명란 */}
          <div className="mb-6 p-4 border-2 border-gray-300 rounded-lg bg-gray-50">
            <div className="text-center text-sm mb-4">
              상기 내역을 확인하고 납품물을 인수합니다.
            </div>
            <div className="grid grid-cols-3 gap-4">
              <div className="text-center">
                <div className="text-xs text-gray-500 mb-1">인수일자</div>
                <div className="border-b border-gray-400 py-2">{today}</div>
              </div>
              <div className="text-center">
                <div className="text-xs text-gray-500 mb-1">인수자</div>
                <div className="border-b border-gray-400 py-2">&nbsp;</div>
              </div>
              <div className="text-center">
                <div className="text-xs text-gray-500 mb-1">서명</div>
                <div className="border-b border-gray-400 py-2">&nbsp;</div>
              </div>
            </div>
          </div>

          {/* 인수담당자 정보 */}
          <div className="grid grid-cols-3 gap-4 mb-6">
            <div className="border rounded-lg p-3">
              <div className="text-sm text-gray-500">인수담당자</div>
              <div className="font-medium">{shipment.receiverName || '-'}</div>
            </div>
            <div className="border rounded-lg p-3">
              <div className="text-sm text-gray-500">인수자연락처</div>
              <div className="font-medium">{shipment.receiverPhone || '-'}</div>
            </div>
            <div className="border rounded-lg p-3">
              <div className="text-sm text-gray-500">배송방법</div>
              <div className="font-medium">{shipment.deliveryMethod || '상차'} / {shipment.deliveryType || '선불'}</div>
            </div>
          </div>

          {/* 결재란 */}
          <div className="flex justify-end">
            <table className="border text-sm">
              <thead>
                <tr className="bg-gray-100">
                  <th className="px-4 py-2 border-r">검재</th>
                  <th className="px-8 py-2 border-r">작성</th>
                  <th className="px-8 py-2 border-r">검토</th>
                  <th className="px-8 py-2">승인</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td className="px-4 py-2 border-r bg-gray-50">판매/전진</td>
                  <td className="px-8 py-6 border-r"></td>
                  <td className="px-8 py-6 border-r"></td>
                  <td className="px-8 py-6"></td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// 작업일지 문서 컴포넌트 (생산 현장 작업 기록)
// ============================================================
const WorkLogDoc = ({
  workOrder,
  workResults = [],
  onClose,
  onPrint,
  onSave
}) => {
  const [formData, setFormData] = useState({
    workDate: new Date().toISOString().split('T')[0],
    productionManager: '',
    items: workOrder?.items?.map(item => ({
      ...item,
      incomingLotNo: '',
      prodWidth: item.width || '',
      prodHeight: item.height || '',
      remainHeight: 810,
      qty1180: 0,
      qty900: 0,
      qty600: 0,
      qty400: 0,
      qty300: 0,
    })) || [],
    fabricLotNo: '',
    fabricUsage: { 1220: 0, 900: 0, 600: 0 },
    totalArea: 0,
  });

  if (!workOrder) return null;

  const lotNo = workOrder.lotNo || `KD-WE-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-01-(${workOrder.splitIndex || 1})`;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-5xl max-h-[90vh] overflow-auto">
        {/* 문서 헤더 */}
        <div className="p-6 border-b flex justify-between items-center bg-gray-50">
          <h2 className="text-xl font-bold">작업일지</h2>
          <div className="flex gap-2">
            <button
              onClick={onPrint}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
            >
              <Printer className="w-4 h-4" />
              인쇄
            </button>
            <button
              onClick={() => onSave?.(formData)}
              className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700"
            >
              저장
            </button>
            <button
              onClick={onClose}
              className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100"
            >
              닫기
            </button>
          </div>
        </div>

        {/* 문서 내용 */}
        <div className="p-6" id="work-log-print">
          {/* 상단 헤더 */}
          <div className="flex justify-between items-start mb-6 border-b pb-4">
            <div>
              <h1 className="text-2xl font-bold text-gray-800">KD 경동기업</h1>
              <p className="text-sm text-gray-500 mt-1">스크린 생산부서</p>
            </div>
            <div className="text-center">
              <h2 className="text-xl font-bold">작 업 일 지</h2>
            </div>
            <div className="text-right">
              <table className="border text-xs">
                <thead>
                  <tr className="bg-gray-100">
                    <th className="px-3 py-1 border-r">작성</th>
                    <th className="px-3 py-1 border-r">검토</th>
                    <th className="px-3 py-1">승인</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td className="px-3 py-4 border-r"></td>
                    <td className="px-3 py-4 border-r"></td>
                    <td className="px-3 py-4"></td>
                  </tr>
                  <tr className="bg-gray-50">
                    <td className="px-3 py-1 border-r text-center">판매/전진</td>
                    <td className="px-3 py-1 border-r text-center">생산</td>
                    <td className="px-3 py-1 text-center">품질</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* 기본 정보 */}
          <div className="grid grid-cols-2 gap-6 mb-6">
            <div className="border rounded-lg overflow-hidden">
              <div className="bg-gray-100 px-3 py-2 font-medium text-sm">신청업체</div>
              <table className="w-full text-sm">
                <tbody>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2 w-24">발주일</td>
                    <td className="px-3 py-2">{workOrder.orderDate || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">업체명</td>
                    <td className="px-3 py-2">{workOrder.customerName || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">담당자</td>
                    <td className="px-3 py-2">{workOrder.manager || '-'}</td>
                  </tr>
                </tbody>
              </table>
            </div>

            <div className="border rounded-lg overflow-hidden">
              <div className="bg-gray-100 px-3 py-2 font-medium text-sm">신청내용</div>
              <table className="w-full text-sm">
                <tbody>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2 w-24">현장명</td>
                    <td className="px-3 py-2 font-medium">{workOrder.siteName || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">작업일자</td>
                    <td className="px-3 py-2">
                      <input
                        type="date"
                        value={formData.workDate}
                        onChange={(e) => setFormData(prev => ({ ...prev, workDate: e.target.value }))}
                        className="border rounded px-2 py-1"
                      />
                    </td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">제품 LOT NO</td>
                    <td className="px-3 py-2 font-mono">{lotNo}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">생산담당자</td>
                    <td className="px-3 py-2">
                      <input
                        type="text"
                        value={formData.productionManager}
                        onChange={(e) => setFormData(prev => ({ ...prev, productionManager: e.target.value }))}
                        placeholder="담당자명 입력"
                        className="border rounded px-2 py-1 w-full"
                      />
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* 작업 내역 */}
          <div className="mb-6">
            <h3 className="font-medium mb-3 text-gray-700">■ 작업 내역</h3>
            <div className="border rounded-lg overflow-hidden overflow-x-auto">
              <table className="w-full text-sm min-w-[900px]">
                <thead className="bg-yellow-100">
                  <tr>
                    <th className="px-2 py-2 border-r">일련번호</th>
                    <th className="px-2 py-2 border-r">입고 LOT NO.</th>
                    <th className="px-2 py-2 border-r">제품명</th>
                    <th className="px-2 py-2 border-r">부호</th>
                    <th className="px-2 py-2 border-r" colSpan="2">제작사이즈(mm)</th>
                    <th className="px-2 py-2 border-r">나머지높이</th>
                    <th className="px-2 py-2" colSpan="5">규격(매수)</th>
                  </tr>
                  <tr className="bg-yellow-50 text-xs">
                    <th className="px-2 py-1 border-r"></th>
                    <th className="px-2 py-1 border-r"></th>
                    <th className="px-2 py-1 border-r"></th>
                    <th className="px-2 py-1 border-r"></th>
                    <th className="px-2 py-1 border-r">가로</th>
                    <th className="px-2 py-1 border-r">세로</th>
                    <th className="px-2 py-1 border-r"></th>
                    <th className="px-2 py-1 border-r bg-cyan-100">1180</th>
                    <th className="px-2 py-1 border-r bg-cyan-100">900</th>
                    <th className="px-2 py-1 border-r bg-yellow-200">600</th>
                    <th className="px-2 py-1 border-r">400</th>
                    <th className="px-2 py-1">300</th>
                  </tr>
                </thead>
                <tbody>
                  {formData.items.map((item, idx) => (
                    <tr key={idx} className="border-t">
                      <td className="px-2 py-2 text-center border-r">{String(idx + 1).padStart(2, '0')}</td>
                      <td className="px-2 py-2 text-center border-r">
                        <input
                          type="text"
                          value={item.incomingLotNo}
                          onChange={(e) => {
                            const newItems = [...formData.items];
                            newItems[idx].incomingLotNo = e.target.value;
                            setFormData(prev => ({ ...prev, items: newItems }));
                          }}
                          className="border rounded px-1 py-0.5 w-20 text-xs"
                        />
                      </td>
                      <td className="px-2 py-2 text-center border-r">{item.productName || '와이어'}</td>
                      <td className="px-2 py-2 text-center border-r">{item.code || `4층 FSS${idx + 1}`}</td>
                      <td className="px-2 py-2 text-center border-r bg-cyan-50 font-medium">{item.prodWidth}</td>
                      <td className="px-2 py-2 text-center border-r bg-cyan-50 font-medium">{item.prodHeight || 2950}</td>
                      <td className="px-2 py-2 text-center border-r bg-cyan-50 font-medium">{item.remainHeight}</td>
                      <td className="px-2 py-2 text-center border-r bg-cyan-100">{item.qty1180 || 2}</td>
                      <td className="px-2 py-2 text-center border-r bg-cyan-100">{item.qty900 || 1}</td>
                      <td className="px-2 py-2 text-center border-r bg-yellow-100">{item.qty600}</td>
                      <td className="px-2 py-2 text-center border-r">{item.qty400}</td>
                      <td className="px-2 py-2 text-center">{item.qty300}</td>
                    </tr>
                  ))}
                  <tr className="border-t bg-green-50 font-medium">
                    <td colSpan="6" className="px-2 py-2 text-center border-r">합 계</td>
                    <td className="px-2 py-2 text-center border-r"></td>
                    <td className="px-2 py-2 text-center border-r">{formData.items.reduce((sum, i) => sum + (i.qty1180 || 2), 0)}</td>
                    <td className="px-2 py-2 text-center border-r">{formData.items.reduce((sum, i) => sum + (i.qty900 || 1), 0)}</td>
                    <td className="px-2 py-2 text-center border-r">{formData.items.reduce((sum, i) => sum + (i.qty600 || 0), 0)}</td>
                    <td className="px-2 py-2 text-center border-r">{formData.items.reduce((sum, i) => sum + (i.qty400 || 0), 0)}</td>
                    <td className="px-2 py-2 text-center">{formData.items.reduce((sum, i) => sum + (i.qty300 || 0), 0)}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* 내화실 입고 LOT NO */}
          <div className="mb-6">
            <div className="flex items-center gap-4 mb-3">
              <span className="font-medium text-gray-700">내화실 입고 LOT.NO</span>
              <input
                type="text"
                value={formData.fabricLotNo}
                onChange={(e) => setFormData(prev => ({ ...prev, fabricLotNo: e.target.value }))}
                className="border rounded px-3 py-1.5 w-48"
                placeholder="LOT 번호 입력"
              />
            </div>

            {/* 사용량 */}
            <div className="grid grid-cols-2 gap-6">
              <div className="border rounded-lg p-4">
                <h4 className="text-sm font-medium mb-3">사용량 (M)</h4>
                <div className="grid grid-cols-3 gap-3">
                  <div>
                    <label className="text-xs text-gray-500">1220</label>
                    <input
                      type="number"
                      className="border rounded px-2 py-1 w-full mt-1"
                      value={formData.fabricUsage[1220]}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        fabricUsage: { ...prev.fabricUsage, 1220: parseFloat(e.target.value) || 0 }
                      }))}
                    />
                  </div>
                  <div>
                    <label className="text-xs text-gray-500">900</label>
                    <input
                      type="number"
                      className="border rounded px-2 py-1 w-full mt-1"
                      value={formData.fabricUsage[900]}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        fabricUsage: { ...prev.fabricUsage, 900: parseFloat(e.target.value) || 0 }
                      }))}
                    />
                  </div>
                  <div>
                    <label className="text-xs text-gray-500">600</label>
                    <input
                      type="number"
                      className="border rounded px-2 py-1 w-full mt-1"
                      value={formData.fabricUsage[600]}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        fabricUsage: { ...prev.fabricUsage, 600: parseFloat(e.target.value) || 0 }
                      }))}
                    />
                  </div>
                </div>
              </div>

              <div className="border rounded-lg p-4 bg-gray-50">
                <h4 className="text-sm font-medium mb-3">사용량 (㎡)</h4>
                <div className="text-2xl font-bold text-blue-600">
                  {(
                    (formData.fabricUsage[1220] * 1.22) +
                    (formData.fabricUsage[900] * 0.9) +
                    (formData.fabricUsage[600] * 0.6)
                  ).toFixed(2)} ㎡
                </div>
              </div>
            </div>
          </div>

          {/* 주의사항 */}
          <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg text-center">
            <span className="text-yellow-800 font-bold text-lg">[비 고]사이즈 착오없이 부탁드립니다</span>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// 출고증 문서 컴포넌트 (출하 시 자재/부품 출고 내역)
// ============================================================
const ShippingSlipDoc = ({
  shipment,
  order,
  materials = [],
  onClose,
  onPrint
}) => {
  if (!shipment || !order) return null;

  const lotNo = shipment.lotNo || `KD-WE-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-01-(${shipment.splitIndex || 1})`;

  // 부자재 카테고리별 데이터
  const subMaterials = {
    shaft2inch: { name: '감기샤프트 2인치', spec: 'L:300', qty: 11 },
    shaft4inch: [
      { spec: 'L:3,000', qty: 0 },
      { spec: 'L:4,500', qty: 3 },
      { spec: 'L:6,000', qty: 3 },
    ],
    shaft5inch: [
      { spec: 'L:6,000', qty: 0 },
      { spec: 'L:7,000', qty: 2 },
      { spec: 'L:8,200', qty: 3 },
    ],
    squarePipe: [
      { spec: 'L:3,000', qty: 0 },
      { spec: 'L:6,000', qty: 56 },
    ],
    roundBar: { spec: 'L:3,000', qty: 27 },
    bottomChannel: { spec: 'L:2,000', qty: 67 },
    angle: [
      { spec: 'L:380', qty: 0 },
      { spec: 'L:2,500', qty: 44 },
    ],
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-5xl max-h-[90vh] overflow-auto">
        {/* 문서 헤더 */}
        <div className="p-6 border-b flex justify-between items-center bg-gray-50">
          <h2 className="text-xl font-bold">출고증</h2>
          <div className="flex gap-2">
            <button
              onClick={onPrint}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
            >
              <Printer className="w-4 h-4" />
              인쇄
            </button>
            <button
              onClick={onClose}
              className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100"
            >
              닫기
            </button>
          </div>
        </div>

        {/* 문서 내용 */}
        <div className="p-6" id="shipping-slip-print">
          {/* 상단 헤더 */}
          <div className="flex justify-between items-start mb-6 border-b pb-4">
            <div>
              <h1 className="text-2xl font-bold text-gray-800">KD 경동기업</h1>
              <p className="text-sm text-gray-500 mt-1">
                전화: 031-938-5130 | 팩스: 02-6911-6315 | 이메일: kd5130@naver.com
              </p>
            </div>
            <div className="text-center">
              <h2 className="text-xl font-bold">출 고 증</h2>
            </div>
            <div className="text-right">
              <p className="text-sm">로트번호: <span className="font-mono font-bold">{lotNo}</span></p>
              <table className="border text-xs mt-2 ml-auto">
                <thead>
                  <tr className="bg-gray-100">
                    <th className="px-2 py-1 border-r">작성</th>
                    <th className="px-2 py-1 border-r">검토</th>
                    <th className="px-2 py-1">승인</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td className="px-4 py-3 border-r"></td>
                    <td className="px-4 py-3 border-r"></td>
                    <td className="px-4 py-3"></td>
                  </tr>
                  <tr className="bg-gray-50 text-center">
                    <td className="px-2 py-1 border-r">판매/전진</td>
                    <td className="px-2 py-1 border-r">출하</td>
                    <td className="px-2 py-1">생산관리</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* 기본 정보 */}
          <div className="grid grid-cols-2 gap-6 mb-6">
            <div className="border rounded-lg overflow-hidden">
              <div className="bg-gray-100 px-3 py-2 font-medium text-sm">신청업체</div>
              <table className="w-full text-sm">
                <tbody>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2 w-24">발주일</td>
                    <td className="px-3 py-2">{order.orderDate || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">발주처</td>
                    <td className="px-3 py-2">{order.customerName || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">발주 담당자</td>
                    <td className="px-3 py-2">{order.manager || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">담당자 연락처</td>
                    <td className="px-3 py-2">{order.contactPhone || '-'}</td>
                  </tr>
                </tbody>
              </table>
            </div>

            <div className="border rounded-lg overflow-hidden">
              <div className="bg-gray-100 px-3 py-2 font-medium text-sm">신청내용 / 납품정보</div>
              <table className="w-full text-sm">
                <tbody>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2 w-24">현장명</td>
                    <td className="px-3 py-2 font-medium">{order.siteName || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">납기요청일</td>
                    <td className="px-3 py-2">{order.dueDate || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">출고일</td>
                    <td className="px-3 py-2">{shipment.shipDate || '-'}</td>
                  </tr>
                  <tr className="border-t">
                    <td className="bg-gray-50 px-3 py-2">셔터총수량</td>
                    <td className="px-3 py-2">{order.totalQty || '-'} 개소</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* 배송지 주소 */}
          <div className="mb-6 p-3 bg-blue-50 rounded-lg">
            <span className="text-sm font-medium text-blue-800">배송지 주소: </span>
            <span className="text-sm text-blue-900">{order.deliveryAddress || '-'}</span>
          </div>

          {/* 1. 부자재 내역 */}
          <div className="mb-6">
            <h3 className="font-medium mb-3 text-gray-700">1. 부자재 - 감기샤프트, 각파이프, 앵글</h3>
            <div className="grid grid-cols-5 gap-4">
              {/* 감기샤프트 2인치 */}
              <div className="border rounded-lg p-3">
                <div className="text-xs text-gray-500 mb-1">감기샤프트 2인치</div>
                <div className="text-xs text-gray-400">L : 300</div>
                <div className="text-xl font-bold text-blue-600 mt-2 text-center">11</div>
              </div>

              {/* 감기샤프트 4인치 */}
              <div className="border rounded-lg p-3">
                <div className="text-xs text-gray-500 mb-1">감기샤프트 4인치</div>
                <div className="space-y-1 text-xs">
                  <div className="flex justify-between"><span>L:3,000</span><span className="text-blue-600 font-medium">-</span></div>
                  <div className="flex justify-between"><span>L:4,500</span><span className="text-blue-600 font-medium">3</span></div>
                  <div className="flex justify-between"><span>L:6,000</span><span className="text-blue-600 font-medium">3</span></div>
                </div>
              </div>

              {/* 감기샤프트 5인치 */}
              <div className="border rounded-lg p-3">
                <div className="text-xs text-gray-500 mb-1">감기샤프트 5인치</div>
                <div className="space-y-1 text-xs">
                  <div className="flex justify-between"><span>L:6,000</span><span className="text-blue-600 font-medium">-</span></div>
                  <div className="flex justify-between"><span>L:7,000</span><span className="text-blue-600 font-medium">2</span></div>
                  <div className="flex justify-between"><span>L:8,200</span><span className="text-blue-600 font-medium">3</span></div>
                </div>
              </div>

              {/* 각파이프 */}
              <div className="border rounded-lg p-3">
                <div className="text-xs text-gray-500 mb-1">각파이프 (50*30*1.4T)</div>
                <div className="space-y-1 text-xs">
                  <div className="flex justify-between"><span>L:3,000</span><span className="text-blue-600 font-medium">-</span></div>
                  <div className="flex justify-between"><span>L:6,000</span><span className="text-blue-600 font-medium">56</span></div>
                </div>
              </div>

              {/* 앵글 */}
              <div className="border rounded-lg p-3">
                <div className="text-xs text-gray-500 mb-1">앵글 (40*40*3T)</div>
                <div className="space-y-1 text-xs">
                  <div className="flex justify-between"><span>L:380</span><span className="text-blue-600 font-medium">-</span></div>
                  <div className="flex justify-between"><span>L:2,500</span><span className="text-blue-600 font-medium">44</span></div>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4 mt-3">
              {/* 마철봉 */}
              <div className="border rounded-lg p-3 flex justify-between items-center">
                <div>
                  <div className="text-xs text-gray-500">마철봉 (6mm)</div>
                  <div className="text-xs text-gray-400">L : 3,000</div>
                </div>
                <div className="text-xl font-bold text-blue-600">27</div>
              </div>

              {/* 하단 무게평철 */}
              <div className="border rounded-lg p-3 flex justify-between items-center">
                <div>
                  <div className="text-xs text-gray-500">하단 무게평철 [50*12T]</div>
                  <div className="text-xs text-gray-400">L : 2,000</div>
                </div>
                <div className="text-xl font-bold text-blue-600">67</div>
              </div>
            </div>

            <p className="text-xs text-gray-500 mt-2">※ 별도 추가사항 - 부자재</p>
          </div>

          {/* 2. 모터 */}
          <div className="mb-6">
            <h3 className="font-medium mb-3 text-gray-700">2. 모터</h3>
            <div className="grid grid-cols-2 gap-6">
              {/* 모터 220V 단상 */}
              <div className="border rounded-lg overflow-hidden">
                <div className="bg-gray-100 px-3 py-2 font-medium text-sm">2-1. 모터(220V 단상)</div>
                <table className="w-full text-sm">
                  <thead>
                    <tr className="bg-gray-50">
                      <th className="px-3 py-2 border-r">모터 용량</th>
                      <th className="px-3 py-2 border-r">수량</th>
                      <th className="px-3 py-2">입고 LOT NO.</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr className="border-t">
                      <td className="px-3 py-2 border-r">KD-150K</td>
                      <td className="px-3 py-2 text-center border-r">-</td>
                      <td className="px-3 py-2"></td>
                    </tr>
                    <tr className="border-t">
                      <td className="px-3 py-2 border-r">KD-300K</td>
                      <td className="px-3 py-2 text-center border-r">-</td>
                      <td className="px-3 py-2"></td>
                    </tr>
                  </tbody>
                </table>
              </div>

              {/* 모터 380V 삼상 */}
              <div className="border rounded-lg overflow-hidden">
                <div className="bg-gray-100 px-3 py-2 font-medium text-sm">2-2. 모터(380V 삼상)</div>
                <table className="w-full text-sm">
                  <thead>
                    <tr className="bg-gray-50">
                      <th className="px-3 py-2 border-r">모터 용량</th>
                      <th className="px-3 py-2 border-r">수량</th>
                      <th className="px-3 py-2">입고 LOT NO.</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr className="border-t">
                      <td className="px-3 py-2 border-r">KD-150K</td>
                      <td className="px-3 py-2 text-center border-r text-blue-600 font-medium">6</td>
                      <td className="px-3 py-2"></td>
                    </tr>
                    <tr className="border-t">
                      <td className="px-3 py-2 border-r">KD-300K</td>
                      <td className="px-3 py-2 text-center border-r text-blue-600 font-medium">5</td>
                      <td className="px-3 py-2"></td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            {/* 브라켓트 & 연동제어기 */}
            <div className="grid grid-cols-2 gap-6 mt-4">
              <div className="border rounded-lg overflow-hidden">
                <div className="bg-gray-100 px-3 py-2 font-medium text-sm">2-3. 브라켓트</div>
                <table className="w-full text-sm">
                  <thead>
                    <tr className="bg-gray-50">
                      <th className="px-3 py-2 border-r">브라켓트</th>
                      <th className="px-3 py-2 border-r">수량</th>
                      <th className="px-3 py-2">입고 LOT NO.</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr className="border-t">
                      <td className="px-3 py-2 border-r">380*180 (2-4")</td>
                      <td className="px-3 py-2 text-center border-r text-blue-600 font-medium">6</td>
                      <td className="px-3 py-2"></td>
                    </tr>
                    <tr className="border-t">
                      <td className="px-3 py-2 border-r">380*180 (2-5")</td>
                      <td className="px-3 py-2 text-center border-r text-blue-600 font-medium">5</td>
                      <td className="px-3 py-2"></td>
                    </tr>
                  </tbody>
                </table>
              </div>

              <div className="border rounded-lg overflow-hidden">
                <div className="bg-gray-100 px-3 py-2 font-medium text-sm">2-4. 연동제어기</div>
                <table className="w-full text-sm">
                  <thead>
                    <tr className="bg-gray-50">
                      <th className="px-3 py-2 border-r">품명</th>
                      <th className="px-3 py-2 border-r">수량</th>
                      <th className="px-3 py-2">입고 LOT NO.</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr className="border-t">
                      <td className="px-3 py-2 border-r">매립형</td>
                      <td className="px-3 py-2 text-center border-r">-</td>
                      <td className="px-3 py-2"></td>
                    </tr>
                    <tr className="border-t">
                      <td className="px-3 py-2 border-r">노출형</td>
                      <td className="px-3 py-2 text-center border-r">-</td>
                      <td className="px-3 py-2"></td>
                    </tr>
                    <tr className="border-t">
                      <td className="px-3 py-2 border-r">뒷박스</td>
                      <td className="px-3 py-2 text-center border-r">-</td>
                      <td className="px-3 py-2"></td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            <p className="text-xs text-gray-500 mt-2">※ 별도 추가사항 - 모터</p>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// 중간검사성적서 문서 컴포넌트 (공정 중 품질 검사 기록)
// ============================================================
const ProcessInspectionDoc = ({
  inspection,
  workOrder,
  onClose,
  onPrint,
  onSave
}) => {
  const [formData, setFormData] = useState({
    productName: inspection?.productName || '스크린',
    specification: inspection?.specification || '와이어 클라스 코팅직물',
    lotNo: inspection?.lotNo || workOrder?.lotNo || '',
    lotSize: inspection?.lotSize || 11,
    inspectionDate: inspection?.inspectionDate || new Date().toISOString().split('T')[0],
    inspector: inspection?.inspector || '',
    items: inspection?.items || Array(11).fill(null).map((_, idx) => ({
      no: idx + 1,
      processState: { good: true, bad: false },
      sewingState: { good: true, bad: false },
      assemblyState: { good: true, bad: false },
      length: { drawing: 0, measured: 0 },
      height: { drawing: 0, measured: 0 },
      gap: { standard: '400 이하', measured: 0 },
      result: 'OK',
    })),
  });

  const lotNo = formData.lotNo || `KD-WE-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-01-(${workOrder?.splitIndex || 1})`;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-6xl max-h-[90vh] overflow-auto">
        {/* 문서 헤더 */}
        <div className="p-6 border-b flex justify-between items-center bg-gray-50">
          <h2 className="text-xl font-bold">스크린-중간 검사성적서</h2>
          <div className="flex gap-2">
            <button
              onClick={onPrint}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
            >
              <Printer className="w-4 h-4" />
              인쇄
            </button>
            <button
              onClick={() => onSave?.(formData)}
              className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700"
            >
              저장
            </button>
            <button
              onClick={onClose}
              className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100"
            >
              닫기
            </button>
          </div>
        </div>

        {/* 문서 내용 */}
        <div className="p-6" id="process-inspection-print">
          {/* 상단 헤더 */}
          <div className="flex justify-between items-start mb-6 border-b pb-4">
            <div>
              <h1 className="text-2xl font-bold text-gray-800">KD 경동기업</h1>
            </div>
            <div className="text-center">
              <h2 className="text-xl font-bold">스크린-중간 검사성적서</h2>
            </div>
            <div className="text-right">
              <table className="border text-xs">
                <thead>
                  <tr className="bg-gray-100">
                    <th className="px-3 py-1 border-r">작성</th>
                    <th className="px-3 py-1 border-r">검토</th>
                    <th className="px-3 py-1">승인</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td className="px-4 py-3 border-r"></td>
                    <td className="px-4 py-3 border-r">전진</td>
                    <td className="px-4 py-3"></td>
                  </tr>
                  <tr className="bg-gray-50 text-center">
                    <td className="px-3 py-1 border-r">판매/전진</td>
                    <td className="px-3 py-1 border-r">생산</td>
                    <td className="px-3 py-1">품질</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* 기본 정보 */}
          <div className="grid grid-cols-4 gap-4 mb-6">
            <div className="border rounded-lg p-3">
              <div className="text-xs text-gray-500">품 명</div>
              <div className="font-medium">{formData.productName}</div>
            </div>
            <div className="border rounded-lg p-3">
              <div className="text-xs text-gray-500">규 격</div>
              <div className="font-medium">{formData.specification}</div>
            </div>
            <div className="border rounded-lg p-3">
              <div className="text-xs text-gray-500">제품 LOT NO</div>
              <div className="font-mono font-medium">{lotNo}</div>
            </div>
            <div className="border rounded-lg p-3">
              <div className="text-xs text-gray-500">로트크기</div>
              <div className="font-medium">{formData.lotSize} 개소</div>
            </div>
          </div>

          <div className="grid grid-cols-3 gap-4 mb-6">
            <div className="border rounded-lg p-3">
              <div className="text-xs text-gray-500">발주처</div>
              <div className="font-medium">{workOrder?.customerName || '-'}</div>
            </div>
            <div className="border rounded-lg p-3">
              <div className="text-xs text-gray-500">검사일자</div>
              <input
                type="date"
                value={formData.inspectionDate}
                onChange={(e) => setFormData(prev => ({ ...prev, inspectionDate: e.target.value }))}
                className="border rounded px-2 py-1 w-full"
              />
            </div>
            <div className="border rounded-lg p-3">
              <div className="text-xs text-gray-500">현장명</div>
              <div className="font-medium text-blue-600">{workOrder?.siteName || '-'}</div>
            </div>
          </div>

          {/* 검사기준서 */}
          <div className="mb-6 border rounded-lg overflow-hidden">
            <div className="bg-gray-100 px-4 py-2 font-medium">중간검사 기준서</div>
            <div className="p-4">
              <div className="grid grid-cols-2 gap-6">
                {/* 도해 */}
                <div className="border rounded-lg p-4 bg-gray-50">
                  <div className="text-center text-sm text-gray-500 mb-2">도해</div>
                  <div className="h-32 flex items-center justify-center border-2 border-dashed border-gray-300 rounded">
                    <span className="text-gray-400">스크린 단면도</span>
                  </div>
                </div>

                {/* 검사항목 */}
                <div>
                  <table className="w-full text-sm border">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-2 py-1 border-r">검사항목</th>
                        <th className="px-2 py-1 border-r">검사기준</th>
                        <th className="px-2 py-1 border-r">검사방법</th>
                        <th className="px-2 py-1 border-r">검사주기</th>
                        <th className="px-2 py-1">관련규정</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr className="border-t">
                        <td className="px-2 py-1 border-r">겉모양 - 가공상태</td>
                        <td className="px-2 py-1 border-r text-xs">사용상 해로운 결함이 없을것</td>
                        <td className="px-2 py-1 border-r text-center" rowSpan="2">육안검사</td>
                        <td className="px-2 py-1 border-r text-center" rowSpan="5">n=1, c=0</td>
                        <td className="px-2 py-1 text-xs">KS F 4510 5.1항</td>
                      </tr>
                      <tr className="border-t">
                        <td className="px-2 py-1 border-r">겉모양 - 재봉상태</td>
                        <td className="px-2 py-1 border-r text-xs">내화실에 의해 견고하게 접합되어야 함</td>
                        <td className="px-2 py-1 text-xs">KS F 4510 9항</td>
                      </tr>
                      <tr className="border-t">
                        <td className="px-2 py-1 border-r">겉모양 - 조립상태</td>
                        <td className="px-2 py-1 border-r text-xs">엔드락이 견고하게 조립되어야 함</td>
                        <td className="px-2 py-1 border-r text-center" rowSpan="3">체크검사</td>
                        <td className="px-2 py-1 text-xs">KS F 4510 7항 표9 인용</td>
                      </tr>
                      <tr className="border-t">
                        <td className="px-2 py-1 border-r">치수 - 길이 ①</td>
                        <td className="px-2 py-1 border-r text-xs">도면치수 ± 4</td>
                        <td className="px-2 py-1 text-xs" rowSpan="2">자체규정</td>
                      </tr>
                      <tr className="border-t">
                        <td className="px-2 py-1 border-r">치수 - 높이 ②</td>
                        <td className="px-2 py-1 border-r text-xs">도면치수 + 제한없음 - 40</td>
                      </tr>
                      <tr className="border-t">
                        <td className="px-2 py-1 border-r">치수 - 간격 ③</td>
                        <td className="px-2 py-1 border-r text-xs">400 이하</td>
                        <td className="px-2 py-1 border-r text-center">GONO 게이지</td>
                        <td className="px-2 py-1 border-r"></td>
                        <td className="px-2 py-1 text-xs">자체규정</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>

          {/* 중간검사 DATA */}
          <div className="mb-6">
            <h3 className="font-medium mb-3 text-gray-700">중간검사 DATA</h3>
            <div className="border rounded-lg overflow-hidden overflow-x-auto">
              <table className="w-full text-sm min-w-[1000px]">
                <thead className="bg-gray-100">
                  <tr>
                    <th className="px-2 py-2 border-r" rowSpan="2">일련번호</th>
                    <th className="px-2 py-2 border-r" colSpan="3">겉모양</th>
                    <th className="px-2 py-2 border-r" colSpan="6">치수 [mm]</th>
                    <th className="px-2 py-2" rowSpan="2">판정</th>
                  </tr>
                  <tr>
                    <th className="px-2 py-1 border-r text-xs">가공상태</th>
                    <th className="px-2 py-1 border-r text-xs">재봉상태</th>
                    <th className="px-2 py-1 border-r text-xs">조립상태</th>
                    <th className="px-2 py-1 border-r text-xs" colSpan="2">① 길이</th>
                    <th className="px-2 py-1 border-r text-xs" colSpan="2">② 높이</th>
                    <th className="px-2 py-1 border-r text-xs" colSpan="2">③ 간격</th>
                  </tr>
                  <tr className="bg-gray-50 text-xs">
                    <th className="px-2 py-1 border-r"></th>
                    <th className="px-2 py-1 border-r">양호/불량</th>
                    <th className="px-2 py-1 border-r">양호/불량</th>
                    <th className="px-2 py-1 border-r">양호/불량</th>
                    <th className="px-2 py-1 border-r">도면치수</th>
                    <th className="px-2 py-1 border-r">측정값</th>
                    <th className="px-2 py-1 border-r">도면치수</th>
                    <th className="px-2 py-1 border-r">측정값</th>
                    <th className="px-2 py-1 border-r">기준치</th>
                    <th className="px-2 py-1 border-r">측정값</th>
                    <th className="px-2 py-1"></th>
                  </tr>
                </thead>
                <tbody>
                  {formData.items.map((item, idx) => (
                    <tr key={idx} className="border-t">
                      <td className="px-2 py-2 text-center border-r">{String(idx + 1).padStart(2, '0')}</td>
                      <td className="px-2 py-2 text-center border-r">
                        <label className="inline-flex items-center mr-2">
                          <input type="checkbox" defaultChecked className="mr-1" /> 양호
                        </label>
                        <label className="inline-flex items-center">
                          <input type="checkbox" className="mr-1" /> 불량
                        </label>
                      </td>
                      <td className="px-2 py-2 text-center border-r">
                        <label className="inline-flex items-center mr-2">
                          <input type="checkbox" defaultChecked className="mr-1" /> 양호
                        </label>
                        <label className="inline-flex items-center">
                          <input type="checkbox" className="mr-1" /> 불량
                        </label>
                      </td>
                      <td className="px-2 py-2 text-center border-r">
                        <label className="inline-flex items-center mr-2">
                          <input type="checkbox" defaultChecked className="mr-1" /> 양호
                        </label>
                        <label className="inline-flex items-center">
                          <input type="checkbox" className="mr-1" /> 불량
                        </label>
                      </td>
                      <td className="px-2 py-2 text-center border-r">
                        <input type="number" className="border rounded w-16 px-1 py-0.5 text-center" />
                      </td>
                      <td className="px-2 py-2 text-center border-r bg-cyan-50">
                        <input type="number" className="border rounded w-16 px-1 py-0.5 text-center bg-cyan-50 font-medium" />
                      </td>
                      <td className="px-2 py-2 text-center border-r">
                        <input type="number" className="border rounded w-16 px-1 py-0.5 text-center" />
                      </td>
                      <td className="px-2 py-2 text-center border-r bg-cyan-50">
                        <input type="number" className="border rounded w-16 px-1 py-0.5 text-center bg-cyan-50 font-medium" />
                      </td>
                      <td className="px-2 py-2 text-center border-r text-xs">400 이하</td>
                      <td className="px-2 py-2 text-center border-r">
                        <input type="number" className="border rounded w-16 px-1 py-0.5 text-center" />
                      </td>
                      <td className="px-2 py-2 text-center">
                        <label className="inline-flex items-center mr-2">
                          <input type="checkbox" defaultChecked className="mr-1" /> OK
                        </label>
                        <label className="inline-flex items-center">
                          <input type="checkbox" className="mr-1" /> NG
                        </label>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// 제품검사요청서 문서 컴포넌트 (인정기관 검사 요청)
// ============================================================
const ProductInspectionRequestDoc = ({
  order,
  shipment,
  onClose,
  onPrint,
  onSave
}) => {
  const [formData, setFormData] = useState({
    receiptDate: new Date().toISOString().split('T')[0],
    requesterName: order?.customerName || '',
    contactPerson: order?.contactPerson || '',
    contactPhone: order?.contactPhone || '',
    orderNo: order?.orderNo || '',
    siteName: order?.siteName || '',
    siteAddress: order?.siteAddress || '',
    deliveryDate: order?.dueDate || '',
    totalQty: order?.totalQty || 0,
    inspectionRequestDate: '',
    // 건축공사장 정보
    constructionSite: {
      name: '',
      address: '',
      lotNo: '',
    },
    // 자재유통업자 정보
    materialDistributor: {
      name: '',
      company: '',
      companyAddress: '',
      phone: '',
    },
    // 공사시공자 정보
    contractor: {
      name: '',
      company: '',
      companyAddress: '',
      phone: '',
    },
    // 공사감리자 정보
    supervisor: {
      name: '',
      office: '',
      officeAddress: '',
      phone: '',
    },
    // 검사대상 사전 고지 정보
    inspectionItems: order?.items?.map((item, idx) => ({
      floor: item.floor || `${idx + 1}층`,
      code: item.code || `FST-${String(idx + 1).padStart(2, '0')}`,
      orderWidth: item.width || 0,
      orderHeight: item.height || 0,
      actualWidth: item.width || 0,
      actualHeight: item.height || 0,
      changeReason: '',
    })) || [],
  });

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-5xl max-h-[90vh] overflow-auto">
        {/* 문서 헤더 */}
        <div className="p-6 border-b flex justify-between items-center bg-gray-50">
          <h2 className="text-xl font-bold">자동방화셔터(인정제품) 제품검사요청서</h2>
          <div className="flex gap-2">
            <button
              onClick={onPrint}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
            >
              <Printer className="w-4 h-4" />
              인쇄
            </button>
            <button
              onClick={() => onSave?.(formData)}
              className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700"
            >
              저장
            </button>
            <button
              onClick={onClose}
              className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100"
            >
              닫기
            </button>
          </div>
        </div>

        {/* 문서 내용 */}
        <div className="p-6" id="product-inspection-request-print">
          {/* 상단 헤더 */}
          <div className="flex justify-between items-start mb-6 border-b pb-4">
            <div>
              <h1 className="text-2xl font-bold text-gray-800">KD 경동기업</h1>
            </div>
            <div className="text-center flex-1">
              <h2 className="text-xl font-bold">자동방화셔터(인정제품) 제품검사요청서</h2>
            </div>
            <div className="text-right">
              <div className="text-sm">접수일</div>
              <input
                type="date"
                value={formData.receiptDate}
                onChange={(e) => setFormData(prev => ({ ...prev, receiptDate: e.target.value }))}
                className="border rounded px-2 py-1"
              />
            </div>
          </div>

          {/* 기본정보 */}
          <div className="mb-6 border rounded-lg overflow-hidden">
            <div className="bg-blue-100 px-4 py-2 font-medium text-blue-800">기본정보</div>
            <table className="w-full text-sm">
              <tbody>
                <tr className="border-t">
                  <td className="bg-gray-50 px-4 py-3 w-32 font-medium">발신처(업체명)</td>
                  <td className="px-4 py-3">
                    <input
                      type="text"
                      value={formData.requesterName}
                      onChange={(e) => setFormData(prev => ({ ...prev, requesterName: e.target.value }))}
                      className="border rounded px-2 py-1 w-48"
                    />
                  </td>
                  <td className="bg-gray-50 px-4 py-3 w-24 font-medium">담당자</td>
                  <td className="px-4 py-3">
                    <input
                      type="text"
                      value={formData.contactPerson}
                      onChange={(e) => setFormData(prev => ({ ...prev, contactPerson: e.target.value }))}
                      className="border rounded px-2 py-1 w-32"
                    />
                  </td>
                </tr>
                <tr className="border-t">
                  <td className="bg-gray-50 px-4 py-3 font-medium">발주번호</td>
                  <td className="px-4 py-3 font-mono">{formData.orderNo}</td>
                  <td className="bg-gray-50 px-4 py-3 font-medium">담당자연락처</td>
                  <td className="px-4 py-3">
                    <input
                      type="text"
                      value={formData.contactPhone}
                      onChange={(e) => setFormData(prev => ({ ...prev, contactPhone: e.target.value }))}
                      className="border rounded px-2 py-1 w-40"
                    />
                  </td>
                </tr>
                <tr className="border-t">
                  <td className="bg-gray-50 px-4 py-3 font-medium">현장명</td>
                  <td className="px-4 py-3 text-blue-600 font-medium" colSpan="3">{formData.siteName}</td>
                </tr>
                <tr className="border-t">
                  <td className="bg-gray-50 px-4 py-3 font-medium">현장주소</td>
                  <td className="px-4 py-3" colSpan="3">{formData.siteAddress}</td>
                </tr>
                <tr className="border-t">
                  <td className="bg-gray-50 px-4 py-3 font-medium">납품일</td>
                  <td className="px-4 py-3 text-blue-600">{formData.deliveryDate}</td>
                  <td className="bg-gray-50 px-4 py-3 font-medium">총 개소</td>
                  <td className="px-4 py-3 font-medium">{formData.totalQty} 개소</td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 검사방문요청일 */}
          <div className="mb-6 p-4 bg-orange-50 border border-orange-200 rounded-lg">
            <div className="font-medium text-orange-800 mb-2">검사방문요청일(전화예정)</div>
            <input
              type="date"
              value={formData.inspectionRequestDate}
              onChange={(e) => setFormData(prev => ({ ...prev, inspectionRequestDate: e.target.value }))}
              className="border rounded px-3 py-2"
            />
          </div>

          {/* 입력사항 */}
          <div className="mb-6 border rounded-lg overflow-hidden">
            <div className="bg-blue-100 px-4 py-2 font-medium text-blue-800">입력사항 (품질관리서 동일정보)</div>

            {/* 건축공사장 */}
            <div className="p-4 border-t">
              <div className="font-medium text-gray-700 mb-3">건축공사장</div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm text-gray-500">현장명</label>
                  <input
                    type="text"
                    value={formData.constructionSite.name}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      constructionSite: { ...prev.constructionSite, name: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-500">지번</label>
                  <input
                    type="text"
                    value={formData.constructionSite.lotNo}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      constructionSite: { ...prev.constructionSite, lotNo: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
                <div className="col-span-2">
                  <label className="text-sm text-gray-500">대지위치</label>
                  <input
                    type="text"
                    value={formData.constructionSite.address}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      constructionSite: { ...prev.constructionSite, address: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
              </div>
            </div>

            {/* 자재유통업자 */}
            <div className="p-4 border-t">
              <div className="font-medium text-gray-700 mb-3">자재유통업자</div>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div>
                  <label className="text-sm text-gray-500">성명</label>
                  <input
                    type="text"
                    value={formData.materialDistributor.name}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      materialDistributor: { ...prev.materialDistributor, name: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-500">회사명</label>
                  <input
                    type="text"
                    value={formData.materialDistributor.company}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      materialDistributor: { ...prev.materialDistributor, company: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-500">회사주소</label>
                  <input
                    type="text"
                    value={formData.materialDistributor.companyAddress}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      materialDistributor: { ...prev.materialDistributor, companyAddress: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-500">전화번호</label>
                  <input
                    type="text"
                    value={formData.materialDistributor.phone}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      materialDistributor: { ...prev.materialDistributor, phone: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
              </div>
            </div>

            {/* 공사시공자 */}
            <div className="p-4 border-t">
              <div className="font-medium text-gray-700 mb-3">공사시공자 <span className="text-blue-600">(건설사)</span></div>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div>
                  <label className="text-sm text-gray-500">성명</label>
                  <input
                    type="text"
                    value={formData.contractor.name}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      contractor: { ...prev.contractor, name: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-500">회사명</label>
                  <input
                    type="text"
                    value={formData.contractor.company}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      contractor: { ...prev.contractor, company: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-500">회사주소</label>
                  <input
                    type="text"
                    value={formData.contractor.companyAddress}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      contractor: { ...prev.contractor, companyAddress: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-500">전화번호</label>
                  <input
                    type="text"
                    value={formData.contractor.phone}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      contractor: { ...prev.contractor, phone: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
              </div>
            </div>

            {/* 공사감리자 */}
            <div className="p-4 border-t">
              <div className="font-medium text-gray-700 mb-3">공사감리자</div>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div>
                  <label className="text-sm text-gray-500">성명</label>
                  <input
                    type="text"
                    value={formData.supervisor.name}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      supervisor: { ...prev.supervisor, name: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-500">사무소명</label>
                  <input
                    type="text"
                    value={formData.supervisor.office}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      supervisor: { ...prev.supervisor, office: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-500">사무소주소</label>
                  <input
                    type="text"
                    value={formData.supervisor.officeAddress}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      supervisor: { ...prev.supervisor, officeAddress: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm text-gray-500">전화번호</label>
                  <input
                    type="text"
                    value={formData.supervisor.phone}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      supervisor: { ...prev.supervisor, phone: e.target.value }
                    }))}
                    className="border rounded px-2 py-1 w-full mt-1"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* 주의사항 */}
          <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
            <div className="font-medium text-red-800 mb-2">※ 검사요청시 필독</div>
            <ul className="text-sm text-red-700 space-y-1">
              <li>√ 발주 size 와 시공완료된 size 가 다를 시, 일정 범위를 벗어난 경우 인정라벨을 부착할 수 없습니다.</li>
              <li className="font-medium">제품검사를 위한 방문 전까지 <span className="text-blue-600 underline">변경사유를 고지하셔야 인정라벨을 부착</span>할 수 있습니다.</li>
              <li>(사전고지를 하지 않음으로 발생하는 문제의 귀책은 신청업체에 있습니다)</li>
            </ul>
          </div>

          {/* 검사대상 사전 고지 정보 */}
          <div className="mb-6 border rounded-lg overflow-hidden">
            <div className="bg-blue-100 px-4 py-2 font-medium text-blue-800">검사대상 사전 고지 정보</div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-100">
                  <tr>
                    <th className="px-3 py-2 border-r" rowSpan="2">일련번호</th>
                    <th className="px-3 py-2 border-r" rowSpan="2">층수</th>
                    <th className="px-3 py-2 border-r" rowSpan="2">부호</th>
                    <th className="px-3 py-2 border-r" colSpan="4">오픈사이즈</th>
                    <th className="px-3 py-2" rowSpan="2">변경사유</th>
                  </tr>
                  <tr>
                    <th className="px-3 py-1 border-r text-xs" colSpan="2">발주규격</th>
                    <th className="px-3 py-1 border-r text-xs" colSpan="2">시공후규격</th>
                  </tr>
                  <tr className="bg-gray-50 text-xs">
                    <th className="px-3 py-1 border-r"></th>
                    <th className="px-3 py-1 border-r"></th>
                    <th className="px-3 py-1 border-r"></th>
                    <th className="px-3 py-1 border-r">가로</th>
                    <th className="px-3 py-1 border-r">세로</th>
                    <th className="px-3 py-1 border-r">가로</th>
                    <th className="px-3 py-1 border-r">세로</th>
                    <th className="px-3 py-1"></th>
                  </tr>
                </thead>
                <tbody>
                  {formData.inspectionItems.slice(0, 5).map((item, idx) => (
                    <tr key={idx} className="border-t">
                      <td className="px-3 py-2 text-center border-r">{idx + 1}</td>
                      <td className="px-3 py-2 text-center border-r">{item.floor}</td>
                      <td className="px-3 py-2 text-center border-r">{item.code}</td>
                      <td className="px-3 py-2 text-center border-r">{item.orderWidth}</td>
                      <td className="px-3 py-2 text-center border-r">{item.orderHeight}</td>
                      <td className="px-3 py-2 text-center border-r">{item.actualWidth}</td>
                      <td className="px-3 py-2 text-center border-r">{item.actualHeight}</td>
                      <td className="px-3 py-2">
                        <input
                          type="text"
                          value={item.changeReason}
                          onChange={(e) => {
                            const newItems = [...formData.inspectionItems];
                            newItems[idx].changeReason = e.target.value;
                            setFormData(prev => ({ ...prev, inspectionItems: newItems }));
                          }}
                          className="border rounded px-2 py-1 w-full text-xs"
                          placeholder="변경사유 입력"
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// 품질기준 상세/등록/수정 패널
const InspectionStandardPanel = ({ mode, standard, onClose, onSave, onEdit }) => {
  const [formData, setFormData] = useState(standard || {
    code: '',
    name: '',
    inspectionType: '입고검사',
    targetType: '자재',
    targetCode: '',
    targetName: '',
    inspectionItems: [],
    samplingRule: '',
    samplingQty: '',
    frequency: '',
    responsibleTeam: '품질팀',
    status: '사용',
  });

  const [newItem, setNewItem] = useState({
    item: '',
    method: '',
    standard: '',
    unit: '-',
    min: null,
    max: null,
    critical: false,
  });

  const isReadOnly = mode === 'detail';

  const handleAddItem = () => {
    if (!newItem.item || !newItem.standard) {
      alert('검사항목과 기준을 입력해주세요.');
      return;
    }
    setFormData(prev => ({
      ...prev,
      inspectionItems: [...prev.inspectionItems, { ...newItem, id: Date.now() }],
    }));
    setNewItem({
      item: '',
      method: '',
      standard: '',
      unit: '-',
      min: null,
      max: null,
      critical: false,
    });
  };

  const handleRemoveItem = (id) => {
    setFormData(prev => ({
      ...prev,
      inspectionItems: prev.inspectionItems.filter(i => i.id !== id),
    }));
  };

  const handleSubmit = () => {
    if (!formData.code || !formData.name) {
      alert('기준코드와 기준명은 필수입니다.');
      return;
    }
    if (formData.inspectionItems.length === 0) {
      alert('검사항목을 1개 이상 등록해주세요.');
      return;
    }
    onSave?.(formData);
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-start justify-end z-50">
      <div className="bg-white w-full max-w-3xl h-full overflow-y-auto">
        <div className="sticky top-0 bg-white border-b z-10">
          <div className="flex items-center justify-between p-4">
            <div className="flex items-center gap-3">
              <ShieldCheck className="w-6 h-6 text-green-500" />
              <div>
                <h2 className="text-lg font-bold">
                  {mode === 'create' ? '품질기준 등록' : mode === 'edit' ? '품질기준 수정' : '품질기준 상세'}
                </h2>
                {standard && <p className="text-sm text-gray-500">{standard.code}</p>}
              </div>
            </div>
            <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg">
              <X className="w-5 h-5 text-gray-500" />
            </button>
          </div>
        </div>

        <div className="p-6 space-y-6">
          {/* 기본 정보 */}
          <Card title="기본 정보">
            <div className="grid grid-cols-2 gap-4">
              <FormField label="기준코드" required>
                <input
                  type="text"
                  value={formData.code}
                  onChange={(e) => setFormData(prev => ({ ...prev, code: e.target.value }))}
                  disabled={isReadOnly}
                  placeholder="QS-INC-001"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg disabled:bg-gray-100"
                />
              </FormField>
              <FormField label="기준명" required>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                  disabled={isReadOnly}
                  placeholder="스크린 원단 입고검사"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg disabled:bg-gray-100"
                />
              </FormField>
              <FormField label="검사유형" required>
                <select
                  value={formData.inspectionType}
                  onChange={(e) => setFormData(prev => ({ ...prev, inspectionType: e.target.value }))}
                  disabled={isReadOnly}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg disabled:bg-gray-100"
                >
                  <option value="입고검사">입고검사</option>
                  <option value="중간검사">중간검사</option>
                  <option value="제품검사">제품검사</option>
                </select>
              </FormField>
              <FormField label="상태">
                <select
                  value={formData.status}
                  onChange={(e) => setFormData(prev => ({ ...prev, status: e.target.value }))}
                  disabled={isReadOnly}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg disabled:bg-gray-100"
                >
                  <option value="사용">사용</option>
                  <option value="미사용">미사용</option>
                </select>
              </FormField>
            </div>
          </Card>

          {/* 검사 대상 */}
          <Card title="검사 대상">
            <div className="grid grid-cols-3 gap-4">
              <FormField label="대상유형">
                <select
                  value={formData.targetType}
                  onChange={(e) => setFormData(prev => ({ ...prev, targetType: e.target.value }))}
                  disabled={isReadOnly}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg disabled:bg-gray-100"
                >
                  <option value="자재">자재</option>
                  <option value="공정">공정</option>
                  <option value="품목">품목</option>
                </select>
              </FormField>
              <FormField label="대상코드">
                <input
                  type="text"
                  value={formData.targetCode}
                  onChange={(e) => setFormData(prev => ({ ...prev, targetCode: e.target.value }))}
                  disabled={isReadOnly}
                  placeholder="SCR-MAT-001"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg disabled:bg-gray-100"
                />
              </FormField>
              <FormField label="대상명">
                <input
                  type="text"
                  value={formData.targetName}
                  onChange={(e) => setFormData(prev => ({ ...prev, targetName: e.target.value }))}
                  disabled={isReadOnly}
                  placeholder="스크린 원단"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg disabled:bg-gray-100"
                />
              </FormField>
            </div>
          </Card>

          {/* 검사 항목 */}
          <Card title="검사 항목">
            <div className="space-y-4">
              {/* 기존 항목 목록 */}
              {formData.inspectionItems.length > 0 ? (
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">검사항목</th>
                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">검사방법</th>
                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">기준</th>
                        <th className="px-3 py-2 text-center text-xs font-medium text-gray-500">단위</th>
                        <th className="px-3 py-2 text-center text-xs font-medium text-gray-500">치명</th>
                        {!isReadOnly && <th className="px-3 py-2 text-center text-xs font-medium text-gray-500">삭제</th>}
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {formData.inspectionItems.map((item, idx) => (
                        <tr key={item.id || idx}>
                          <td className="px-3 py-2 font-medium">{item.item}</td>
                          <td className="px-3 py-2 text-gray-600">{item.method}</td>
                          <td className="px-3 py-2 text-gray-600">
                            <div>
                              {item.standard}
                              {(item.min !== null || item.max !== null) && (
                                <p className="text-xs text-gray-400">
                                  {item.min !== null && `Min: ${item.min}`}
                                  {item.min !== null && item.max !== null && ' / '}
                                  {item.max !== null && `Max: ${item.max}`}
                                </p>
                              )}
                            </div>
                          </td>
                          <td className="px-3 py-2 text-center text-gray-500">{item.unit}</td>
                          <td className="px-3 py-2 text-center">
                            {item.critical ? (
                              <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-red-100 text-red-700">
                                <AlertCircle className="w-3 h-3 mr-1" /> 치명
                              </span>
                            ) : (
                              <span className="text-gray-400">-</span>
                            )}
                          </td>
                          {!isReadOnly && (
                            <td className="px-3 py-2 text-center">
                              <button
                                onClick={() => handleRemoveItem(item.id)}
                                className="p-1 hover:bg-red-100 rounded text-red-500"
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </td>
                          )}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  <Clipboard className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                  <p>등록된 검사항목이 없습니다.</p>
                </div>
              )}

              {/* 새 항목 추가 */}
              {!isReadOnly && (
                <div className="border-t pt-4">
                  <h4 className="text-sm font-medium text-gray-700 mb-3">검사항목 추가</h4>
                  <div className="grid grid-cols-6 gap-2">
                    <div className="col-span-2">
                      <input
                        type="text"
                        placeholder="검사항목"
                        value={newItem.item}
                        onChange={(e) => setNewItem(prev => ({ ...prev, item: e.target.value }))}
                        className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
                      />
                    </div>
                    <div>
                      <input
                        type="text"
                        placeholder="검사방법"
                        value={newItem.method}
                        onChange={(e) => setNewItem(prev => ({ ...prev, method: e.target.value }))}
                        className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
                      />
                    </div>
                    <div className="col-span-2">
                      <input
                        type="text"
                        placeholder="기준 (예: ±5mm 이내)"
                        value={newItem.standard}
                        onChange={(e) => setNewItem(prev => ({ ...prev, standard: e.target.value }))}
                        className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
                      />
                    </div>
                    <div>
                      <input
                        type="text"
                        placeholder="단위"
                        value={newItem.unit}
                        onChange={(e) => setNewItem(prev => ({ ...prev, unit: e.target.value }))}
                        className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
                      />
                    </div>
                  </div>
                  <div className="flex items-center justify-between mt-2">
                    <label className="flex items-center gap-2 text-sm">
                      <input
                        type="checkbox"
                        checked={newItem.critical}
                        onChange={(e) => setNewItem(prev => ({ ...prev, critical: e.target.checked }))}
                        className="rounded"
                      />
                      <span className="text-red-600 font-medium">치명적 항목 (불합격 시 전체 불합격)</span>
                    </label>
                    <Button variant="outline" size="sm" onClick={handleAddItem}>
                      <Plus className="w-4 h-4" /> 항목 추가
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </Card>

          {/* 샘플링 규칙 */}
          <Card title="샘플링 규칙">
            <div className="grid grid-cols-2 gap-4">
              <FormField label="샘플링 규칙">
                <input
                  type="text"
                  value={formData.samplingRule}
                  onChange={(e) => setFormData(prev => ({ ...prev, samplingRule: e.target.value }))}
                  disabled={isReadOnly}
                  placeholder="AQL 2.5, 일반검사 Level II"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg disabled:bg-gray-100"
                />
              </FormField>
              <FormField label="샘플 수량">
                <input
                  type="text"
                  value={formData.samplingQty}
                  onChange={(e) => setFormData(prev => ({ ...prev, samplingQty: e.target.value }))}
                  disabled={isReadOnly}
                  placeholder="로트당 5개"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg disabled:bg-gray-100"
                />
              </FormField>
              <FormField label="검사 주기">
                <input
                  type="text"
                  value={formData.frequency}
                  onChange={(e) => setFormData(prev => ({ ...prev, frequency: e.target.value }))}
                  disabled={isReadOnly}
                  placeholder="입고시 전수 / 포장 전"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg disabled:bg-gray-100"
                />
              </FormField>
              <FormField label="담당부서">
                <input
                  type="text"
                  value={formData.responsibleTeam}
                  onChange={(e) => setFormData(prev => ({ ...prev, responsibleTeam: e.target.value }))}
                  disabled={isReadOnly}
                  placeholder="품질팀"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg disabled:bg-gray-100"
                />
              </FormField>
            </div>
          </Card>

          {/* 이력 정보 (상세 모드) */}
          {mode === 'detail' && standard && (
            <Card title="이력 정보">
              <div className="grid grid-cols-2 gap-4 text-sm">
                <InfoRow label="등록일" value={standard.createdAt} />
                <InfoRow label="수정일" value={standard.updatedAt} />
              </div>
            </Card>
          )}
        </div>

        {/* 하단 버튼 */}
        <div className="sticky bottom-0 bg-white border-t p-4 flex justify-end gap-2">
          <Button variant="outline" onClick={onClose}>
            {isReadOnly ? '닫기' : '취소'}
          </Button>
          {mode === 'detail' && (
            <Button variant="primary" onClick={onEdit}>
              <Edit3 className="w-4 h-4" /> 수정
            </Button>
          )}
          {(mode === 'create' || mode === 'edit') && (
            <Button variant="primary" onClick={handleSubmit}>
              <Check className="w-4 h-4" /> {mode === 'create' ? '등록' : '저장'}
            </Button>
          )}
        </div>
      </div>
    </div>
  );
};

// =============================================
// 회계관리 컴포넌트
// =============================================

// 매출관리
const SalesAccountManagement = ({ shipments = [], onNavigate }) => {
  const [activeTab, setActiveTab] = useState('list');
  const [search, setSearch] = useState('');
  const [dateRange, setDateRange] = useState({ start: '2025-12-01', end: '2025-12-09' });
  const [showPanel, setShowPanel] = useState(null);
  const [selectedSale, setSelectedSale] = useState(null);
  const [statusFilter, setStatusFilter] = useState('all');

  // 샘플 매출 데이터 (신용등급 연동 확장)
  const [salesData, setSalesData] = useState([
    {
      id: 1, saleNo: 'SL-251201-001', orderNo: 'KD-TS-251201-01', customerCode: 'C001', customerName: '삼성전자',
      creditGrade: 'A', productName: '방화스크린 KSS01', qty: 5, unitPrice: 2500000, amount: 12500000, vat: 1250000, totalAmount: 13750000,
      saleDate: '2025-12-01', dueDate: '2025-12-31', status: '미수금', invoiceNo: '', invoiceStatus: '미발행',
      // 경리승인 프로세스
      accountingApprovalRequired: false, // A등급: 불필요
      accountingApprovalStatus: '-', // 대기중/승인/반려/-
      accountingApprovalDate: '',
      accountingApprover: '',
      // 입금확인 프로세스
      paymentConfirmRequired: false, // A등급: 불필요
      paymentConfirmStatus: '-',
      paymentConfirmDate: '',
      paymentConfirmAmount: 0,
      // 출고상태
      shipmentStatus: '출고완료',
      shipmentDate: '2025-12-01',
    },
    {
      id: 2, saleNo: 'SL-251203-001', orderNo: 'KD-SL-251203-01', customerCode: 'C002', customerName: 'LG전자',
      creditGrade: 'A', productName: '방화슬랫셔터 KSL01', qty: 3, unitPrice: 1800000, amount: 5400000, vat: 540000, totalAmount: 5940000,
      saleDate: '2025-12-03', dueDate: '2025-12-20', status: '수금완료', invoiceNo: 'INV-251203-001', invoiceStatus: '발행완료',
      accountingApprovalRequired: false,
      accountingApprovalStatus: '-',
      accountingApprovalDate: '',
      accountingApprover: '',
      paymentConfirmRequired: false,
      paymentConfirmStatus: '확인완료',
      paymentConfirmDate: '2025-12-18',
      paymentConfirmAmount: 5940000,
      shipmentStatus: '출고완료',
      shipmentDate: '2025-12-03',
    },
    {
      id: 3, saleNo: 'SL-251205-001', orderNo: 'KD-BD-251205-01', customerCode: 'C003', customerName: '현대건설',
      creditGrade: 'A', productName: '방화절곡셔터 KSB01', qty: 10, unitPrice: 3200000, amount: 32000000, vat: 3200000, totalAmount: 35200000,
      saleDate: '2025-12-05', dueDate: '2026-01-05', status: '미수금', invoiceNo: 'INV-251205-001', invoiceStatus: '발행완료',
      accountingApprovalRequired: false,
      accountingApprovalStatus: '-',
      accountingApprovalDate: '',
      accountingApprover: '',
      paymentConfirmRequired: false,
      paymentConfirmStatus: '-',
      paymentConfirmDate: '',
      paymentConfirmAmount: 0,
      shipmentStatus: '출고완료',
      shipmentDate: '2025-12-05',
    },
    {
      id: 4, saleNo: 'SL-251208-001', orderNo: 'KD-TS-251208-01', customerCode: 'C004', customerName: '대우건설',
      creditGrade: 'B', productName: '방화스크린 KSS02', qty: 8, unitPrice: 2800000, amount: 22400000, vat: 2240000, totalAmount: 24640000,
      saleDate: '2025-12-08', dueDate: '2026-01-08', status: '미수금', invoiceNo: '', invoiceStatus: '미발행',
      accountingApprovalRequired: false, // B등급: 경리승인 불필요
      accountingApprovalStatus: '-',
      accountingApprovalDate: '',
      accountingApprover: '',
      paymentConfirmRequired: true, // B등급: 입금확인 후 출고
      paymentConfirmStatus: '입금대기',
      paymentConfirmDate: '',
      paymentConfirmAmount: 0,
      shipmentStatus: '입금대기',
      shipmentDate: '',
    },
    {
      id: 5, saleNo: 'SL-251210-001', orderNo: 'KD-BD-251210-01', customerCode: 'C005', customerName: '신흥건설',
      creditGrade: 'C', productName: '방화절곡셔터 KSB02', qty: 5, unitPrice: 3500000, amount: 17500000, vat: 1750000, totalAmount: 19250000,
      saleDate: '2025-12-10', dueDate: '2026-01-10', status: '미수금', invoiceNo: '', invoiceStatus: '미발행',
      accountingApprovalRequired: true, // C등급: 경리승인 필요
      accountingApprovalStatus: '승인대기',
      accountingApprovalDate: '',
      accountingApprover: '',
      paymentConfirmRequired: true, // C등급: 입금확인 후 출고
      paymentConfirmStatus: '입금대기',
      paymentConfirmDate: '',
      paymentConfirmAmount: 0,
      shipmentStatus: '경리승인대기',
      shipmentDate: '',
    },
  ]);

  const tabs = [
    { id: 'list', label: '매출목록' },
    { id: 'approval', label: '경리승인' },
    { id: 'payment', label: '입금확인' },
    { id: 'summary', label: '매출현황' },
    { id: 'customer', label: '거래처별' },
  ];

  // 통계
  const totalSales = salesData.reduce((sum, s) => sum + s.totalAmount, 0);
  const collectedAmount = salesData.filter(s => s.status === '수금완료').reduce((sum, s) => sum + s.totalAmount, 0);
  const outstandingAmount = salesData.filter(s => s.status === '미수금').reduce((sum, s) => sum + s.totalAmount, 0);
  const invoicedCount = salesData.filter(s => s.invoiceStatus === '발행완료').length;

  const filtered = salesData.filter(s =>
    s.saleNo.toLowerCase().includes(search.toLowerCase()) ||
    s.customerName.includes(search) ||
    s.orderNo.toLowerCase().includes(search.toLowerCase())
  );

  // 공통 UX: 매출목록 선택
  const {
    selectedIds: salesSelectedIds,
    handleSelect: handleSalesSelect,
    handleSelectAll: handleSalesSelectAll,
    isAllSelected: isSalesAllSelected,
    hasSelection: hasSalesSelection,
    isMultiSelect: isSalesMultiSelect,
    isSelected: isSalesSelected,
  } = useListSelection(filtered);

  // 공통 UX: 경리승인 목록 선택
  const approvalFiltered = salesData.filter(s => s.accountingApprovalRequired);
  const {
    selectedIds: approvalSelectedIds,
    handleSelect: handleApprovalSelect,
    handleSelectAll: handleApprovalSelectAll,
    isAllSelected: isApprovalAllSelected,
    hasSelection: hasApprovalSelection,
    isMultiSelect: isApprovalMultiSelect,
    isSelected: isApprovalSelected,
  } = useListSelection(approvalFiltered);

  // 공통 UX: 입금확인 목록 선택
  const paymentFiltered = salesData.filter(s => s.paymentConfirmRequired);
  const {
    selectedIds: paymentSelectedIds,
    handleSelect: handlePaymentSelect,
    handleSelectAll: handlePaymentSelectAll,
    isAllSelected: isPaymentAllSelected,
    hasSelection: hasPaymentSelection,
    isMultiSelect: isPaymentMultiSelect,
    isSelected: isPaymentSelected,
  } = useListSelection(paymentFiltered);

  const [showDeleteModal, setShowDeleteModal] = useState(false);

  const handleCreateSale = () => {
    setSelectedSale(null);
    setShowPanel(true);
  };

  const handleViewSale = (sale) => {
    setSelectedSale(sale);
    setShowPanel(true);
  };

  const handleIssueInvoice = (sale) => {
    if (sale.invoiceStatus === '발행완료') {
      alert('이미 세금계산서가 발행되었습니다.');
      return;
    }
    // C등급 거래처는 경리 승인 필요
    if (sale.creditGrade === 'C' && sale.accountingApprovalStatus !== '승인') {
      alert('C등급 거래처는 경리 승인 후 세금계산서 발행이 가능합니다.');
      return;
    }
    const invoiceNo = `INV-${sale.saleNo.split('-').slice(1).join('-')}`;
    setSalesData(prev => prev.map(s =>
      s.id === sale.id ? { ...s, invoiceNo, invoiceStatus: '발행완료' } : s
    ));
    alert(`세금계산서가 발행되었습니다.\n계산서번호: ${invoiceNo}`);
  };

  // 경리 승인 처리
  const handleAccountingApproval = (sale, action) => {
    const today = new Date().toISOString().split('T')[0];
    if (action === 'approve') {
      setSalesData(prev => prev.map(s =>
        s.id === sale.id ? {
          ...s,
          accountingApprovalStatus: '승인',
          accountingApprovalDate: today,
          accountingApprover: '경리팀 김경리',
          shipmentStatus: s.paymentConfirmRequired && s.paymentConfirmStatus !== '확인완료' ? '입금대기' : '출고가능'
        } : s
      ));
      alert(`경리 승인이 완료되었습니다.\n매출번호: ${sale.saleNo}\n거래처: ${sale.customerName}`);
    } else {
      const reason = prompt('반려 사유를 입력하세요:');
      if (reason) {
        setSalesData(prev => prev.map(s =>
          s.id === sale.id ? {
            ...s,
            accountingApprovalStatus: '반려',
            accountingApprovalDate: today,
            accountingApprover: '경리팀 김경리'
          } : s
        ));
        alert(`경리 승인이 반려되었습니다.\n사유: ${reason}`);
      }
    }
  };

  // 입금 확인 처리
  const handlePaymentConfirm = (sale) => {
    setSelectedSale(sale);
    setShowPanel('paymentConfirm');
  };

  const processPaymentConfirm = (sale, amount) => {
    const today = new Date().toISOString().split('T')[0];
    const isFullPayment = amount >= sale.totalAmount;
    setSalesData(prev => prev.map(s =>
      s.id === sale.id ? {
        ...s,
        paymentConfirmStatus: isFullPayment ? '확인완료' : '부분입금',
        paymentConfirmDate: today,
        paymentConfirmAmount: amount,
        status: isFullPayment ? '수금완료' : '부분수금',
        shipmentStatus: isFullPayment ? '출고가능' : s.shipmentStatus
      } : s
    ));
    setShowPanel(null);
    alert(`입금이 확인되었습니다.\n입금액: ${amount.toLocaleString()}원\n상태: ${isFullPayment ? '전액입금' : '부분입금'}`);
  };

  // 통계
  const pendingApprovalCount = salesData.filter(s => s.accountingApprovalStatus === '승인대기').length;
  const pendingPaymentCount = salesData.filter(s => s.paymentConfirmStatus === '입금대기').length;

  return (
    <div className="space-y-6">
      <PageHeader icon={TrendingUp} title="매출 목록" />

      {/* 통계 카드 */}
      <div className="grid grid-cols-2 md:grid-cols-6 gap-4">
        <StatCard icon={DollarSign} label="총 매출액" value={`${totalSales.toLocaleString()}원`} color="blue" />
        <StatCard icon={Check} label="수금완료" value={`${collectedAmount.toLocaleString()}원`} color="green" />
        <StatCard icon={AlertCircle} label="미수금" value={`${outstandingAmount.toLocaleString()}원`} color="red" />
        <StatCard icon={FileText} label="계산서발행" value={`${invoicedCount}건`} color="purple" />
        <StatCard icon={Shield} label="경리승인대기" value={`${pendingApprovalCount}건`} color="orange" />
        <StatCard icon={CreditCard} label="입금대기" value={`${pendingPaymentCount}건`} color="yellow" />
      </div>

      {/* 탭 및 검색 */}
      <Card>
        <div className="flex justify-between items-center mb-4">
          <div className="flex flex-wrap gap-2">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-full border transition-colors ${activeTab === tab.id ? 'bg-gray-900 text-white border-gray-900' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                  }`}
              >
                <span>{tab.label}</span>
              </button>
            ))}
          </div>
          <div className="flex gap-2">
            <div className="flex items-center gap-2">
              <input type="date" value={dateRange.start} onChange={e => setDateRange(prev => ({ ...prev, start: e.target.value }))}
                className="px-3 py-2 border rounded-lg text-sm" />
              <span>~</span>
              <input type="date" value={dateRange.end} onChange={e => setDateRange(prev => ({ ...prev, end: e.target.value }))}
                className="px-3 py-2 border rounded-lg text-sm" />
            </div>
            <SearchInput value={search} onChange={setSearch} placeholder="매출번호, 거래처명 검색" />
            {isSalesMultiSelect && (
              <Button variant="outline" onClick={() => setShowDeleteModal(true)}>
                <Trash2 className="w-4 h-4" /> 선택 삭제 ({salesSelectedIds.length})
              </Button>
            )}
            <Button variant="primary" onClick={handleCreateSale}><Plus className="w-4 h-4" /> 매출등록</Button>
          </div>
        </div>

        {activeTab === 'list' && (
          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-center w-10">
                  <input type="checkbox" checked={isSalesAllSelected} onChange={handleSalesSelectAll} className="rounded" />
                </th>
                <th className="px-4 py-3 text-left">매출번호</th>
                <th className="px-4 py-3 text-left">수주번호</th>
                <th className="px-4 py-3 text-left">거래처</th>
                <th className="px-4 py-3 text-left">품목명</th>
                <th className="px-4 py-3 text-right">공급가</th>
                <th className="px-4 py-3 text-right">부가세</th>
                <th className="px-4 py-3 text-right">합계</th>
                <th className="px-4 py-3 text-center">매출일</th>
                <th className="px-4 py-3 text-center">결제예정일</th>
                <th className="px-4 py-3 text-center">수금상태</th>
                <th className="px-4 py-3 text-center">계산서</th>
                <th className="px-4 py-3 text-center">관리</th>
                {hasSalesSelection && <th className="px-4 py-3 text-center">작업</th>}
              </tr>
            </thead>
            <tbody className="divide-y">
              {filtered.map(sale => (
                <tr key={sale.id} className={`hover:bg-gray-50 ${isSalesSelected(sale.id) ? 'bg-blue-50' : ''}`}>
                  <td className="px-4 py-3 text-center">
                    <input type="checkbox" checked={isSalesSelected(sale.id)} onChange={() => handleSalesSelect(sale.id)} className="rounded" />
                  </td>
                  <td className="px-4 py-3 font-medium text-blue-600">{sale.saleNo}</td>
                  <td className="px-4 py-3 text-gray-600">{sale.orderNo}</td>
                  <td className="px-4 py-3">{sale.customerName}</td>
                  <td className="px-4 py-3">{sale.productName}</td>
                  <td className="px-4 py-3 text-right">{sale.amount.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right">{sale.vat.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right font-medium">{sale.totalAmount.toLocaleString()}</td>
                  <td className="px-4 py-3 text-center">{sale.saleDate}</td>
                  <td className="px-4 py-3 text-center">{sale.dueDate}</td>
                  <td className="px-4 py-3 text-center">
                    <StatusBadge status={sale.status} />
                  </td>
                  <td className="px-4 py-3 text-center">
                    <span className={`text-xs px-2 py-1 rounded ${sale.invoiceStatus === '발행완료' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600'
                      }`}>{sale.invoiceStatus}</span>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <div className="flex justify-center gap-1">
                      <button onClick={() => handleViewSale(sale)} className="p-1 hover:bg-gray-100 rounded" title="상세보기">
                        <Eye className="w-4 h-4 text-gray-500" />
                      </button>
                      {sale.invoiceStatus !== '발행완료' && (
                        <button onClick={() => handleIssueInvoice(sale)} className="p-1 hover:bg-blue-100 rounded" title="계산서발행">
                          <FileText className="w-4 h-4 text-blue-500" />
                        </button>
                      )}
                    </div>
                  </td>
                  {hasSalesSelection && isSalesSelected(sale.id) && (
                    <td className="px-4 py-3 text-center">
                      <div className="flex justify-center gap-1">
                        <Button variant="outline" size="sm" onClick={() => handleViewSale(sale)}>
                          <Edit3 className="w-3 h-3" /> 수정
                        </Button>
                        <Button variant="outline" size="sm" onClick={() => setShowDeleteModal(true)}>
                          <Trash2 className="w-3 h-3" /> 삭제
                        </Button>
                      </div>
                    </td>
                  )}
                  {hasSalesSelection && !isSalesSelected(sale.id) && <td className="px-4 py-3"></td>}
                </tr>
              ))}
            </tbody>
          </table>
        )}

        {activeTab === 'approval' && (
          <div className="space-y-4">
            <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
              <p className="text-sm text-yellow-800">C등급(경리승인 거래처) 거래처의 매출 건은 경리 승인 후 생산지시 및 출고가 가능합니다.</p>
            </div>
            {salesData.filter(s => s.accountingApprovalRequired).length === 0 ? (
              <div className="text-center py-12 text-gray-500">
                경리 승인이 필요한 매출 건이 없습니다.
              </div>
            ) : (
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-center w-10">
                      <input type="checkbox" checked={isApprovalAllSelected} onChange={handleApprovalSelectAll} className="rounded" />
                    </th>
                    <th className="px-4 py-3 text-left">매출번호</th>
                    <th className="px-4 py-3 text-left">거래처</th>
                    <th className="px-4 py-3 text-center">신용등급</th>
                    <th className="px-4 py-3 text-left">품목명</th>
                    <th className="px-4 py-3 text-right">금액</th>
                    <th className="px-4 py-3 text-center">매출일</th>
                    <th className="px-4 py-3 text-center">승인상태</th>
                    <th className="px-4 py-3 text-center">출고상태</th>
                    <th className="px-4 py-3 text-center">처리</th>
                    {hasApprovalSelection && <th className="px-4 py-3 text-center">작업</th>}
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {approvalFiltered.map(sale => (
                    <tr key={sale.id} className={`hover:bg-gray-50 ${isApprovalSelected(sale.id) ? 'bg-blue-50' : sale.accountingApprovalStatus === '승인대기' ? 'bg-yellow-50' : ''}`}>
                      <td className="px-4 py-3 text-center">
                        <input type="checkbox" checked={isApprovalSelected(sale.id)} onChange={() => handleApprovalSelect(sale.id)} className="rounded" />
                      </td>
                      <td className="px-4 py-3 font-medium text-blue-600">{sale.saleNo}</td>
                      <td className="px-4 py-3">{sale.customerName}</td>
                      <td className="px-4 py-3 text-center">
                        <span className="px-2 py-1 rounded-full text-xs font-bold bg-red-100 text-red-700">{sale.creditGrade}등급</span>
                      </td>
                      <td className="px-4 py-3">{sale.productName}</td>
                      <td className="px-4 py-3 text-right font-medium">{sale.totalAmount.toLocaleString()}</td>
                      <td className="px-4 py-3 text-center">{sale.saleDate}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded text-xs font-medium ${sale.accountingApprovalStatus === '승인대기' ? 'bg-yellow-100 text-yellow-700' :
                            sale.accountingApprovalStatus === '승인' ? 'bg-green-100 text-green-700' :
                              sale.accountingApprovalStatus === '반려' ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-600'
                          }`}>{sale.accountingApprovalStatus}</span>
                      </td>
                      <td className="px-4 py-3 text-center text-xs text-gray-600">{sale.shipmentStatus}</td>
                      <td className="px-4 py-3 text-center">
                        {sale.accountingApprovalStatus === '승인대기' && (
                          <div className="flex justify-center gap-1">
                            <Button size="sm" variant="primary" onClick={() => handleAccountingApproval(sale, 'approve')}>승인</Button>
                            <Button size="sm" variant="outline" onClick={() => handleAccountingApproval(sale, 'reject')}>반려</Button>
                          </div>
                        )}
                        {sale.accountingApprovalStatus === '승인' && (
                          <span className="text-xs text-green-600">{sale.accountingApprovalDate} 승인</span>
                        )}
                        {sale.accountingApprovalStatus === '반려' && (
                          <span className="text-xs text-red-600">반려됨</span>
                        )}
                      </td>
                      {hasApprovalSelection && isApprovalSelected(sale.id) && (
                        <td className="px-4 py-3 text-center">
                          <div className="flex justify-center gap-1">
                            <Button variant="outline" size="sm" onClick={() => handleViewSale(sale)}>
                              <Edit3 className="w-3 h-3" /> 수정
                            </Button>
                            <Button variant="outline" size="sm" onClick={() => setShowDeleteModal(true)}>
                              <Trash2 className="w-3 h-3" /> 삭제
                            </Button>
                          </div>
                        </td>
                      )}
                      {hasApprovalSelection && !isApprovalSelected(sale.id) && <td className="px-4 py-3"></td>}
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        )}

        {activeTab === 'payment' && (
          <div className="space-y-4">
            <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <p className="text-sm text-blue-800">B등급(관리대상), C등급(경리승인) 거래처는 입금 확인 후 출고가 가능합니다.</p>
            </div>
            {salesData.filter(s => s.paymentConfirmRequired).length === 0 ? (
              <div className="text-center py-12 text-gray-500">
                입금 확인이 필요한 매출 건이 없습니다.
              </div>
            ) : (
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-center w-10">
                      <input type="checkbox" checked={isPaymentAllSelected} onChange={handlePaymentSelectAll} className="rounded" />
                    </th>
                    <th className="px-4 py-3 text-left">매출번호</th>
                    <th className="px-4 py-3 text-left">거래처</th>
                    <th className="px-4 py-3 text-center">신용등급</th>
                    <th className="px-4 py-3 text-right">청구금액</th>
                    <th className="px-4 py-3 text-right">입금액</th>
                    <th className="px-4 py-3 text-right">잔액</th>
                    <th className="px-4 py-3 text-center">입금상태</th>
                    <th className="px-4 py-3 text-center">출고상태</th>
                    <th className="px-4 py-3 text-center">처리</th>
                    {hasPaymentSelection && <th className="px-4 py-3 text-center">작업</th>}
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {paymentFiltered.map(sale => (
                    <tr key={sale.id} className={`hover:bg-gray-50 ${isPaymentSelected(sale.id) ? 'bg-blue-50' : sale.paymentConfirmStatus === '입금대기' ? 'bg-orange-50' : ''}`}>
                      <td className="px-4 py-3 text-center">
                        <input type="checkbox" checked={isPaymentSelected(sale.id)} onChange={() => handlePaymentSelect(sale.id)} className="rounded" />
                      </td>
                      <td className="px-4 py-3 font-medium text-blue-600">{sale.saleNo}</td>
                      <td className="px-4 py-3">{sale.customerName}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded-full text-xs font-bold ${sale.creditGrade === 'B' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'
                          }`}>{sale.creditGrade}등급</span>
                      </td>
                      <td className="px-4 py-3 text-right font-medium">{sale.totalAmount.toLocaleString()}</td>
                      <td className="px-4 py-3 text-right text-green-600">{sale.paymentConfirmAmount.toLocaleString()}</td>
                      <td className="px-4 py-3 text-right text-red-600">{(sale.totalAmount - sale.paymentConfirmAmount).toLocaleString()}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded text-xs font-medium ${sale.paymentConfirmStatus === '입금대기' ? 'bg-orange-100 text-orange-700' :
                            sale.paymentConfirmStatus === '확인완료' ? 'bg-green-100 text-green-700' :
                              sale.paymentConfirmStatus === '부분입금' ? 'bg-yellow-100 text-yellow-700' : 'bg-gray-100 text-gray-600'
                          }`}>{sale.paymentConfirmStatus}</span>
                      </td>
                      <td className="px-4 py-3 text-center text-xs text-gray-600">{sale.shipmentStatus}</td>
                      <td className="px-4 py-3 text-center">
                        {sale.paymentConfirmStatus !== '확인완료' && (
                          <Button size="sm" variant="primary" onClick={() => handlePaymentConfirm(sale)}>입금확인</Button>
                        )}
                        {sale.paymentConfirmStatus === '확인완료' && (
                          <span className="text-xs text-green-600">{sale.paymentConfirmDate} 확인</span>
                        )}
                      </td>
                      {hasPaymentSelection && isPaymentSelected(sale.id) && (
                        <td className="px-4 py-3 text-center">
                          <div className="flex justify-center gap-1">
                            <Button variant="outline" size="sm" onClick={() => handleViewSale(sale)}>
                              <Edit3 className="w-3 h-3" /> 수정
                            </Button>
                            <Button variant="outline" size="sm" onClick={() => setShowDeleteModal(true)}>
                              <Trash2 className="w-3 h-3" /> 삭제
                            </Button>
                          </div>
                        </td>
                      )}
                      {hasPaymentSelection && !isPaymentSelected(sale.id) && <td className="px-4 py-3"></td>}
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        )}

        {activeTab === 'summary' && (
          <div className="space-y-6">
            <div className="grid grid-cols-2 gap-6">
              <Card title="월별 매출 추이">
                <div className="h-48 flex items-end justify-around gap-2">
                  {['10월', '11월', '12월'].map((month, i) => (
                    <div key={month} className="flex flex-col items-center">
                      <div className="w-16 bg-blue-500 rounded-t" style={{ height: `${[80, 120, 160][i]}px` }} />
                      <span className="text-xs mt-2">{month}</span>
                      <span className="text-xs text-gray-500">{[3200, 4800, 5489][i]}만</span>
                    </div>
                  ))}
                </div>
              </Card>
              <Card title="거래처별 매출 비중">
                <div className="space-y-3">
                  {[
                    { name: '현대건설', amount: 35200000, percent: 64 },
                    { name: '삼성전자', amount: 13750000, percent: 25 },
                    { name: 'LG전자', amount: 5940000, percent: 11 },
                  ].map(item => (
                    <div key={item.name} className="flex items-center gap-3">
                      <span className="w-24 text-sm">{item.name}</span>
                      <div className="flex-1 h-4 bg-gray-100 rounded-full overflow-hidden">
                        <div className="h-full bg-blue-500 rounded-full" style={{ width: `${item.percent}%` }} />
                      </div>
                      <span className="w-20 text-right text-sm">{(item.amount / 10000).toLocaleString()}만</span>
                    </div>
                  ))}
                </div>
              </Card>
            </div>
          </div>
        )}

        {activeTab === 'customer' && (
          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left">거래처</th>
                <th className="px-4 py-3 text-right">매출건수</th>
                <th className="px-4 py-3 text-right">총매출액</th>
                <th className="px-4 py-3 text-right">수금완료</th>
                <th className="px-4 py-3 text-right">미수금</th>
                <th className="px-4 py-3 text-center">수금률</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {[
                { name: '현대건설', count: 1, total: 35200000, collected: 0, outstanding: 35200000 },
                { name: '삼성전자', count: 1, total: 13750000, collected: 0, outstanding: 13750000 },
                { name: 'LG전자', count: 1, total: 5940000, collected: 5940000, outstanding: 0 },
              ].map(row => (
                <tr key={row.name} className="hover:bg-gray-50">
                  <td className="px-4 py-3 font-medium">{row.name}</td>
                  <td className="px-4 py-3 text-right">{row.count}건</td>
                  <td className="px-4 py-3 text-right">{row.total.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-green-600">{row.collected.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-red-600">{row.outstanding.toLocaleString()}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`px-2 py-1 rounded text-xs ${row.collected / row.total >= 1 ? 'bg-green-100 text-green-700' :
                        row.collected / row.total >= 0.5 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'
                      }`}>
                      {Math.round(row.collected / row.total * 100)}%
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Card>

      {/* 입금확인 모달 */}
      {showPanel === 'paymentConfirm' && selectedSale && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-md w-full mx-4">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold">입금 확인</h3>
              <button onClick={() => setShowPanel(null)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4">
              <div className="p-4 bg-gray-50 rounded-lg space-y-2">
                <div className="flex justify-between"><span className="text-gray-500">매출번호</span><span className="font-medium">{selectedSale.saleNo}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">거래처</span><span className="font-medium">{selectedSale.customerName}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">청구금액</span><span className="font-bold text-blue-600">{selectedSale.totalAmount.toLocaleString()}원</span></div>
                <div className="flex justify-between"><span className="text-gray-500">기입금액</span><span className="text-green-600">{selectedSale.paymentConfirmAmount.toLocaleString()}원</span></div>
                <div className="flex justify-between border-t pt-2"><span className="text-gray-500">잔액</span><span className="font-bold text-red-600">{(selectedSale.totalAmount - selectedSale.paymentConfirmAmount).toLocaleString()}원</span></div>
              </div>
              <FormField label="입금액" required>
                <input
                  type="number"
                  id="paymentAmount"
                  defaultValue={selectedSale.totalAmount - selectedSale.paymentConfirmAmount}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-right"
                />
              </FormField>
              <FormField label="입금일자">
                <input
                  type="date"
                  defaultValue={new Date().toISOString().split('T')[0]}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg"
                />
              </FormField>
              <FormField label="입금구분">
                <select className="w-full px-3 py-2 border border-gray-200 rounded-lg">
                  <option>계좌이체</option>
                  <option>현금</option>
                  <option>카드</option>
                  <option>어음</option>
                  <option>기타</option>
                </select>
              </FormField>
              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button variant="outline" onClick={() => setShowPanel(null)}>취소</Button>
                <Button variant="primary" onClick={() => {
                  const amount = parseInt(document.getElementById('paymentAmount').value) || 0;
                  if (amount <= 0) {
                    alert('입금액을 입력해주세요.');
                    return;
                  }
                  processPaymentConfirm(selectedSale, selectedSale.paymentConfirmAmount + amount);
                }}>입금확인</Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 세금계산서 관리
const InvoiceManagement = () => {
  const [activeTab, setActiveTab] = useState('issued');
  const [search, setSearch] = useState('');
  const [showPanel, setShowPanel] = useState(false);
  const [selectedInvoice, setSelectedInvoice] = useState(null);

  const [invoices, setInvoices] = useState([
    {
      id: 1, invoiceNo: 'INV-251203-001', saleNo: 'SL-251203-001', customerCode: 'C002', customerName: 'LG전자',
      businessNo: '123-45-67890', amount: 5400000, vat: 540000, totalAmount: 5940000,
      issueDate: '2025-12-03', reportDate: '2025-12-05', status: '전송완료', type: '발행'
    },
    {
      id: 2, invoiceNo: 'INV-251205-001', saleNo: 'SL-251205-001', customerCode: 'C003', customerName: '현대건설',
      businessNo: '234-56-78901', amount: 32000000, vat: 3200000, totalAmount: 35200000,
      issueDate: '2025-12-05', reportDate: '', status: '발행완료', type: '발행'
    },
    {
      id: 3, invoiceNo: 'INV-R-251201-001', customerCode: 'S001', customerName: '금강철강',
      businessNo: '345-67-89012', amount: 8500000, vat: 850000, totalAmount: 9350000,
      issueDate: '2025-12-01', reportDate: '2025-12-02', status: '전송완료', type: '수취'
    },
  ]);

  const tabs = [
    { id: 'issued', label: '매출계산서', count: invoices.filter(i => i.type === '발행').length },
    { id: 'received', label: '매입계산서', count: invoices.filter(i => i.type === '수취').length },
    { id: 'pending', label: '미전송', count: invoices.filter(i => i.status === '발행완료').length },
  ];

  const filtered = invoices.filter(i => {
    const matchSearch = i.invoiceNo.toLowerCase().includes(search.toLowerCase()) ||
      i.customerName.includes(search);
    if (activeTab === 'issued') return matchSearch && i.type === '발행';
    if (activeTab === 'received') return matchSearch && i.type === '수취';
    if (activeTab === 'pending') return matchSearch && i.status === '발행완료';
    return matchSearch;
  });

  // 통계
  const issuedTotal = invoices.filter(i => i.type === '발행').reduce((sum, i) => sum + i.totalAmount, 0);
  const receivedTotal = invoices.filter(i => i.type === '수취').reduce((sum, i) => sum + i.totalAmount, 0);
  const pendingCount = invoices.filter(i => i.status === '발행완료').length;
  const transmittedCount = invoices.filter(i => i.status === '전송완료').length;

  const handleSendInvoice = (invoice) => {
    if (invoice.status === '전송완료') {
      alert('이미 국세청에 전송된 계산서입니다.');
      return;
    }
    setInvoices(prev => prev.map(i =>
      i.id === invoice.id ? { ...i, status: '전송완료', reportDate: new Date().toISOString().split('T')[0] } : i
    ));
    alert(`세금계산서가 국세청에 전송되었습니다.\n계산서번호: ${invoice.invoiceNo}`);
  };

  return (
    <div className="space-y-6">
      <PageHeader icon={FileText} title="세금계산서 목록" />

      {/* 통계 카드 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatCard icon={TrendingUp} label="매출계산서" value={`${issuedTotal.toLocaleString()}원`} color="blue" />
        <StatCard icon={ShoppingCart} label="매입계산서" value={`${receivedTotal.toLocaleString()}원`} color="green" />
        <StatCard icon={AlertCircle} label="미전송" value={`${pendingCount}건`} color="red" />
        <StatCard icon={Check} label="전송완료" value={`${transmittedCount}건`} color="purple" />
      </div>

      {/* 탭 및 검색 */}
      <Card>
        <div className="flex justify-between items-center mb-4">
          <div className="flex flex-wrap gap-2">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-full border transition-colors ${activeTab === tab.id ? 'bg-gray-900 text-white border-gray-900' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                  }`}
              >
                <span>{tab.label}</span>
                <span className={activeTab === tab.id ? 'text-white' : 'text-gray-500'}>{tab.count}</span>
              </button>
            ))}
          </div>
          <div className="flex gap-2">
            <SearchInput value={search} onChange={setSearch} placeholder="계산서번호, 거래처명 검색" />
            <Button variant="outline" onClick={() => alert('일괄전송 기능 준비 중')}>
              <Send className="w-4 h-4" /> 일괄전송
            </Button>
          </div>
        </div>

        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left">
                <input type="checkbox" className="rounded border-gray-300" />
              </th>
              <th className="px-4 py-3 text-left">계산서번호</th>
              <th className="px-4 py-3 text-left">거래처</th>
              <th className="px-4 py-3 text-left">사업자번호</th>
              <th className="px-4 py-3 text-right">공급가</th>
              <th className="px-4 py-3 text-right">부가세</th>
              <th className="px-4 py-3 text-right">합계</th>
              <th className="px-4 py-3 text-center">발행일</th>
              <th className="px-4 py-3 text-center">전송일</th>
              <th className="px-4 py-3 text-center">상태</th>
              <th className="px-4 py-3 text-center">관리</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map(invoice => (
              <tr key={invoice.id} className="hover:bg-gray-50">
                <td className="px-4 py-3">
                  <input type="checkbox" className="rounded border-gray-300" />
                </td>
                <td className="px-4 py-3 font-medium text-blue-600">{invoice.invoiceNo}</td>
                <td className="px-4 py-3">{invoice.customerName}</td>
                <td className="px-4 py-3 text-gray-600">{invoice.businessNo}</td>
                <td className="px-4 py-3 text-right">{invoice.amount.toLocaleString()}</td>
                <td className="px-4 py-3 text-right">{invoice.vat.toLocaleString()}</td>
                <td className="px-4 py-3 text-right font-medium">{invoice.totalAmount.toLocaleString()}</td>
                <td className="px-4 py-3 text-center">{invoice.issueDate}</td>
                <td className="px-4 py-3 text-center">{invoice.reportDate || '-'}</td>
                <td className="px-4 py-3 text-center">
                  <span className={`text-xs px-2 py-1 rounded ${invoice.status === '전송완료' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
                    }`}>{invoice.status}</span>
                </td>
                <td className="px-4 py-3 text-center">
                  <div className="flex justify-center gap-1">
                    <button onClick={() => { setSelectedInvoice(invoice); setShowPanel(true); }}
                      className="p-1 hover:bg-gray-100 rounded" title="상세보기">
                      <Eye className="w-4 h-4 text-gray-500" />
                    </button>
                    <button onClick={() => alert('인쇄 미리보기')} className="p-1 hover:bg-gray-100 rounded" title="인쇄">
                      <Printer className="w-4 h-4 text-gray-500" />
                    </button>
                    {invoice.status !== '전송완료' && (
                      <button onClick={() => handleSendInvoice(invoice)} className="p-1 hover:bg-blue-100 rounded" title="국세청전송">
                        <Send className="w-4 h-4 text-blue-500" />
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
};

// 수금관리
const CollectionManagement = () => {
  const [search, setSearch] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [showPanel, setShowPanel] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);

  const [collections, setCollections] = useState([
    {
      id: 1, collectionNo: 'COL-251209-001', saleNo: 'SL-251203-001', customerCode: 'C002', customerName: 'LG전자',
      saleAmount: 5940000, collectedAmount: 5940000, remainAmount: 0, collectionDate: '2025-12-09',
      paymentMethod: '계좌이체', bankAccount: '국민 123-456-789012', memo: '정상 수금', status: '완료'
    },
    {
      id: 2, collectionNo: 'COL-251208-001', saleNo: 'SL-251201-001', customerCode: 'C001', customerName: '삼성전자',
      saleAmount: 13750000, collectedAmount: 7000000, remainAmount: 6750000, collectionDate: '2025-12-08',
      paymentMethod: '계좌이체', bankAccount: '신한 111-222-333444', memo: '1차 부분수금', status: '진행중'
    },
  ]);

  const statusFilters = [
    { id: 'all', label: '전체' },
    { id: '완료', label: '완료' },
    { id: '진행중', label: '진행중' },
  ];

  // 통계
  const totalSaleAmount = collections.reduce((sum, c) => sum + c.saleAmount, 0);
  const totalCollected = collections.reduce((sum, c) => sum + c.collectedAmount, 0);
  const totalRemain = collections.reduce((sum, c) => sum + c.remainAmount, 0);
  const completedCount = collections.filter(c => c.status === '완료').length;

  const filtered = collections.filter(c => {
    const matchSearch = c.collectionNo.toLowerCase().includes(search.toLowerCase()) ||
      c.customerName.includes(search) || c.saleNo.toLowerCase().includes(search.toLowerCase());
    const matchStatus = filterStatus === 'all' || c.status === filterStatus;
    return matchSearch && matchStatus;
  });

  const handleRegisterCollection = () => {
    setSelectedItem(null);
    setShowPanel(true);
  };

  return (
    <div className="space-y-6">
      <PageHeader icon={DollarSign} title="수금 목록" />

      {/* 통계 카드 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatCard icon={FileText} label="매출총액" value={`${totalSaleAmount.toLocaleString()}원`} color="blue" />
        <StatCard icon={Check} label="수금완료" value={`${totalCollected.toLocaleString()}원`} color="green" />
        <StatCard icon={AlertCircle} label="미수잔액" value={`${totalRemain.toLocaleString()}원`} color="red" />
        <StatCard icon={Users} label="완료건수" value={`${completedCount}건`} color="purple" />
      </div>

      {/* 필터 및 검색 */}
      <Card>
        <div className="flex justify-between items-center mb-4">
          <div className="flex gap-2">
            {statusFilters.map(filter => (
              <button
                key={filter.id}
                onClick={() => setFilterStatus(filter.id)}
                className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-full border transition-colors ${filterStatus === filter.id ? 'bg-gray-900 text-white border-gray-900' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                  }`}
              >
                {filter.label}
              </button>
            ))}
          </div>
          <div className="flex gap-2">
            <SearchInput value={search} onChange={setSearch} placeholder="수금번호, 거래처명 검색" />
            <Button variant="primary" onClick={handleRegisterCollection}><Plus className="w-4 h-4" /> 수금등록</Button>
          </div>
        </div>

        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left">수금번호</th>
              <th className="px-4 py-3 text-left">매출번호</th>
              <th className="px-4 py-3 text-left">거래처</th>
              <th className="px-4 py-3 text-right">매출금액</th>
              <th className="px-4 py-3 text-right">수금금액</th>
              <th className="px-4 py-3 text-right">잔액</th>
              <th className="px-4 py-3 text-center">수금일</th>
              <th className="px-4 py-3 text-center">결제방법</th>
              <th className="px-4 py-3 text-center">상태</th>
              <th className="px-4 py-3 text-center">관리</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map(col => (
              <tr key={col.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 font-medium text-blue-600">{col.collectionNo}</td>
                <td className="px-4 py-3 text-gray-600">{col.saleNo}</td>
                <td className="px-4 py-3">{col.customerName}</td>
                <td className="px-4 py-3 text-right">{col.saleAmount.toLocaleString()}</td>
                <td className="px-4 py-3 text-right text-green-600">{col.collectedAmount.toLocaleString()}</td>
                <td className="px-4 py-3 text-right text-red-600">{col.remainAmount.toLocaleString()}</td>
                <td className="px-4 py-3 text-center">{col.collectionDate}</td>
                <td className="px-4 py-3 text-center">{col.paymentMethod}</td>
                <td className="px-4 py-3 text-center">
                  <span className={`text-xs px-2 py-1 rounded ${col.status === '완료' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
                    }`}>{col.status}</span>
                </td>
                <td className="px-4 py-3 text-center">
                  <button onClick={() => { setSelectedItem(col); setShowPanel(true); }}
                    className="p-1 hover:bg-gray-100 rounded" title="상세보기">
                    <Eye className="w-4 h-4 text-gray-500" />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
};

// 미수금관리
const OutstandingManagement = () => {
  const [search, setSearch] = useState('');
  const [filterOverdue, setFilterOverdue] = useState('all');

  const outstandingData = [
    {
      id: 1, customerCode: 'C001', customerName: '삼성전자', creditGrade: 'A',
      totalAmount: 13750000, collectedAmount: 7000000, outstandingAmount: 6750000,
      dueDate: '2025-12-31', overdueDays: 0, lastCollectionDate: '2025-12-08', contactPerson: '김부장', phone: '010-1234-5678'
    },
    {
      id: 2, customerCode: 'C003', customerName: '현대건설', creditGrade: 'A',
      totalAmount: 35200000, collectedAmount: 0, outstandingAmount: 35200000,
      dueDate: '2026-01-05', overdueDays: 0, lastCollectionDate: '-', contactPerson: '이과장', phone: '010-2345-6789'
    },
    {
      id: 3, customerCode: 'C004', customerName: '대우건설', creditGrade: 'B',
      totalAmount: 8800000, collectedAmount: 0, outstandingAmount: 8800000,
      dueDate: '2025-12-01', overdueDays: 8, lastCollectionDate: '-', contactPerson: '박대리', phone: '010-3456-7890'
    },
  ];

  // 통계
  const totalOutstanding = outstandingData.reduce((sum, d) => sum + d.outstandingAmount, 0);
  const overdueAmount = outstandingData.filter(d => d.overdueDays > 0).reduce((sum, d) => sum + d.outstandingAmount, 0);
  const overdueCount = outstandingData.filter(d => d.overdueDays > 0).length;
  const customerCount = outstandingData.length;

  const filtered = outstandingData.filter(d => {
    const matchSearch = d.customerCode.toLowerCase().includes(search.toLowerCase()) ||
      d.customerName.includes(search);
    const matchOverdue = filterOverdue === 'all' ||
      (filterOverdue === 'overdue' && d.overdueDays > 0) ||
      (filterOverdue === 'normal' && d.overdueDays === 0);
    return matchSearch && matchOverdue;
  });

  // 공통 UX: 미수금 목록 선택
  const {
    selectedIds: outstandingSelectedIds,
    handleSelect: handleOutstandingSelect,
    handleSelectAll: handleOutstandingSelectAll,
    isAllSelected: isOutstandingAllSelected,
    hasSelection: hasOutstandingSelection,
    isMultiSelect: isOutstandingMultiSelect,
    isSelected: isOutstandingSelected,
  } = useListSelection(filtered);

  const [showDeleteModal, setShowDeleteModal] = useState(false);

  return (
    <div className="space-y-6">
      <PageHeader icon={AlertCircle} title="미수금 목록" />

      {/* 통계 카드 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatCard icon={DollarSign} label="총 미수금" value={`${totalOutstanding.toLocaleString()}원`} color="blue" />
        <StatCard icon={AlertTriangle} label="연체금액" value={`${overdueAmount.toLocaleString()}원`} color="red" />
        <StatCard icon={Clock} label="연체건수" value={`${overdueCount}건`} color="orange" />
        <StatCard icon={Users} label="미수거래처" value={`${customerCount}개사`} color="purple" />
      </div>

      {/* 필터 및 검색 */}
      <Card>
        <div className="flex justify-between items-center mb-4">
          <div className="flex gap-2">
            {[
              { id: 'all', label: '전체' },
              { id: 'overdue', label: '연체' },
              { id: 'normal', label: '정상' },
            ].map(filter => (
              <button
                key={filter.id}
                onClick={() => setFilterOverdue(filter.id)}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${filterOverdue === filter.id ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
              >
                {filter.label}
              </button>
            ))}
          </div>
          <div className="flex gap-2">
            <SearchInput value={search} onChange={setSearch} placeholder="거래처코드, 거래처명 검색" />
            {isOutstandingMultiSelect && (
              <Button variant="outline" onClick={() => alert('선택된 거래처에 독촉장 발송')}>
                <Send className="w-4 h-4" /> 선택 독촉장 ({outstandingSelectedIds.length})
              </Button>
            )}
            <Button variant="outline" onClick={() => alert('독촉장 발송 기능')}><Send className="w-4 h-4" /> 독촉장발송</Button>
          </div>
        </div>

        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-center w-10">
                <input type="checkbox" checked={isOutstandingAllSelected} onChange={handleOutstandingSelectAll} className="rounded" />
              </th>
              <th className="px-4 py-3 text-left">거래처코드</th>
              <th className="px-4 py-3 text-left">거래처명</th>
              <th className="px-4 py-3 text-center">신용등급</th>
              <th className="px-4 py-3 text-right">매출총액</th>
              <th className="px-4 py-3 text-right">수금액</th>
              <th className="px-4 py-3 text-right">미수금</th>
              <th className="px-4 py-3 text-center">결제예정일</th>
              <th className="px-4 py-3 text-center">연체일수</th>
              <th className="px-4 py-3 text-center">최종수금일</th>
              <th className="px-4 py-3 text-left">담당자</th>
              <th className="px-4 py-3 text-center">관리</th>
              {hasOutstandingSelection && <th className="px-4 py-3 text-center">작업</th>}
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map(row => (
              <tr key={row.id} className={`hover:bg-gray-50 ${isOutstandingSelected(row.id) ? 'bg-blue-50' : row.overdueDays > 0 ? 'bg-red-50' : ''}`}>
                <td className="px-4 py-3 text-center">
                  <input type="checkbox" checked={isOutstandingSelected(row.id)} onChange={() => handleOutstandingSelect(row.id)} className="rounded" />
                </td>
                <td className="px-4 py-3 font-medium">{row.customerCode}</td>
                <td className="px-4 py-3">{row.customerName}</td>
                <td className="px-4 py-3 text-center">
                  <span className={`px-2 py-1 rounded text-xs font-medium ${row.creditGrade === 'A' ? 'bg-green-100 text-green-700' :
                      row.creditGrade === 'B' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'
                    }`}>{row.creditGrade}</span>
                </td>
                <td className="px-4 py-3 text-right">{row.totalAmount.toLocaleString()}</td>
                <td className="px-4 py-3 text-right text-green-600">{row.collectedAmount.toLocaleString()}</td>
                <td className="px-4 py-3 text-right font-medium text-red-600">{row.outstandingAmount.toLocaleString()}</td>
                <td className="px-4 py-3 text-center">{row.dueDate}</td>
                <td className="px-4 py-3 text-center">
                  {row.overdueDays > 0 ? (
                    <span className="text-red-600 font-medium">{row.overdueDays}일</span>
                  ) : (
                    <span className="text-gray-400">-</span>
                  )}
                </td>
                <td className="px-4 py-3 text-center">{row.lastCollectionDate}</td>
                <td className="px-4 py-3">
                  <div className="text-sm">{row.contactPerson}</div>
                  <div className="text-xs text-gray-500">{row.phone}</div>
                </td>
                <td className="px-4 py-3 text-center">
                  <div className="flex justify-center gap-1">
                    <button className="p-1 hover:bg-gray-100 rounded" title="상세보기">
                      <Eye className="w-4 h-4 text-gray-500" />
                    </button>
                    <button className="p-1 hover:bg-blue-100 rounded" title="전화">
                      <Phone className="w-4 h-4 text-blue-500" />
                    </button>
                  </div>
                </td>
                {hasOutstandingSelection && isOutstandingSelected(row.id) && (
                  <td className="px-4 py-3 text-center">
                    <div className="flex justify-center gap-1">
                      <Button variant="outline" size="sm" onClick={() => alert('수금 등록')}>
                        <Edit3 className="w-3 h-3" /> 수금
                      </Button>
                      <Button variant="outline" size="sm" onClick={() => alert('독촉장 발송')}>
                        <Send className="w-3 h-3" /> 독촉
                      </Button>
                    </div>
                  </td>
                )}
                {hasOutstandingSelection && !isOutstandingSelected(row.id) && <td className="px-4 py-3"></td>}
              </tr>
            ))}
          </tbody>
        </table>

        {/* 연체 경고 */}
        {overdueCount > 0 && (
          <div className="mt-4 p-4 bg-red-50 border border-red-200 rounded-lg">
            <div className="flex items-center gap-2 text-red-700">
              <AlertTriangle className="w-5 h-5" />
              <span className="font-medium">연체 경고: {overdueCount}건의 미수금이 결제예정일을 초과했습니다.</span>
            </div>
            <p className="mt-1 text-sm text-red-600">총 연체금액: {overdueAmount.toLocaleString()}원</p>
          </div>
        )}
      </Card>
    </div>
  );
};

// =============================================
// 회계관리 추가 컴포넌트 (기능정의서 A0~A5 기준)
// =============================================

// 회계관리 거래처 샘플 데이터
const accCustomerData = [
  { id: 1, customerCode: 'CUS-001', customerName: '삼성물산(주)', customerType: '매출', businessNo: '1248100998', ceoName: '오세철', phone: '02-2145-2114', creditGrade: 'A', creditLimit: 500000000, usedCredit: 320000000, paymentTerm: '60일', receivableTotal: 85000000, receivableOverdue: 0, overdueDays: 0, isActive: true, requireApproval: false, isCreditWarning: false },
  { id: 2, customerCode: 'CUS-002', customerName: '현대건설(주)', customerType: '매출', businessNo: '1018116756', ceoName: '윤영준', phone: '02-746-1114', creditGrade: 'A', creditLimit: 800000000, usedCredit: 450000000, paymentTerm: '60일', receivableTotal: 120000000, receivableOverdue: 0, overdueDays: 0, isActive: true, requireApproval: false, isCreditWarning: false },
  { id: 3, customerCode: 'CUS-003', customerName: '대우건설(주)', customerType: '매출', businessNo: '1168108831', ceoName: '백정완', phone: '02-2109-3114', creditGrade: 'B', creditLimit: 300000000, usedCredit: 280000000, paymentTerm: '30일', receivableTotal: 95000000, receivableOverdue: 15000000, overdueDays: 35, isActive: true, requireApproval: true, isCreditWarning: true },
  { id: 4, customerCode: 'CUS-004', customerName: '(주)서울인테리어', customerType: '매출', businessNo: '2148556789', ceoName: '정서울', phone: '02-555-1234', creditGrade: 'C', creditLimit: 50000000, usedCredit: 48000000, paymentTerm: '현금', receivableTotal: 32000000, receivableOverdue: 25000000, overdueDays: 62, isActive: true, requireApproval: true, isCreditWarning: true },
  { id: 5, customerCode: 'SUP-001', customerName: '(주)한국스크린', customerType: '매입', businessNo: '3148109876', ceoName: '이원단', phone: '031-481-5500', creditGrade: 'A', creditLimit: 0, usedCredit: 0, paymentTerm: '30일', receivableTotal: 0, receivableOverdue: 0, overdueDays: 0, isActive: true, requireApproval: false, isCreditWarning: false },
];

// 회계관리 거래처 목록 (판매관리 스타일)
const AccCustomerList = ({ onNavigate }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const { selectedIds, handleSelect, handleSelectAll, isAllSelected, hasSelection, isMultiSelect, isSelected } = useListSelection(accCustomerData);
  const tabs = [{ id: 'all', label: '전체', count: accCustomerData.length }, { id: 'sales', label: '매출거래처', count: accCustomerData.filter(c => c.customerType === '매출').length }, { id: 'purchase', label: '매입거래처', count: accCustomerData.filter(c => c.customerType === '매입').length }, { id: 'warning', label: '신용위험', count: accCustomerData.filter(c => c.isCreditWarning).length }];
  const filteredData = accCustomerData.filter(item => { if (activeTab === 'sales') return item.customerType === '매출'; if (activeTab === 'purchase') return item.customerType === '매입'; if (activeTab === 'warning') return item.isCreditWarning; return true; }).filter(item => item.customerCode.toLowerCase().includes(searchTerm.toLowerCase()) || item.customerName.toLowerCase().includes(searchTerm.toLowerCase())).sort((a, b) => b.id - a.id);
  const getGradeBadge = (grade) => { const colors = { A: 'bg-green-100 text-green-800', B: 'bg-yellow-100 text-yellow-800', C: 'bg-red-100 text-red-800' }; const labels = { A: '우량', B: '관리', C: '위험' }; return <span className={`px-2 py-0.5 rounded text-xs font-medium ${colors[grade]}`}>{grade} ({labels[grade]})</span>; };
  const formatCurrency = (val) => val ? `${val.toLocaleString()}원` : '-';
  const totalReceivable = accCustomerData.filter(c => c.customerType === '매출').reduce((sum, c) => sum + c.receivableTotal, 0);
  const overdueReceivable = accCustomerData.reduce((sum, c) => sum + c.receivableOverdue, 0);
  const warningCount = accCustomerData.filter(c => c.isCreditWarning).length;
  const creditCustomers = accCustomerData.filter(c => c.creditLimit > 0);
  const avgCreditUsage = creditCustomers.length > 0 ? Math.round(creditCustomers.reduce((sum, c) => sum + (c.usedCredit / c.creditLimit * 100), 0) / creditCustomers.length) : 0;
  return (<div className="space-y-6"><div className="space-y-3"><h1 className="text-xl font-bold text-gray-900 flex items-center gap-2"><CreditCard className="w-6 h-6 text-blue-500" />거래처 목록</h1><div className="flex items-center justify-end"><Button variant="primary" onClick={() => onNavigate('acc-customer-register')}><Plus className="w-4 h-4" /> 거래처 등록</Button></div></div><div className="grid grid-cols-4 gap-4"><DashboardCard title="총 미수금" value={formatCurrency(totalReceivable)} /><DashboardCard title="연체 미수금" value={formatCurrency(overdueReceivable)} /><DashboardCard title="신용위험 거래처" value={`${warningCount}건`} /><DashboardCard title="평균 여신사용률" value={`${avgCreditUsage}%`} /></div><div className="relative"><Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" /><input type="text" placeholder="거래처코드, 거래처명 검색..." className="w-full pl-12 pr-4 py-3 border rounded-xl" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} /></div><TabFilter tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />{isMultiSelect && <div className="flex justify-end"><Button variant="outline" size="sm" onClick={() => alert(`${selectedIds.length}건 선택 삭제`)}>선택 삭제 ({selectedIds.length})</Button></div>}<Card><div className="overflow-x-auto"><table className="w-full text-sm"><thead className="bg-gray-50 border-b"><tr><th className="p-3 text-left w-10"><input type="checkbox" checked={isAllSelected} onChange={handleSelectAll} /></th><th className="p-3 text-left">거래처코드</th><th className="p-3 text-left">거래처명</th><th className="p-3 text-left">구분</th><th className="p-3 text-left">신용등급</th><th className="p-3 text-left">결제조건</th><th className="p-3 text-right">여신한도</th><th className="p-3 text-right">사용금액</th><th className="p-3 text-right">미수금</th><th className="p-3 text-center">상태</th>{hasSelection && <th className="p-3 text-center">작업</th>}</tr></thead><tbody>{filteredData.map(item => (<tr key={item.id} className={`border-b hover:bg-gray-50 cursor-pointer ${isSelected(item.id) ? 'bg-blue-50' : ''}`} onClick={() => onNavigate('acc-customer-detail', item)}><td className="p-3" onClick={e => e.stopPropagation()}><input type="checkbox" checked={isSelected(item.id)} onChange={() => handleSelect(item.id)} /></td><td className="p-3 font-mono text-blue-600">{item.customerCode}</td><td className="p-3 font-medium">{item.customerName}</td><td className="p-3">{item.customerType}</td><td className="p-3">{getGradeBadge(item.creditGrade)}</td><td className="p-3">{item.paymentTerm}</td><td className="p-3 text-right">{formatCurrency(item.creditLimit)}</td><td className="p-3 text-right">{formatCurrency(item.usedCredit)}</td><td className="p-3 text-right"><span className={item.receivableOverdue > 0 ? 'text-red-600 font-medium' : ''}>{formatCurrency(item.receivableTotal)}</span></td><td className="p-3 text-center">{item.isCreditWarning ? <span className="px-2 py-0.5 bg-red-100 text-red-700 rounded text-xs">위험</span> : <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">정상</span>}</td>{hasSelection && <td className="p-3 text-center" onClick={e => e.stopPropagation()}>{isSelected(item.id) && <div className="flex justify-center gap-1"><Button size="xs" variant="outline" onClick={() => onNavigate('acc-customer-edit', item)}>수정</Button><Button size="xs" variant="outline" onClick={() => alert('삭제')}>삭제</Button></div>}</td>}</tr>))}</tbody></table></div></Card></div>);
};

// 회계관리 거래처 상세
const AccCustomerDetail = ({ customer, onNavigate }) => {
  if (!customer) return <div className="p-8 text-center text-gray-500">거래처를 선택해주세요.</div>;
  const formatCurrency = (val) => val ? `${val.toLocaleString()}원` : '-';
  const getGradeLabel = (grade) => { const labels = { A: 'A (우량)', B: 'B (관리)', C: 'C (위험)' }; return labels[grade] || grade; };
  const availableCredit = customer.creditLimit - customer.usedCredit;
  const creditUsageRate = customer.creditLimit > 0 ? Math.round((customer.usedCredit / customer.creditLimit) * 100) : 0;

  return (
    <div className="space-y-6">
      {/* 헤더 - 타이틀/버튼 분리 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
          <CreditCard className="w-6 h-6 text-blue-500" />
          거래처 상세
        </h1>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <button className="flex items-center gap-1 px-3 py-1.5 text-sm border rounded hover:bg-gray-50">
              <Printer className="w-4 h-4" /> 거래원장
            </button>
            <button className="flex items-center gap-1 px-3 py-1.5 text-sm border rounded hover:bg-gray-50">
              <Printer className="w-4 h-4" /> 미수금명세서
            </button>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={() => onNavigate('acc-customer-list')}>목록</Button>
            <Button variant="primary" onClick={() => onNavigate('acc-customer-edit', customer)}>
              <Edit className="w-4 h-4" /> 수정
            </Button>
          </div>
        </div>
      </div>

      {/* 기본 정보 */}
      <Card title="기본 정보">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div><p className="text-sm text-gray-500">거래처코드</p><p className="font-medium font-mono">{customer.customerCode}</p></div>
          <div><p className="text-sm text-gray-500">거래처명</p><p className="font-medium">{customer.customerName}</p></div>
          <div><p className="text-sm text-gray-500">거래처구분</p><p className="font-medium">{customer.customerType}</p></div>
          <div><p className="text-sm text-gray-500">사업자번호</p><p className="font-medium">{customer.businessNo}</p></div>
          <div><p className="text-sm text-gray-500">대표자</p><p className="font-medium">{customer.ceoName}</p></div>
          <div><p className="text-sm text-gray-500">연락처</p><p className="font-medium">{customer.phone}</p></div>
        </div>
      </Card>

      {/* 신용/여신 정보 */}
      <Card title="신용/여신 정보">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div><p className="text-sm text-gray-500">신용등급</p><p className="font-medium">{getGradeLabel(customer.creditGrade)}</p></div>
          <div><p className="text-sm text-gray-500">결제조건</p><p className="font-medium">{customer.paymentTerm}</p></div>
          <div><p className="text-sm text-gray-500">여신한도</p><p className="font-medium">{formatCurrency(customer.creditLimit)}</p></div>
          <div><p className="text-sm text-gray-500">사용금액</p><p className="font-medium">{formatCurrency(customer.usedCredit)}</p></div>
          <div><p className="text-sm text-gray-500">가용여신</p><p className="font-medium">{formatCurrency(availableCredit)}</p></div>
          <div><p className="text-sm text-gray-500">여신사용률</p><p className="font-medium">{creditUsageRate}%</p></div>
        </div>
      </Card>

      {/* 미수금 현황 */}
      <Card title="미수금 현황">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div><p className="text-sm text-gray-500">총 미수금</p><p className="font-medium">{formatCurrency(customer.receivableTotal)}</p></div>
          <div><p className="text-sm text-gray-500">연체 미수금</p><p className="font-medium">{formatCurrency(customer.receivableOverdue)}</p></div>
          <div><p className="text-sm text-gray-500">연체일수</p><p className="font-medium">{customer.overdueDays}일</p></div>
        </div>
      </Card>

      {/* 프로세스 제어 */}
      <Card title="프로세스 제어">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div><p className="text-sm text-gray-500">수주 승인</p><p className="font-medium">{customer.requireApproval ? '회계승인 필요' : '자동승인'}</p></div>
          <div><p className="text-sm text-gray-500">신용상태</p><p className="font-medium">{customer.isCreditWarning ? '위험 (관리대상)' : '정상'}</p></div>
        </div>
      </Card>
    </div>
  );
};

// 회계관리 거래처 등록/수정
const AccCustomerRegister = ({ customer, onNavigate, isEdit = false }) => {
  const [formData, setFormData] = useState({ customerCode: customer?.customerCode || '', customerName: customer?.customerName || '', customerType: customer?.customerType || '매출', businessNo: customer?.businessNo || '', ceoName: customer?.ceoName || '', phone: customer?.phone || '', creditGrade: customer?.creditGrade || 'B', creditLimit: customer?.creditLimit || 0, paymentTerm: customer?.paymentTerm || '30일', requireApproval: customer?.requireApproval || false });
  const handleChange = (field, value) => setFormData(prev => ({ ...prev, [field]: value }));
  const handleSave = () => { alert(isEdit ? '수정되었습니다.' : '등록되었습니다.'); onNavigate('acc-customer-list'); };
  return (<div className="space-y-6"><div className="space-y-3"><h1 className="text-xl font-bold text-gray-900 flex items-center gap-2"><CreditCard className="w-6 h-6 text-blue-500" />거래처 {isEdit ? '수정' : '등록'}</h1><div className="flex items-center justify-end gap-2"><Button variant="outline" onClick={() => onNavigate('acc-customer-list')}>× 취소</Button><Button variant="primary" onClick={handleSave}><Save className="w-4 h-4" /> 저장</Button></div></div><Card title="기본 정보"><div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"><FormField label="거래처코드" required><TextInput value={formData.customerCode} onChange={e => handleChange('customerCode', e.target.value)} placeholder="CUS-001" /></FormField><FormField label="거래처명" required><TextInput value={formData.customerName} onChange={e => handleChange('customerName', e.target.value)} placeholder="거래처명 입력" /></FormField><FormField label="거래처구분" required><select className="w-full px-3 py-2 border rounded-lg" value={formData.customerType} onChange={e => handleChange('customerType', e.target.value)}><option value="매출">매출</option><option value="매입">매입</option><option value="매입매출">매입매출</option></select></FormField><FormField label="사업자번호"><TextInput value={formData.businessNo} onChange={e => handleChange('businessNo', e.target.value)} placeholder="0000000000" /></FormField><FormField label="대표자"><TextInput value={formData.ceoName} onChange={e => handleChange('ceoName', e.target.value)} placeholder="대표자명" /></FormField><FormField label="연락처"><TextInput value={formData.phone} onChange={e => handleChange('phone', e.target.value)} placeholder="02-0000-0000" /></FormField></div></Card><Card title="여신/결제 정보"><div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"><FormField label="신용등급" required><select className="w-full px-3 py-2 border rounded-lg" value={formData.creditGrade} onChange={e => handleChange('creditGrade', e.target.value)}><option value="A">A (우량)</option><option value="B">B (관리)</option><option value="C">C (위험)</option></select></FormField><FormField label="여신한도"><TextInput type="number" value={formData.creditLimit} onChange={e => handleChange('creditLimit', Number(e.target.value))} placeholder="0" /></FormField><FormField label="결제조건"><select className="w-full px-3 py-2 border rounded-lg" value={formData.paymentTerm} onChange={e => handleChange('paymentTerm', e.target.value)}><option value="현금">현금</option><option value="30일">30일</option><option value="60일">60일</option><option value="90일">90일</option></select></FormField></div></Card><Card title="프로세스 제어 설정"><div className="space-y-3"><label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={formData.requireApproval} onChange={e => handleChange('requireApproval', e.target.checked)} className="w-4 h-4" /><span className="text-sm">수주 시 회계 승인 필요</span></label></div></Card></div>);
};

// 거래처 신용등급 관리 (A0-1) - Legacy
const CustomerCreditManagement = ({ shipments = [], onUpdateShipment, mode = 'list' }) => {
  const [activeTab, setActiveTab] = useState('list');
  const [search, setSearch] = useState('');
  const [showPanel, setShowPanel] = useState(null);
  const [selectedCustomer, setSelectedCustomer] = useState(null);
  const [gradeFilter, setGradeFilter] = useState('all');

  // 신용등급별 프로세스 제어 규칙
  const creditGradeRules = {
    A: {
      name: '우량',
      groupName: '정상거래처',
      description: '입금지연 거의 없음, 거래이력 안정적',
      orderConfirm: '자동 승인',
      productionOrder: '자동',
      shipment: '자동',
      taxInvoice: '자동 발행',
      color: 'green',
    },
    B: {
      name: '관리',
      groupName: '관리대상거래처',
      description: '가끔 입금 지연 또는 할인 요청 발생',
      orderConfirm: '자동 승인',
      productionOrder: '자동',
      shipment: '입금 확인 후 출고',
      taxInvoice: '할인 적용 후 발행 가능',
      color: 'blue',
    },
    C: {
      name: '위험',
      groupName: '경리승인 거래처',
      description: '입금약속 미이행, 신용불량 이력',
      orderConfirm: '자동(생산 보류)',
      productionOrder: '경리 승인 후 진행',
      shipment: '입금 확인 후 출고',
      taxInvoice: '입금 후 발행 또는 경리 승인 필요',
      color: 'red',
    },
  };

  // 거래처 통합 마스터 데이터 (회계관리 기준)
  // customerType: 매출(판매처), 매입(구매처), 매입매출(양방향)
  // supplyType: 자재(자재공급업체), 외주(외주협력사) - 매입 거래처만 해당
  const [customers, setCustomers] = useState([
    // ========== 매출 거래처 (건설사 - 블라인드/셔터 납품처) ==========
    {
      id: 1, customerCode: 'CUS-001', customerName: '삼성물산(주)', businessNo: '124-81-00998',
      ceoName: '오세철', businessType: '건설업', businessItem: '종합건설',
      customerType: '매출',
      creditGrade: 'A', previousGrade: 'A', gradeDate: '2025-01-01',
      paymentTerms: '60일', paymentDay: 25,
      creditLimit: 200000000, usedCredit: 48890000, availableCredit: 151110000,
      contactPerson: '김건설', phone: '010-1234-5678', email: 'procurement@samsungcnt.com',
      address: '서울특별시 서초구 서초대로 74길 11',
      requireAccountingApproval: false, requirePaymentBeforeShipment: false, isCreditWarning: false,
      discountRate: 5, note: '대형 건설사 - 우량 거래처',
      transactions: { totalCount: 45, totalAmount: 580000000, lastDate: '2025-12-01' },
    },
    {
      id: 2, customerCode: 'CUS-002', customerName: '현대건설(주)', businessNo: '101-81-16756',
      ceoName: '윤영준', businessType: '건설업', businessItem: '종합건설',
      customerType: '매출',
      creditGrade: 'A', previousGrade: 'A', gradeDate: '2025-01-01',
      paymentTerms: '60일', paymentDay: 30,
      creditLimit: 150000000, usedCredit: 35200000, availableCredit: 114800000,
      contactPerson: '이현장', phone: '010-2345-6789', email: 'order@hdec.kr',
      address: '서울특별시 종로구 율곡로 75',
      requireAccountingApproval: false, requirePaymentBeforeShipment: false, isCreditWarning: false,
      discountRate: 5, note: '대형 건설사',
      transactions: { totalCount: 38, totalAmount: 890000000, lastDate: '2025-12-05' },
    },
    {
      id: 3, customerCode: 'CUS-003', customerName: '대우건설(주)', businessNo: '116-81-08831',
      ceoName: '백정완', businessType: '건설업', businessItem: '종합건설',
      customerType: '매출',
      creditGrade: 'B', previousGrade: 'A', gradeDate: '2025-09-01',
      paymentTerms: '30일', paymentDay: 30,
      creditLimit: 80000000, usedCredit: 28800000, availableCredit: 51200000,
      contactPerson: '박건설', phone: '010-3456-7890', email: 'purchase@dwconst.co.kr',
      address: '서울특별시 중구 을지로 170',
      requireAccountingApproval: false, requirePaymentBeforeShipment: true, isCreditWarning: false,
      discountRate: 2, note: '결제 지연 이력 있음 - 등급 하향',
      transactions: { totalCount: 22, totalAmount: 420000000, lastDate: '2025-11-28' },
    },
    {
      id: 4, customerCode: 'CUS-004', customerName: '(주)서울인테리어', businessNo: '214-85-56789',
      ceoName: '정서울', businessType: '건설업', businessItem: '실내건축',
      customerType: '매출',
      creditGrade: 'B', previousGrade: 'B', gradeDate: '2025-01-01',
      paymentTerms: '30일', paymentDay: 25,
      creditLimit: 30000000, usedCredit: 12000000, availableCredit: 18000000,
      contactPerson: '김담당', phone: '010-4567-8901', email: 'order@seoulinterior.co.kr',
      address: '서울특별시 강남구 테헤란로 123',
      requireAccountingApproval: false, requirePaymentBeforeShipment: true, isCreditWarning: false,
      discountRate: 0, note: '중소 인테리어 업체',
      transactions: { totalCount: 15, totalAmount: 85000000, lastDate: '2025-12-03' },
    },
    {
      id: 5, customerCode: 'CUS-005', customerName: '신흥건설(주)', businessNo: '567-89-01234',
      ceoName: '정민수', businessType: '건설업', businessItem: '전문건설',
      customerType: '매출',
      creditGrade: 'C', previousGrade: 'B', gradeDate: '2025-11-01',
      paymentTerms: '선입금필수', paymentDay: null,
      creditLimit: 20000000, usedCredit: 15000000, availableCredit: 5000000,
      contactPerson: '정사원', phone: '010-5678-9012', email: 'jung@shinheung.com',
      address: '경기도 성남시 분당구 판교로 228',
      requireAccountingApproval: true, requirePaymentBeforeShipment: true, isCreditWarning: true,
      discountRate: 0, note: '신용불량 경고 - 경리승인 필요',
      transactions: { totalCount: 8, totalAmount: 95000000, lastDate: '2025-10-15' },
    },
    // ========== 매입 거래처 - 자재 (자재 공급업체) ==========
    {
      id: 6, customerCode: 'SUP-001', customerName: '(주)한국스크린', businessNo: '314-81-09876',
      ceoName: '이원단', businessType: '제조업', businessItem: '섬유제품',
      customerType: '매입', supplyType: '자재',
      creditGrade: 'A', previousGrade: 'A', gradeDate: '2025-01-01',
      paymentTerms: '30일', paymentDay: 25,
      creditLimit: null, usedCredit: null, availableCredit: null,
      contactPerson: '최판매', phone: '010-6789-0123', email: 'sales@koreascreen.co.kr',
      address: '경기도 안산시 단원구 산업로 200',
      requireAccountingApproval: false, requirePaymentBeforeShipment: false, isCreditWarning: false,
      discountRate: 0, note: '스크린 원단 주력 공급처',
      transactions: { totalCount: 52, totalAmount: 180000000, lastDate: '2025-12-10' },
      supplyItems: ['스크린 원단', '방화스크린 원단'],
      purchasePrices: [
        { itemCode: 'RM-SCR-1016', itemName: '스크린 원단 1016', price: 15000, unit: 'M', effectiveDate: '2025-01-01' },
        { itemCode: 'RM-SCR-1520', itemName: '스크린 원단 1520', price: 18000, unit: 'M', effectiveDate: '2025-01-01' },
        { itemCode: 'RM-SCR-FIRE', itemName: '방화스크린 원단', price: 35000, unit: 'M', effectiveDate: '2025-01-01' },
      ],
    },
    {
      id: 7, customerCode: 'SUP-002', customerName: '(주)대한슬랫', businessNo: '416-82-05432',
      ceoName: '박슬랫', businessType: '제조업', businessItem: '금속제품',
      customerType: '매입', supplyType: '자재',
      creditGrade: 'A', previousGrade: 'A', gradeDate: '2025-01-01',
      paymentTerms: '30일', paymentDay: 25,
      creditLimit: null, usedCredit: null, availableCredit: null,
      contactPerson: '정자재', phone: '010-7890-1234', email: 'order@dhslat.co.kr',
      address: '경기도 화성시 정남면 공단로 50',
      requireAccountingApproval: false, requirePaymentBeforeShipment: false, isCreditWarning: false,
      discountRate: 0, note: '슬랫 주력 공급처',
      transactions: { totalCount: 48, totalAmount: 220000000, lastDate: '2025-12-08' },
      supplyItems: ['알루미늄 슬랫', '우드 슬랫'],
      purchasePrices: [
        { itemCode: 'RM-SLT-AL25', itemName: '알루미늄 슬랫 25mm', price: 2500, unit: 'EA', effectiveDate: '2025-01-01' },
        { itemCode: 'RM-SLT-AL50', itemName: '알루미늄 슬랫 50mm', price: 4500, unit: 'EA', effectiveDate: '2025-01-01' },
        { itemCode: 'RM-SLT-WD50', itemName: '우드 슬랫 50mm', price: 6000, unit: 'EA', effectiveDate: '2025-01-01' },
      ],
    },
    {
      id: 8, customerCode: 'SUP-003', customerName: '(주)세종철강', businessNo: '514-83-06543',
      ceoName: '김철강', businessType: '제조업', businessItem: '철강제품',
      customerType: '매입', supplyType: '자재',
      creditGrade: 'B', previousGrade: 'A', gradeDate: '2025-06-01',
      paymentTerms: '현금', paymentDay: null,
      creditLimit: null, usedCredit: null, availableCredit: null,
      contactPerson: '이철판', phone: '010-8901-2345', email: 'supply@sejongsteel.co.kr',
      address: '충청남도 당진시 송악읍 철강로 100',
      requireAccountingApproval: false, requirePaymentBeforeShipment: false, isCreditWarning: false,
      discountRate: 0, note: '철강 자재 공급처',
      transactions: { totalCount: 25, totalAmount: 95000000, lastDate: '2025-12-01' },
      supplyItems: ['철판', '아연도금강판', '스테인리스'],
      purchasePrices: [
        { itemCode: 'RM-STL-1.0', itemName: '철판 1.0T', price: 85000, unit: 'SHEET', effectiveDate: '2025-01-01' },
        { itemCode: 'RM-STL-1.2', itemName: '철판 1.2T', price: 95000, unit: 'SHEET', effectiveDate: '2025-01-01' },
        { itemCode: 'RM-GAL-1.0', itemName: '아연도금강판 1.0T', price: 120000, unit: 'SHEET', effectiveDate: '2025-01-01' },
      ],
    },
    {
      id: 9, customerCode: 'SUP-004', customerName: '(주)동양모터', businessNo: '612-84-07654',
      ceoName: '최모터', businessType: '제조업', businessItem: '전기기기',
      customerType: '매입', supplyType: '자재',
      creditGrade: 'A', previousGrade: 'A', gradeDate: '2025-01-01',
      paymentTerms: '30일', paymentDay: 25,
      creditLimit: null, usedCredit: null, availableCredit: null,
      contactPerson: '강전기', phone: '010-9012-3456', email: 'sales@dongyang-motor.co.kr',
      address: '경기도 부천시 오정구 산업로 88',
      requireAccountingApproval: false, requirePaymentBeforeShipment: false, isCreditWarning: false,
      discountRate: 0, note: '모터/컨트롤러 주력 공급처',
      transactions: { totalCount: 38, totalAmount: 150000000, lastDate: '2025-12-09' },
      supplyItems: ['셔터 모터', '블라인드 모터', '컨트롤러'],
      purchasePrices: [
        { itemCode: 'RM-MTR-SH300', itemName: '셔터모터 300W', price: 85000, unit: 'EA', effectiveDate: '2025-01-01' },
        { itemCode: 'RM-MTR-SH500', itemName: '셔터모터 500W', price: 120000, unit: 'EA', effectiveDate: '2025-01-01' },
        { itemCode: 'RM-MTR-BL', itemName: '블라인드모터', price: 45000, unit: 'EA', effectiveDate: '2025-01-01' },
        { itemCode: 'RM-CTR-01', itemName: '리모컨 컨트롤러', price: 25000, unit: 'EA', effectiveDate: '2025-01-01' },
      ],
    },
    // ========== 매입 거래처 - 외주 (외주협력사) ==========
    {
      id: 10, customerCode: 'PAR-001', customerName: '(주)금성도금', businessNo: '615-84-07654',
      ceoName: '최도금', businessType: '제조업', businessItem: '표면처리',
      customerType: '매입', supplyType: '외주',
      creditGrade: 'B', previousGrade: 'B', gradeDate: '2025-01-01',
      paymentTerms: '30일', paymentDay: 25,
      creditLimit: null, usedCredit: null, availableCredit: null,
      contactPerson: '박협력', phone: '010-0123-4567', email: 'work@ksplating.co.kr',
      address: '경기도 시흥시 정왕동 공단로 88',
      requireAccountingApproval: false, requirePaymentBeforeShipment: false, isCreditWarning: false,
      discountRate: 0, note: '도금가공 협력사',
      transactions: { totalCount: 65, totalAmount: 85000000, lastDate: '2025-12-11' },
      partnerType: '도금가공',
      processingPrices: [
        { processName: '아연도금', price: 500, unit: 'EA', effectiveDate: '2025-01-01' },
        { processName: '크롬도금', price: 800, unit: 'EA', effectiveDate: '2025-01-01' },
        { processName: '니켈도금', price: 700, unit: 'EA', effectiveDate: '2025-01-01' },
      ],
    },
    {
      id: 11, customerCode: 'PAR-002', customerName: '(주)대성분체도장', businessNo: '718-85-08765',
      ceoName: '한분체', businessType: '제조업', businessItem: '표면처리',
      customerType: '매입', supplyType: '외주',
      creditGrade: 'A', previousGrade: 'A', gradeDate: '2025-01-01',
      paymentTerms: '30일', paymentDay: 25,
      creditLimit: null, usedCredit: null, availableCredit: null,
      contactPerson: '김도장', phone: '010-1234-5670', email: 'work@dscoating.co.kr',
      address: '경기도 시흥시 정왕동 공단로 120',
      requireAccountingApproval: false, requirePaymentBeforeShipment: false, isCreditWarning: false,
      discountRate: 0, note: '분체도장 협력사',
      transactions: { totalCount: 72, totalAmount: 120000000, lastDate: '2025-12-10' },
      partnerType: '분체도장',
      processingPrices: [
        { processName: '분체도장(백색)', price: 600, unit: 'EA', effectiveDate: '2025-01-01' },
        { processName: '분체도장(유색)', price: 700, unit: 'EA', effectiveDate: '2025-01-01' },
        { processName: '분체도장(특수)', price: 1000, unit: 'EA', effectiveDate: '2025-01-01' },
      ],
    },
  ]);

  const tabs = [
    { id: 'list', label: '거래처 목록' },
    { id: 'credit', label: '신용등급 관리' },
    { id: 'process', label: '등급별 프로세스' },
    { id: 'history', label: '등급변경 이력' },
  ];

  // 통계 (매출 거래처만 - 매입 거래처는 신용한도 없음)
  const customerOnly = customers.filter(c => c.customerType === '매출');
  const gradeA = customerOnly.filter(c => c.creditGrade === 'A').length;
  const gradeB = customerOnly.filter(c => c.creditGrade === 'B').length;
  const gradeC = customerOnly.filter(c => c.creditGrade === 'C').length;
  const totalCreditLimit = customerOnly.reduce((sum, c) => sum + (c.creditLimit || 0), 0);
  const totalUsedCredit = customerOnly.reduce((sum, c) => sum + (c.usedCredit || 0), 0);

  const filtered = customers.filter(c => {
    const matchSearch = c.customerCode.toLowerCase().includes(search.toLowerCase()) ||
      c.customerName.includes(search) ||
      c.creditGrade.includes(search.toUpperCase());
    const matchGrade = gradeFilter === 'all' || c.creditGrade === gradeFilter;
    return matchSearch && matchGrade;
  });

  const handleChangeGrade = (customer, newGrade) => {
    const reason = prompt(`${customer.customerName}의 신용등급을 ${customer.creditGrade} → ${newGrade}로 변경합니다.\n변경 사유를 입력하세요:`);
    if (reason) {
      setCustomers(prev => prev.map(c =>
        c.id === customer.id ? {
          ...c,
          previousGrade: c.creditGrade,
          creditGrade: newGrade,
          gradeDate: new Date().toISOString().split('T')[0],
          note: `등급변경: ${c.creditGrade}→${newGrade} (${reason})`
        } : c
      ));
      alert(`신용등급이 변경되었습니다.\n${customer.customerName}: ${customer.creditGrade} → ${newGrade}`);
    }
  };

  return (
    <div className="space-y-6">
      <PageHeader icon={Building} title="신용등급 목록" />

      {/* 통계 카드 - 반응형 */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
        <StatCard icon={Award} label="A등급 (우량)" value={`${gradeA}개사`} color="green" />
        <StatCard icon={Shield} label="B등급 (관리)" value={`${gradeB}개사`} color="blue" />
        <StatCard icon={AlertTriangle} label="C등급 (위험)" value={`${gradeC}개사`} color="red" />
        <StatCard icon={DollarSign} label="총 여신한도" value={`${(totalCreditLimit / 100000000).toFixed(1)}억`} color="purple" />
        <StatCard icon={TrendingUp} label="여신사용률" value={`${Math.round(totalUsedCredit / totalCreditLimit * 100)}%`} color="orange" />
      </div>

      {/* 탭 */}
      <Card>
        <div className="flex justify-between items-center mb-4">
          <div className="flex flex-wrap gap-2">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-full border transition-colors ${activeTab === tab.id ? 'bg-gray-900 text-white border-gray-900' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                  }`}
              >
                <span>{tab.label}</span>
              </button>
            ))}
          </div>
          <div className="flex gap-2">
            <select
              value={gradeFilter}
              onChange={(e) => setGradeFilter(e.target.value)}
              className="px-3 py-2 border border-gray-200 rounded-lg text-sm"
            >
              <option value="all">전체 등급</option>
              <option value="A">A등급 (우량)</option>
              <option value="B">B등급 (관리)</option>
              <option value="C">C등급 (위험)</option>
            </select>
            <SearchInput value={search} onChange={setSearch} placeholder="거래처코드, 거래처명 검색" />
            <Button variant="primary" onClick={() => setShowPanel('create')}>
              <Plus className="w-4 h-4" /> 거래처 등록
            </Button>
          </div>
        </div>

        {activeTab === 'list' && (
          <div className="overflow-x-auto">
            <table className="w-full text-sm min-w-[900px]">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left">거래처코드</th>
                  <th className="px-4 py-3 text-left">거래처명</th>
                  <th className="px-4 py-3 text-center">신용등급</th>
                  <th className="px-4 py-3 text-center">이전등급</th>
                  <th className="px-4 py-3 text-center">결제조건</th>
                  <th className="px-4 py-3 text-right">여신한도</th>
                  <th className="px-4 py-3 text-right">사용금액</th>
                  <th className="px-4 py-3 text-right">잔여한도</th>
                  <th className="px-4 py-3 text-center">등급변경일</th>
                  <th className="px-4 py-3 text-center">관리</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {filtered.map(customer => (
                  <tr key={customer.id} className={`hover:bg-gray-50 ${customer.creditGrade === 'C' ? 'bg-red-50' : ''}`}>
                    <td className="px-4 py-3 font-mono text-blue-600">{customer.customerCode}</td>
                    <td className="px-4 py-3 font-medium">{customer.customerName}</td>
                    <td className="px-4 py-3 text-center">
                      <span className={`px-3 py-1 rounded-full text-xs font-bold ${customer.creditGrade === 'A' ? 'bg-green-100 text-green-700' :
                          customer.creditGrade === 'B' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'
                        }`}>{customer.creditGrade}등급</span>
                    </td>
                    <td className="px-4 py-3 text-center">
                      {customer.previousGrade !== customer.creditGrade ? (
                        <span className="text-gray-400">{customer.previousGrade}→{customer.creditGrade}</span>
                      ) : <span className="text-gray-300">-</span>}
                    </td>
                    <td className="px-4 py-3 text-center text-xs">{customer.paymentTerms}</td>
                    <td className="px-4 py-3 text-right">{customer.creditLimit ? customer.creditLimit.toLocaleString() : '-'}</td>
                    <td className="px-4 py-3 text-right text-orange-600">{customer.usedCredit ? customer.usedCredit.toLocaleString() : '-'}</td>
                    <td className="px-4 py-3 text-right text-green-600">{customer.availableCredit ? customer.availableCredit.toLocaleString() : '-'}</td>
                    <td className="px-4 py-3 text-center text-gray-500">{customer.gradeDate}</td>
                    <td className="px-4 py-3 text-center">
                      <div className="flex justify-center gap-1">
                        <button onClick={() => { setSelectedCustomer(customer); setShowPanel('detail'); }}
                          className="p-1 hover:bg-gray-100 rounded" title="상세보기">
                          <Eye className="w-4 h-4 text-gray-500" />
                        </button>
                        <button onClick={() => { setSelectedCustomer(customer); setShowPanel('grade'); }}
                          className="p-1 hover:bg-blue-100 rounded" title="등급변경">
                          <Edit className="w-4 h-4 text-blue-500" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {activeTab === 'credit' && (
          <div className="space-y-6">
            <div className="grid grid-cols-3 gap-4">
              {['A', 'B', 'C'].map(grade => {
                const rule = creditGradeRules[grade];
                const gradeCustomers = customers.filter(c => c.creditGrade === grade);
                return (
                  <div key={grade} className={`p-5 rounded-xl border-2 ${grade === 'A' ? 'border-green-200 bg-green-50' : grade === 'B' ? 'border-blue-200 bg-blue-50' : 'border-red-200 bg-red-50'}`}>
                    <div className="flex items-center justify-between mb-3">
                      <span className={`px-3 py-1 rounded-full text-sm font-bold ${grade === 'A' ? 'bg-green-500 text-white' : grade === 'B' ? 'bg-blue-500 text-white' : 'bg-red-500 text-white'}`}>
                        {grade}등급 - {rule.name}
                      </span>
                      <span className="text-lg font-bold">{gradeCustomers.length}개사</span>
                    </div>
                    <p className="text-sm text-gray-600 mb-3">{rule.description}</p>
                    <div className="text-sm space-y-1">
                      <div>여신총액: <span className="font-medium">{(gradeCustomers.reduce((sum, c) => sum + c.creditLimit, 0) / 100000000).toFixed(1)}억</span></div>
                      <div>사용금액: <span className="font-medium text-orange-600">{(gradeCustomers.reduce((sum, c) => sum + c.usedCredit, 0) / 100000000).toFixed(1)}억</span></div>
                    </div>
                    <div className="mt-3 pt-3 border-t border-gray-200">
                      <p className="text-xs text-gray-500">{rule.groupName}</p>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {activeTab === 'process' && (
          <div className="space-y-6">
            <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
              <p className="text-sm text-yellow-800">신용등급에 따라 수주확인, 생산지시, 출고, 세금계산서 발행 프로세스가 자동으로 제어됩니다.</p>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-100">
                  <tr>
                    <th className="px-4 py-3 text-left">프로세스</th>
                    <th className="px-4 py-3 text-center">
                      <span className="px-2 py-1 rounded bg-green-100 text-green-700 font-bold">A등급 (우량)</span>
                    </th>
                    <th className="px-4 py-3 text-center">
                      <span className="px-2 py-1 rounded bg-blue-100 text-blue-700 font-bold">B등급 (관리)</span>
                    </th>
                    <th className="px-4 py-3 text-center">
                      <span className="px-2 py-1 rounded bg-red-100 text-red-700 font-bold">C등급 (위험)</span>
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  <tr>
                    <td className="px-4 py-3 font-medium">수주확인</td>
                    <td className="px-4 py-3 text-center"><span className="text-green-600">{creditGradeRules.A.orderConfirm}</span></td>
                    <td className="px-4 py-3 text-center"><span className="text-blue-600">{creditGradeRules.B.orderConfirm}</span></td>
                    <td className="px-4 py-3 text-center"><span className="text-red-600">{creditGradeRules.C.orderConfirm}</span></td>
                  </tr>
                  <tr>
                    <td className="px-4 py-3 font-medium">생산지시</td>
                    <td className="px-4 py-3 text-center"><span className="text-green-600">{creditGradeRules.A.productionOrder}</span></td>
                    <td className="px-4 py-3 text-center"><span className="text-blue-600">{creditGradeRules.B.productionOrder}</span></td>
                    <td className="px-4 py-3 text-center"><span className="text-red-600">{creditGradeRules.C.productionOrder}</span></td>
                  </tr>
                  <tr>
                    <td className="px-4 py-3 font-medium">출고</td>
                    <td className="px-4 py-3 text-center"><span className="text-green-600">{creditGradeRules.A.shipment}</span></td>
                    <td className="px-4 py-3 text-center"><span className="text-blue-600">{creditGradeRules.B.shipment}</span></td>
                    <td className="px-4 py-3 text-center"><span className="text-red-600">{creditGradeRules.C.shipment}</span></td>
                  </tr>
                  <tr>
                    <td className="px-4 py-3 font-medium">세금계산서</td>
                    <td className="px-4 py-3 text-center"><span className="text-green-600">{creditGradeRules.A.taxInvoice}</span></td>
                    <td className="px-4 py-3 text-center"><span className="text-blue-600">{creditGradeRules.B.taxInvoice}</span></td>
                    <td className="px-4 py-3 text-center"><span className="text-red-600">{creditGradeRules.C.taxInvoice}</span></td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div className="grid grid-cols-3 gap-4 mt-6">
              <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                <h4 className="font-bold text-green-700 mb-2">A등급 - 정상거래처</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>- 모든 프로세스 자동 진행</li>
                  <li>- 여신한도 내 자유 거래</li>
                  <li>- 세금계산서 자동 발행</li>
                </ul>
              </div>
              <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
                <h4 className="font-bold text-blue-700 mb-2">B등급 - 관리대상거래처</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>- 출고 시 입금 확인 필요</li>
                  <li>- 할인 적용 시 주의</li>
                  <li>- 정기적 신용 재평가</li>
                </ul>
              </div>
              <div className="p-4 bg-red-50 rounded-lg border border-red-200">
                <h4 className="font-bold text-red-700 mb-2">C등급 - 경리승인 거래처</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>- 생산지시 전 경리 승인 필수</li>
                  <li>- 출고 전 입금 완료 필수</li>
                  <li>- 세금계산서 경리 승인 필요</li>
                </ul>
              </div>
            </div>
          </div>
        )}

        {activeTab === 'history' && (
          <div className="space-y-3">
            {[
              { date: '2025-11-01', customer: '신흥건설', from: 'B', to: 'C', reason: '연속 3회 결제 지연', by: '경리팀 김경리' },
              { date: '2025-09-01', customer: '대우건설', from: 'A', to: 'B', reason: '결제 지연 1회 발생', by: '경리팀 김경리' },
              { date: '2025-06-01', customer: 'LG전자', from: 'B', to: 'A', reason: '1년간 정상 결제', by: '경리팀 박회계' },
            ].map((log, i) => (
              <div key={i} className="flex items-center gap-4 p-4 bg-gray-50 rounded-lg">
                <div className="text-sm text-gray-500 w-24">{log.date}</div>
                <div className="font-medium w-32">{log.customer}</div>
                <div className="flex items-center gap-2">
                  <span className={`px-2 py-0.5 rounded text-xs ${log.from === 'A' ? 'bg-green-100 text-green-700' : log.from === 'B' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'}`}>{log.from}</span>
                  <ArrowRight className="w-4 h-4 text-gray-400" />
                  <span className={`px-2 py-0.5 rounded text-xs ${log.to === 'A' ? 'bg-green-100 text-green-700' : log.to === 'B' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'}`}>{log.to}</span>
                </div>
                <div className="flex-1 text-sm text-gray-600">{log.reason}</div>
                <div className="text-xs text-gray-400">{log.by}</div>
              </div>
            ))}
          </div>
        )}

        {activeTab === 'analysis' && (
          <div className="grid grid-cols-2 gap-6">
            <Card title="등급별 분포">
              <div className="space-y-4">
                {[
                  { grade: 'A', count: gradeA, color: 'green', desc: '우량 - 자동 출고' },
                  { grade: 'B', count: gradeB, color: 'blue', desc: '관리 - 입금확인 후 출고' },
                  { grade: 'C', count: gradeC, color: 'red', desc: '위험 - 경리승인 필요' },
                ].map(item => (
                  <div key={item.grade} className="flex items-center gap-3">
                    <span className={`w-16 px-2 py-1 text-center rounded font-bold text-sm bg-${item.color}-100 text-${item.color}-700`}>
                      {item.grade}등급
                    </span>
                    <div className="flex-1">
                      <div className="h-6 bg-gray-100 rounded-full overflow-hidden">
                        <div className={`h-full bg-${item.color}-500 rounded-full`}
                          style={{ width: `${(item.count / customers.length) * 100}%` }} />
                      </div>
                    </div>
                    <span className="w-16 text-right font-medium">{item.count}개사</span>
                    <span className="w-40 text-xs text-gray-500">{item.desc}</span>
                  </div>
                ))}
              </div>
            </Card>
            <Card title="여신한도 사용현황">
              <div className="space-y-4">
                {customers.slice(0, 5).map(c => (
                  <div key={c.id} className="flex items-center gap-3">
                    <span className="w-24 text-sm font-medium truncate">{c.customerName}</span>
                    <div className="flex-1">
                      <div className="h-4 bg-gray-100 rounded-full overflow-hidden">
                        <div className={`h-full rounded-full ${(c.usedCredit / c.creditLimit) > 0.8 ? 'bg-red-500' :
                            (c.usedCredit / c.creditLimit) > 0.5 ? 'bg-yellow-500' : 'bg-green-500'
                          }`} style={{ width: `${(c.usedCredit / c.creditLimit) * 100}%` }} />
                      </div>
                    </div>
                    <span className="w-12 text-right text-sm">{Math.round(c.usedCredit / c.creditLimit * 100)}%</span>
                  </div>
                ))}
              </div>
            </Card>
          </div>
        )}
      </Card>

      {/* 거래처 상세보기 모달 */}
      {showPanel === 'detail' && selectedCustomer && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold">거래처 상세정보</h3>
              <button onClick={() => setShowPanel(null)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4">
              <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-lg">
                <div className="flex-1">
                  <div className="flex items-center gap-3">
                    <span className="text-lg font-bold">{selectedCustomer.customerName}</span>
                    <span className={`px-3 py-1 rounded-full text-xs font-bold ${selectedCustomer.creditGrade === 'A' ? 'bg-green-100 text-green-700' : selectedCustomer.creditGrade === 'B' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'}`}>
                      {selectedCustomer.creditGrade}등급 ({creditGradeRules[selectedCustomer.creditGrade].name})
                    </span>
                    {selectedCustomer.isCreditWarning && (
                      <span className="px-2 py-1 rounded bg-red-500 text-white text-xs font-bold">신용경고</span>
                    )}
                  </div>
                  <p className="text-sm text-gray-500 mt-1">{selectedCustomer.customerCode} | {selectedCustomer.businessNo}</p>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-3">
                  <h4 className="font-medium text-gray-700 border-b pb-2">기본정보</h4>
                  <div className="grid grid-cols-2 gap-2 text-sm">
                    <div className="text-gray-500">대표자</div>
                    <div>{selectedCustomer.ceoName}</div>
                    <div className="text-gray-500">업태</div>
                    <div>{selectedCustomer.businessType}</div>
                    <div className="text-gray-500">종목</div>
                    <div>{selectedCustomer.businessItem}</div>
                    <div className="text-gray-500">주소</div>
                    <div className="col-span-2 -mt-6 ml-16">{selectedCustomer.address}</div>
                  </div>
                </div>
                <div className="space-y-3">
                  <h4 className="font-medium text-gray-700 border-b pb-2">담당자정보</h4>
                  <div className="grid grid-cols-2 gap-2 text-sm">
                    <div className="text-gray-500">담당자</div>
                    <div>{selectedCustomer.contactPerson}</div>
                    <div className="text-gray-500">연락처</div>
                    <div>{selectedCustomer.phone}</div>
                    <div className="text-gray-500">이메일</div>
                    <div>{selectedCustomer.email}</div>
                  </div>
                </div>
              </div>

              <div className="space-y-3">
                <h4 className="font-medium text-gray-700 border-b pb-2">신용/결제정보</h4>
                <div className="grid grid-cols-4 gap-4">
                  <div className="p-3 bg-blue-50 rounded-lg text-center">
                    <div className="text-xs text-gray-500">여신한도</div>
                    <div className="font-bold text-blue-600">{selectedCustomer.creditLimit ? `${(selectedCustomer.creditLimit / 10000).toLocaleString()}만` : '-'}</div>
                  </div>
                  <div className="p-3 bg-orange-50 rounded-lg text-center">
                    <div className="text-xs text-gray-500">사용금액</div>
                    <div className="font-bold text-orange-600">{selectedCustomer.usedCredit ? `${(selectedCustomer.usedCredit / 10000).toLocaleString()}만` : '-'}</div>
                  </div>
                  <div className="p-3 bg-green-50 rounded-lg text-center">
                    <div className="text-xs text-gray-500">잔여한도</div>
                    <div className="font-bold text-green-600">{selectedCustomer.availableCredit ? `${(selectedCustomer.availableCredit / 10000).toLocaleString()}만` : '-'}</div>
                  </div>
                  <div className="p-3 bg-gray-50 rounded-lg text-center">
                    <div className="text-xs text-gray-500">사용률</div>
                    <div className={`font-bold ${selectedCustomer.creditLimit && (selectedCustomer.usedCredit / selectedCustomer.creditLimit) > 0.8 ? 'text-red-600' : 'text-gray-600'}`}>
                      {selectedCustomer.creditLimit ? `${Math.round((selectedCustomer.usedCredit || 0) / selectedCustomer.creditLimit * 100)}%` : '-'}
                    </div>
                  </div>
                </div>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div><span className="text-gray-500">결제조건: </span><span className="font-medium">{selectedCustomer.paymentTerms}</span></div>
                  <div><span className="text-gray-500">결제일: </span><span className="font-medium">{selectedCustomer.paymentDay ? `매월 ${selectedCustomer.paymentDay}일` : '-'}</span></div>
                  <div><span className="text-gray-500">할인율: </span><span className="font-medium">{selectedCustomer.discountRate}%</span></div>
                </div>
              </div>

              <div className="space-y-3">
                <h4 className="font-medium text-gray-700 border-b pb-2">프로세스 제어</h4>
                <div className="grid grid-cols-3 gap-3">
                  <div className={`p-3 rounded-lg border ${selectedCustomer.requireAccountingApproval ? 'bg-red-50 border-red-200' : 'bg-gray-50 border-gray-200'}`}>
                    <div className="text-xs text-gray-500 mb-1">경리 승인</div>
                    <div className={`font-medium ${selectedCustomer.requireAccountingApproval ? 'text-red-600' : 'text-gray-600'}`}>
                      {selectedCustomer.requireAccountingApproval ? '필요' : '불필요'}
                    </div>
                  </div>
                  <div className={`p-3 rounded-lg border ${selectedCustomer.requirePaymentBeforeShipment ? 'bg-orange-50 border-orange-200' : 'bg-gray-50 border-gray-200'}`}>
                    <div className="text-xs text-gray-500 mb-1">입금 후 출고</div>
                    <div className={`font-medium ${selectedCustomer.requirePaymentBeforeShipment ? 'text-orange-600' : 'text-gray-600'}`}>
                      {selectedCustomer.requirePaymentBeforeShipment ? '필요' : '불필요'}
                    </div>
                  </div>
                  <div className={`p-3 rounded-lg border ${selectedCustomer.isCreditWarning ? 'bg-red-50 border-red-200' : 'bg-gray-50 border-gray-200'}`}>
                    <div className="text-xs text-gray-500 mb-1">신용경고</div>
                    <div className={`font-medium ${selectedCustomer.isCreditWarning ? 'text-red-600' : 'text-gray-600'}`}>
                      {selectedCustomer.isCreditWarning ? '경고 상태' : '정상'}
                    </div>
                  </div>
                </div>
              </div>

              <div className="space-y-3">
                <h4 className="font-medium text-gray-700 border-b pb-2">거래현황</h4>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div><span className="text-gray-500">총 거래횟수: </span><span className="font-medium">{selectedCustomer.transactions.totalCount}회</span></div>
                  <div><span className="text-gray-500">총 거래금액: </span><span className="font-medium">{(selectedCustomer.transactions.totalAmount / 100000000).toFixed(1)}억</span></div>
                  <div><span className="text-gray-500">최근 거래일: </span><span className="font-medium">{selectedCustomer.transactions.lastDate}</span></div>
                </div>
              </div>

              {selectedCustomer.note && (
                <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                  <p className="text-sm text-yellow-800">{selectedCustomer.note}</p>
                </div>
              )}

              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button variant="outline" onClick={() => setShowPanel(null)}>닫기</Button>
                <Button variant="outline" onClick={() => { setShowPanel('grade'); }}>등급 변경</Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 등급 변경 모달 */}
      {showPanel === 'grade' && selectedCustomer && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-md w-full mx-4">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold">신용등급 변경</h3>
              <button onClick={() => setShowPanel(null)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4">
              <div className="p-4 bg-gray-50 rounded-lg">
                <div className="grid grid-cols-2 gap-4">
                  <div><p className="text-sm text-gray-500">거래처</p><p className="font-medium">{selectedCustomer.customerName}</p></div>
                  <div><p className="text-sm text-gray-500">현재 등급</p><span className={`px-3 py-1 rounded-full text-xs font-bold ${selectedCustomer.creditGrade === 'A' ? 'bg-green-100 text-green-700' : selectedCustomer.creditGrade === 'B' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'}`}>{selectedCustomer.creditGrade}등급</span></div>
                </div>
              </div>
              <FormField label="변경할 등급" required>
                <div className="flex gap-3">
                  {['A', 'B', 'C'].map(grade => (
                    <button key={grade} onClick={() => handleChangeGrade(selectedCustomer, grade)} disabled={selectedCustomer.creditGrade === grade} className={`flex-1 p-4 rounded-lg border-2 text-center transition-colors ${selectedCustomer.creditGrade === grade ? 'border-gray-200 bg-gray-100 text-gray-400 cursor-not-allowed' : grade === 'A' ? 'border-green-200 hover:border-green-400 hover:bg-green-50' : grade === 'B' ? 'border-blue-200 hover:border-blue-400 hover:bg-blue-50' : 'border-red-200 hover:border-red-400 hover:bg-red-50'}`}>
                      <div className={`text-2xl font-bold ${grade === 'A' ? 'text-green-600' : grade === 'B' ? 'text-blue-600' : 'text-red-600'}`}>{grade}</div>
                      <div className="text-xs text-gray-500 mt-1">{grade === 'A' ? '우량' : grade === 'B' ? '관리' : '위험'}</div>
                    </button>
                  ))}
                </div>
              </FormField>
              <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                <p className="text-sm text-yellow-700">등급 변경 시 해당 거래처의 출고 조건이 자동으로 변경됩니다.</p>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 거래명세서 발행 (A1-1)
const TransactionStatementIssue = ({ shipments = [], onUpdateShipment, onNavigate }) => {
  const [search, setSearch] = useState('');
  const [filterStatus, setFilterStatus] = useState('pending');
  const [selectedItems, setSelectedItems] = useState([]);
  const [showPreview, setShowPreview] = useState(null);
  const [selectedTemplate, setSelectedTemplate] = useState('SL'); // 문서양식관리 연동

  // 문서양식관리에서 거래명세서 템플릿 가져오기
  const templateConfig = documentTemplateConfig.documentTemplates?.['SL'] || {
    name: '거래명세서',
    blocks: ['HDR-COMPANY', 'PTY-CUSTOMER', 'PTY-SUPPLIER', 'TBL-DELIVERY-ITEMS', 'AMT-TABLE']
  };

  // 출하완료 건 중 거래명세서 미발행 건
  const statementData = [
    {
      id: 1, shipmentNo: 'SH-251201-001', splitNo: 'KD-TS-251201-01-S1', orderNo: 'KD-TS-251201-01',
      customerName: '삼성전자', siteName: '삼성 서초사옥', shipmentDate: '2025-12-01',
      items: [{ name: '방화스크린 KSS01', qty: 5, unitPrice: 2500000, amount: 12500000 }],
      totalAmount: 12500000, vat: 1250000, grandTotal: 13750000,
      statementNo: '', statementDate: '', statementStatus: '미발행', sentMethod: '', sentDate: ''
    },
    {
      id: 2, shipmentNo: 'SH-251203-001', splitNo: 'KD-SL-251203-01-S1', orderNo: 'KD-SL-251203-01',
      customerName: 'LG전자', siteName: 'LG 트윈타워', shipmentDate: '2025-12-03',
      items: [{ name: '방화슬랫셔터 KSL01', qty: 3, unitPrice: 1800000, amount: 5400000 }],
      totalAmount: 5400000, vat: 540000, grandTotal: 5940000,
      statementNo: 'TS-251203-001', statementDate: '2025-12-03', statementStatus: '발행완료', sentMethod: '이메일', sentDate: '2025-12-03'
    },
    {
      id: 3, shipmentNo: 'SH-251205-001', splitNo: 'KD-BD-251205-01-S1', orderNo: 'KD-BD-251205-01',
      customerName: '현대건설', siteName: '현대 본사', shipmentDate: '2025-12-05',
      items: [{ name: '방화절곡셔터 KSB01', qty: 10, unitPrice: 3200000, amount: 32000000 }],
      totalAmount: 32000000, vat: 3200000, grandTotal: 35200000,
      statementNo: '', statementDate: '', statementStatus: '미발행', sentMethod: '', sentDate: ''
    },
  ];

  const [statements, setStatements] = useState(statementData);

  const statusFilters = [
    { id: 'all', label: '전체', count: statements.length },
    { id: 'pending', label: '미발행', count: statements.filter(s => s.statementStatus === '미발행').length },
    { id: 'issued', label: '발행완료', count: statements.filter(s => s.statementStatus === '발행완료').length },
  ];

  const filtered = statements.filter(s => {
    const matchSearch = s.shipmentNo.toLowerCase().includes(search.toLowerCase()) ||
      s.customerName.includes(search) || s.splitNo.toLowerCase().includes(search.toLowerCase());
    const matchStatus = filterStatus === 'all' ||
      (filterStatus === 'pending' && s.statementStatus === '미발행') ||
      (filterStatus === 'issued' && s.statementStatus === '발행완료');
    return matchSearch && matchStatus;
  });

  const handleIssueStatement = (item) => {
    const statementNo = `TS-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-${String(statements.filter(s => s.statementStatus === '발행완료').length + 1).padStart(3, '0')}`;
    setStatements(prev => prev.map(s =>
      s.id === item.id ? {
        ...s,
        statementNo,
        statementDate: new Date().toISOString().split('T')[0],
        statementStatus: '발행완료'
      } : s
    ));
    alert(`거래명세서가 발행되었습니다.\n명세서번호: ${statementNo}`);
  };

  const handleBulkIssue = () => {
    if (selectedItems.length === 0) {
      alert('발행할 건을 선택해주세요.');
      return;
    }
    const pendingItems = selectedItems.filter(id => {
      const item = statements.find(s => s.id === id);
      return item && item.statementStatus === '미발행';
    });
    if (pendingItems.length === 0) {
      alert('미발행 건만 발행할 수 있습니다.');
      return;
    }
    pendingItems.forEach((id, idx) => {
      const statementNo = `TS-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-${String(statements.filter(s => s.statementStatus === '발행완료').length + idx + 1).padStart(3, '0')}`;
      setStatements(prev => prev.map(s =>
        s.id === id ? { ...s, statementNo, statementDate: new Date().toISOString().split('T')[0], statementStatus: '발행완료' } : s
      ));
    });
    alert(`${pendingItems.length}건의 거래명세서가 발행되었습니다.`);
    setSelectedItems([]);
  };

  const handleSendStatement = (item, method) => {
    if (item.statementStatus !== '발행완료') {
      alert('먼저 거래명세서를 발행해주세요.');
      return;
    }
    setStatements(prev => prev.map(s =>
      s.id === item.id ? { ...s, sentMethod: method, sentDate: new Date().toISOString().split('T')[0] } : s
    ));
    alert(`거래명세서가 ${method}로 발송되었습니다.\n거래처: ${item.customerName}`);
  };

  return (
    <div className="space-y-6">
      <PageHeader icon={FileText} title="거래명세서 발행" />

      {/* 통계 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatCard icon={FileText} label="전체 건수" value={`${statements.length}건`} color="blue" />
        <StatCard icon={Clock} label="미발행" value={`${statements.filter(s => s.statementStatus === '미발행').length}건`} color="orange" />
        <StatCard icon={Check} label="발행완료" value={`${statements.filter(s => s.statementStatus === '발행완료').length}건`} color="green" />
        <StatCard icon={DollarSign} label="발행금액" value={`${statements.filter(s => s.statementStatus === '발행완료').reduce((sum, s) => sum + s.grandTotal, 0).toLocaleString()}원`} color="purple" />
      </div>

      <Card>
        <div className="flex justify-between items-center mb-4">
          <div className="flex gap-2">
            {statusFilters.map(filter => (
              <button
                key={filter.id}
                onClick={() => setFilterStatus(filter.id)}
                className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-full border transition-colors ${filterStatus === filter.id ? 'bg-gray-900 text-white border-gray-900' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                  }`}
              >
                {filter.label} ({filter.count})
              </button>
            ))}
          </div>
          <div className="flex gap-2">
            <SearchInput value={search} onChange={setSearch} placeholder="출하번호, 거래처명 검색" />
            <Button variant="primary" onClick={handleBulkIssue} disabled={selectedItems.length === 0}>
              <FileText className="w-4 h-4" /> 일괄발행 ({selectedItems.length})
            </Button>
          </div>
        </div>

        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left">
                <input
                  type="checkbox"
                  checked={filtered.length > 0 && selectedItems.length === filtered.length}
                  onChange={(e) => setSelectedItems(e.target.checked ? filtered.map(f => f.id) : [])}
                  className="rounded border-gray-300"
                />
              </th>
              <th className="px-4 py-3 text-left">출하번호</th>
              <th className="px-4 py-3 text-left">분할번호</th>
              <th className="px-4 py-3 text-left">거래처</th>
              <th className="px-4 py-3 text-left">현장명</th>
              <th className="px-4 py-3 text-center">출하일</th>
              <th className="px-4 py-3 text-right">공급가</th>
              <th className="px-4 py-3 text-right">합계</th>
              <th className="px-4 py-3 text-center">명세서번호</th>
              <th className="px-4 py-3 text-center">발행상태</th>
              <th className="px-4 py-3 text-center">발송</th>
              <th className="px-4 py-3 text-center">관리</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map(item => (
              <tr key={item.id} className={`hover:bg-gray-50 ${item.statementStatus === '미발행' ? 'bg-yellow-50' : ''}`}>
                <td className="px-4 py-3">
                  <input
                    type="checkbox"
                    checked={selectedItems.includes(item.id)}
                    onChange={(e) => setSelectedItems(prev =>
                      e.target.checked ? [...prev, item.id] : prev.filter(id => id !== item.id)
                    )}
                    className="rounded border-gray-300"
                  />
                </td>
                <td className="px-4 py-3 font-mono text-blue-600">{item.shipmentNo}</td>
                <td className="px-4 py-3 font-mono text-gray-600">{item.splitNo}</td>
                <td className="px-4 py-3 font-medium">{item.customerName}</td>
                <td className="px-4 py-3 text-gray-600 max-w-[120px] truncate">{item.siteName}</td>
                <td className="px-4 py-3 text-center">{item.shipmentDate}</td>
                <td className="px-4 py-3 text-right">{item.totalAmount.toLocaleString()}</td>
                <td className="px-4 py-3 text-right font-medium">{item.grandTotal.toLocaleString()}</td>
                <td className="px-4 py-3 text-center font-mono text-sm">{item.statementNo || '-'}</td>
                <td className="px-4 py-3 text-center">
                  <span className={`px-2 py-1 rounded text-xs ${item.statementStatus === '발행완료' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
                    }`}>{item.statementStatus}</span>
                </td>
                <td className="px-4 py-3 text-center">
                  {item.sentDate ? (
                    <span className="text-xs text-green-600">{item.sentMethod}</span>
                  ) : (
                    <span className="text-gray-300">-</span>
                  )}
                </td>
                <td className="px-4 py-3 text-center">
                  <div className="flex justify-center gap-1">
                    <button onClick={() => setShowPreview(item)} className="p-1 hover:bg-gray-100 rounded" title="미리보기">
                      <Eye className="w-4 h-4 text-gray-500" />
                    </button>
                    {item.statementStatus === '미발행' && (
                      <button onClick={() => handleIssueStatement(item)} className="p-1 hover:bg-blue-100 rounded" title="발행">
                        <FileText className="w-4 h-4 text-blue-500" />
                      </button>
                    )}
                    {item.statementStatus === '발행완료' && !item.sentDate && (
                      <>
                        <button onClick={() => handleSendStatement(item, '이메일')} className="p-1 hover:bg-green-100 rounded" title="이메일발송">
                          <Mail className="w-4 h-4 text-green-500" />
                        </button>
                        <button onClick={() => handleSendStatement(item, '팩스')} className="p-1 hover:bg-purple-100 rounded" title="팩스발송">
                          <Printer className="w-4 h-4 text-purple-500" />
                        </button>
                      </>
                    )}
                    <button onClick={() => alert('인쇄')} className="p-1 hover:bg-gray-100 rounded" title="인쇄">
                      <Printer className="w-4 h-4 text-gray-500" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      {/* 미리보기 모달 - 문서양식관리 연동 */}
      {showPreview && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setShowPreview(null)}>
          <div className="bg-white rounded-xl shadow-xl max-w-3xl w-full max-h-[90vh] overflow-auto" onClick={e => e.stopPropagation()}>
            <div className="p-6 border-b flex justify-between items-center">
              <div className="flex items-center gap-4">
                <h3 className="text-lg font-bold">거래명세서 미리보기</h3>
                <div className="flex items-center gap-2 text-sm">
                  <span className="text-gray-500">양식:</span>
                  <select
                    value={selectedTemplate}
                    onChange={(e) => setSelectedTemplate(e.target.value)}
                    className="border rounded px-2 py-1 text-sm"
                  >
                    <option value="SL">표준 거래명세서</option>
                    <option value="SL-DETAIL">상세 거래명세서</option>
                    <option value="SL-SIMPLE">간편 거래명세서</option>
                  </select>
                  <button
                    onClick={() => onNavigate && onNavigate('document-template-list')}
                    className="text-blue-500 hover:text-blue-700 text-xs flex items-center gap-1"
                  >
                    <Settings className="w-3 h-3" /> 양식관리
                  </button>
                </div>
              </div>
              <button onClick={() => setShowPreview(null)} className="p-2 hover:bg-gray-100 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6">
              {/* A4 비율 미리보기 영역 */}
              <div className="border-2 border-gray-800 p-6 bg-white shadow-lg" style={{ aspectRatio: '210/297', maxHeight: '60vh' }}>
                {/* HDR-COMPANY 블록 */}
                <div className="flex items-center justify-between mb-4">
                  <div className="w-20 h-12 border flex items-center justify-center text-xs text-gray-400">
                    [로고]
                  </div>
                  <h2 className="text-2xl font-bold text-center flex-1 tracking-[0.5em]">거 래 명 세 서</h2>
                  <div className="w-20 text-xs text-right text-gray-500">
                    {showPreview.statementNo || '(미발행)'}
                  </div>
                </div>

                {/* PTY-CUSTOMER & PTY-SUPPLIER 블록 */}
                <div className="grid grid-cols-2 gap-4 mb-4">
                  <div className="border">
                    <div className="bg-gray-800 text-white text-center py-1 text-sm tracking-widest">수 요 자</div>
                    <div className="p-3 space-y-1 text-sm">
                      <div className="flex"><span className="w-16 text-gray-500">업체명:</span><span className="font-medium">{showPreview.customerName}</span></div>
                      <div className="flex"><span className="w-16 text-gray-500">현장명:</span><span>{showPreview.siteName}</span></div>
                      <div className="flex"><span className="w-16 text-gray-500">주소:</span><span className="text-xs text-gray-400">-</span></div>
                    </div>
                  </div>
                  <div className="border">
                    <div className="bg-gray-800 text-white text-center py-1 text-sm tracking-widest">공 급 자</div>
                    <div className="p-3 space-y-1 text-sm">
                      <div className="flex"><span className="w-16 text-gray-500">상호:</span><span className="font-medium">(주)금도방재</span></div>
                      <div className="flex"><span className="w-16 text-gray-500">대표자:</span><span>홍길동</span></div>
                      <div className="flex"><span className="w-16 text-gray-500">사업자:</span><span>123-45-67890</span></div>
                    </div>
                  </div>
                </div>

                {/* TBL-DELIVERY-ITEMS 블록 */}
                <table className="w-full border text-sm mb-4">
                  <thead>
                    <tr className="bg-gray-100">
                      <th className="border px-2 py-1.5 text-xs">No</th>
                      <th className="border px-2 py-1.5">품목명</th>
                      <th className="border px-2 py-1.5">규격</th>
                      <th className="border px-2 py-1.5 w-16">수량</th>
                      <th className="border px-2 py-1.5">단가</th>
                      <th className="border px-2 py-1.5">금액</th>
                    </tr>
                  </thead>
                  <tbody>
                    {showPreview.items.map((item, i) => (
                      <tr key={i}>
                        <td className="border px-2 py-1 text-center text-xs">{i + 1}</td>
                        <td className="border px-2 py-1">{item.name}</td>
                        <td className="border px-2 py-1 text-center text-xs text-gray-500">-</td>
                        <td className="border px-2 py-1 text-center">{item.qty}</td>
                        <td className="border px-2 py-1 text-right">{item.unitPrice.toLocaleString()}</td>
                        <td className="border px-2 py-1 text-right">{item.amount.toLocaleString()}</td>
                      </tr>
                    ))}
                    {/* 빈 행 채우기 */}
                    {[...Array(Math.max(0, 5 - showPreview.items.length))].map((_, i) => (
                      <tr key={`empty-${i}`}>
                        <td className="border px-2 py-1 text-center text-xs text-gray-300">{showPreview.items.length + i + 1}</td>
                        <td className="border px-2 py-1"></td>
                        <td className="border px-2 py-1"></td>
                        <td className="border px-2 py-1"></td>
                        <td className="border px-2 py-1"></td>
                        <td className="border px-2 py-1"></td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* AMT-TABLE 블록 */}
                <div className="flex justify-end">
                  <div className="w-72 border">
                    <div className="grid grid-cols-2 text-sm">
                      <div className="border-b border-r px-3 py-1.5 bg-gray-50 font-medium">공급가액</div>
                      <div className="border-b px-3 py-1.5 text-right">{showPreview.totalAmount.toLocaleString()}원</div>
                      <div className="border-b border-r px-3 py-1.5 bg-gray-50 font-medium">부가세</div>
                      <div className="border-b px-3 py-1.5 text-right">{showPreview.vat.toLocaleString()}원</div>
                      <div className="border-r px-3 py-2 bg-gray-800 text-white font-bold">합계금액</div>
                      <div className="px-3 py-2 text-right font-bold text-lg">{showPreview.grandTotal.toLocaleString()}원</div>
                    </div>
                  </div>
                </div>

                {/* RMK-STANDARD 블록 */}
                <div className="mt-4 border-t pt-3">
                  <div className="text-xs text-gray-500 mb-1">비고</div>
                  <div className="min-h-[30px] border rounded p-2 text-sm text-gray-400">
                    -
                  </div>
                </div>
              </div>

              {/* 템플릿 정보 */}
              <div className="mt-4 p-3 bg-blue-50 rounded-lg text-sm">
                <div className="flex items-center gap-2 text-blue-700">
                  <Layers className="w-4 h-4" />
                  <span className="font-medium">사용 양식: {templateConfig.name}</span>
                </div>
                <div className="text-xs text-blue-600 mt-1">
                  블록 구성: {templateConfig.blocks?.map(b => typeof b === 'string' ? b : b.blockId).join(' → ') || 'HDR-COMPANY → PTY-CUSTOMER → TBL-ITEMS → AMT-TABLE'}
                </div>
              </div>
            </div>
            <div className="p-4 border-t bg-gray-50 flex justify-between">
              <div className="flex gap-2">
                <Button variant="outline" size="sm" onClick={() => alert('PDF 다운로드')}>
                  <Download className="w-4 h-4" /> PDF
                </Button>
                <Button variant="outline" size="sm" onClick={() => alert('인쇄')}>
                  <Printer className="w-4 h-4" /> 인쇄
                </Button>
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={() => setShowPreview(null)}>닫기</Button>
                {showPreview.statementStatus === '미발행' && (
                  <Button variant="primary" onClick={() => { handleIssueStatement(showPreview); setShowPreview(null); }}>
                    <FileText className="w-4 h-4" /> 발행
                  </Button>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 세금계산서 발행 (A1-2) - 기존 InvoiceManagement 확장
const TaxInvoiceIssue = ({ shipments = [], onUpdateShipment }) => {
  const [search, setSearch] = useState('');
  const [filterStatus, setFilterStatus] = useState('pending');
  const [selectedItems, setSelectedItems] = useState([]);

  // 출하완료 건 중 세금계산서 미발행 건
  const [invoices, setInvoices] = useState([
    {
      id: 1, shipmentNo: 'SH-251201-001', splitNo: 'KD-TS-251201-01-S1',
      customerName: '삼성전자', businessNo: '123-45-67890', ceoName: '이재용',
      totalAmount: 12500000, vat: 1250000, grandTotal: 13750000,
      invoiceNo: '', invoiceDate: '', invoiceStatus: '미발행', ntsStatus: ''
    },
    {
      id: 2, shipmentNo: 'SH-251203-001', splitNo: 'KD-SL-251203-01-S1',
      customerName: 'LG전자', businessNo: '234-56-78901', ceoName: '구광모',
      totalAmount: 5400000, vat: 540000, grandTotal: 5940000,
      invoiceNo: 'TX-251203-001', invoiceDate: '2025-12-03', invoiceStatus: '발행완료', ntsStatus: '전송완료'
    },
    {
      id: 3, shipmentNo: 'SH-251205-001', splitNo: 'KD-BD-251205-01-S1',
      customerName: '현대건설', businessNo: '345-67-89012', ceoName: '윤영준',
      totalAmount: 32000000, vat: 3200000, grandTotal: 35200000,
      invoiceNo: 'TX-251205-001', invoiceDate: '2025-12-05', invoiceStatus: '발행완료', ntsStatus: '미전송'
    },
  ]);

  const statusFilters = [
    { id: 'all', label: '전체', count: invoices.length },
    { id: 'pending', label: '미발행', count: invoices.filter(i => i.invoiceStatus === '미발행').length },
    { id: 'issued', label: '발행완료', count: invoices.filter(i => i.invoiceStatus === '발행완료').length },
    { id: 'nts-pending', label: '미전송', count: invoices.filter(i => i.invoiceStatus === '발행완료' && i.ntsStatus !== '전송완료').length },
  ];

  const filtered = invoices.filter(i => {
    const matchSearch = i.shipmentNo.toLowerCase().includes(search.toLowerCase()) ||
      i.customerName.includes(search) || i.businessNo.includes(search);
    const matchStatus = filterStatus === 'all' ||
      (filterStatus === 'pending' && i.invoiceStatus === '미발행') ||
      (filterStatus === 'issued' && i.invoiceStatus === '발행완료') ||
      (filterStatus === 'nts-pending' && i.invoiceStatus === '발행완료' && i.ntsStatus !== '전송완료');
    return matchSearch && matchStatus;
  });

  const handleIssueInvoice = (item) => {
    const invoiceNo = `TX-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-${String(invoices.filter(i => i.invoiceStatus === '발행완료').length + 1).padStart(3, '0')}`;
    setInvoices(prev => prev.map(i =>
      i.id === item.id ? {
        ...i,
        invoiceNo,
        invoiceDate: new Date().toISOString().split('T')[0],
        invoiceStatus: '발행완료',
        ntsStatus: '미전송'
      } : i
    ));
    // 출하관리 taxInvoiceIssued 업데이트 (실제 연동)
    if (onUpdateShipment) {
      onUpdateShipment(item.shipmentNo, { taxInvoiceIssued: true });
    }
    alert(`세금계산서가 발행되었습니다.\n계산서번호: ${invoiceNo}`);
  };

  const handleSendNTS = (item) => {
    if (item.ntsStatus === '전송완료') {
      alert('이미 국세청에 전송되었습니다.');
      return;
    }
    setInvoices(prev => prev.map(i =>
      i.id === item.id ? { ...i, ntsStatus: '전송완료' } : i
    ));
    alert(`세금계산서가 국세청에 전송되었습니다.\n계산서번호: ${item.invoiceNo}`);
  };

  const handleBulkSendNTS = () => {
    const pendingNTS = invoices.filter(i => i.invoiceStatus === '발행완료' && i.ntsStatus !== '전송완료');
    if (pendingNTS.length === 0) {
      alert('전송할 계산서가 없습니다.');
      return;
    }
    setInvoices(prev => prev.map(i =>
      i.invoiceStatus === '발행완료' && i.ntsStatus !== '전송완료' ? { ...i, ntsStatus: '전송완료' } : i
    ));
    alert(`${pendingNTS.length}건의 세금계산서가 국세청에 전송되었습니다.`);
  };

  return (
    <div className="space-y-6">
      <PageHeader icon={Receipt} title="세금계산서 발행" />

      {/* 통계 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatCard icon={FileText} label="전체 건수" value={`${invoices.length}건`} color="blue" />
        <StatCard icon={Clock} label="미발행" value={`${invoices.filter(i => i.invoiceStatus === '미발행').length}건`} color="orange" />
        <StatCard icon={AlertCircle} label="국세청 미전송" value={`${invoices.filter(i => i.ntsStatus !== '전송완료' && i.invoiceStatus === '발행완료').length}건`} color="red" />
        <StatCard icon={Check} label="전송완료" value={`${invoices.filter(i => i.ntsStatus === '전송완료').length}건`} color="green" />
      </div>

      <Card>
        <div className="flex justify-between items-center mb-4">
          <div className="flex gap-2">
            {statusFilters.map(filter => (
              <button
                key={filter.id}
                onClick={() => setFilterStatus(filter.id)}
                className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-full border transition-colors ${filterStatus === filter.id ? 'bg-gray-900 text-white border-gray-900' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                  }`}
              >
                {filter.label} ({filter.count})
              </button>
            ))}
          </div>
          <div className="flex gap-2">
            <SearchInput value={search} onChange={setSearch} placeholder="출하번호, 거래처명, 사업자번호 검색" />
            <Button variant="outline" onClick={handleBulkSendNTS}>
              <Send className="w-4 h-4" /> 일괄전송
            </Button>
          </div>
        </div>

        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left">출하번호</th>
              <th className="px-4 py-3 text-left">거래처</th>
              <th className="px-4 py-3 text-left">사업자번호</th>
              <th className="px-4 py-3 text-right">공급가</th>
              <th className="px-4 py-3 text-right">부가세</th>
              <th className="px-4 py-3 text-right">합계</th>
              <th className="px-4 py-3 text-center">계산서번호</th>
              <th className="px-4 py-3 text-center">발행상태</th>
              <th className="px-4 py-3 text-center">국세청전송</th>
              <th className="px-4 py-3 text-center">관리</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map(item => (
              <tr key={item.id} className={`hover:bg-gray-50 ${item.invoiceStatus === '미발행' ? 'bg-yellow-50' : ''}`}>
                <td className="px-4 py-3 font-mono text-blue-600">{item.shipmentNo}</td>
                <td className="px-4 py-3 font-medium">{item.customerName}</td>
                <td className="px-4 py-3 text-gray-600">{item.businessNo}</td>
                <td className="px-4 py-3 text-right">{item.totalAmount.toLocaleString()}</td>
                <td className="px-4 py-3 text-right">{item.vat.toLocaleString()}</td>
                <td className="px-4 py-3 text-right font-medium">{item.grandTotal.toLocaleString()}</td>
                <td className="px-4 py-3 text-center font-mono text-sm">{item.invoiceNo || '-'}</td>
                <td className="px-4 py-3 text-center">
                  <span className={`px-2 py-1 rounded text-xs ${item.invoiceStatus === '발행완료' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
                    }`}>{item.invoiceStatus}</span>
                </td>
                <td className="px-4 py-3 text-center">
                  <span className={`px-2 py-1 rounded text-xs ${item.ntsStatus === '전송완료' ? 'bg-blue-100 text-blue-700' :
                      item.ntsStatus === '미전송' ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-500'
                    }`}>{item.ntsStatus || '-'}</span>
                </td>
                <td className="px-4 py-3 text-center">
                  <div className="flex justify-center gap-1">
                    {item.invoiceStatus === '미발행' && (
                      <button onClick={() => handleIssueInvoice(item)} className="p-1 hover:bg-blue-100 rounded" title="발행">
                        <FileText className="w-4 h-4 text-blue-500" />
                      </button>
                    )}
                    {item.invoiceStatus === '발행완료' && item.ntsStatus !== '전송완료' && (
                      <button onClick={() => handleSendNTS(item)} className="p-1 hover:bg-green-100 rounded" title="국세청전송">
                        <Send className="w-4 h-4 text-green-500" />
                      </button>
                    )}
                    <button onClick={() => alert('인쇄')} className="p-1 hover:bg-gray-100 rounded" title="인쇄">
                      <Printer className="w-4 h-4 text-gray-500" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
};

// 품의서 관리 (A2)
const PurchaseRequestManagement = ({ mode = 'list' }) => {
  const [activeTab, setActiveTab] = useState('list');
  const [search, setSearch] = useState('');
  const [showPanel, setShowPanel] = useState(mode === 'register');
  const [selectedRequest, setSelectedRequest] = useState(null);

  // 결재 흐름: 임직원(작성) → 경리(1차승인) → 대표(최종승인)
  // 금액별 결재선: 100만원 미만: 경리 승인만, 100만원 이상: 대표 승인 필요
  const [requests, setRequests] = useState([
    {
      id: 1, requestNo: 'PR-251201-001', title: '철강자재 구매건', requestDate: '2025-12-01',
      dept: '생산부', requester: '이생산', amount: 8500000, status: '승인완료',
      // 결재 흐름 확장
      approvalFlow: [
        { step: 1, role: '경리', approver: '김경리', status: '승인', date: '2025-12-01', comment: '' },
        { step: 2, role: '대표', approver: '박대표', status: '승인', date: '2025-12-02', comment: '승인합니다' },
      ],
      currentStep: 2, // 현재 결재 단계
      approver: '박대표', approvedDate: '2025-12-02', note: '긴급 구매', purchaseType: '원자재'
    },
    {
      id: 2, requestNo: 'PR-251205-001', title: '모터 부품 구매건', requestDate: '2025-12-05',
      dept: '생산부', requester: '박생산', amount: 3200000, status: '경리승인대기',
      approvalFlow: [
        { step: 1, role: '경리', approver: '', status: '대기', date: '', comment: '' },
        { step: 2, role: '대표', approver: '', status: '대기', date: '', comment: '' },
      ],
      currentStep: 1,
      approver: '', approvedDate: '', note: '정기 구매', purchaseType: '부품'
    },
    {
      id: 3, requestNo: 'PR-251208-001', title: '사무용품 구매건', requestDate: '2025-12-08',
      dept: '총무부', requester: '최총무', amount: 450000, status: '승인완료',
      approvalFlow: [
        { step: 1, role: '경리', approver: '김경리', status: '승인', date: '2025-12-08', comment: '100만원 미만 경리 단독 승인' },
      ],
      currentStep: 1,
      approver: '김경리', approvedDate: '2025-12-08', note: '100만원 미만', purchaseType: '사무용품'
    },
    {
      id: 4, requestNo: 'PR-251209-001', title: '포장재 대량 구매건', requestDate: '2025-12-09',
      dept: '생산부', requester: '김생산', amount: 5500000, status: '대표승인대기',
      approvalFlow: [
        { step: 1, role: '경리', approver: '김경리', status: '승인', date: '2025-12-09', comment: '경리 승인 완료' },
        { step: 2, role: '대표', approver: '', status: '대기', date: '', comment: '' },
      ],
      currentStep: 2,
      approver: '', approvedDate: '', note: '연말 재고 확보', purchaseType: '포장재'
    },
    {
      id: 5, requestNo: 'PR-251210-001', title: '장비 수리 외주', requestDate: '2025-12-10',
      dept: '생산부', requester: '이생산', amount: 2800000, status: '반려',
      approvalFlow: [
        { step: 1, role: '경리', approver: '김경리', status: '반려', date: '2025-12-10', comment: '예산 초과, 차기 분기로 연기 요청' },
      ],
      currentStep: 1,
      approver: '김경리', approvedDate: '2025-12-10', note: '장비 수리', purchaseType: '외주비'
    },
  ]);

  const tabs = [
    { id: 'list', label: '품의서 목록', count: requests.length },
    { id: 'accountingPending', label: '경리승인대기', count: requests.filter(r => r.status === '경리승인대기').length },
    { id: 'ceoPending', label: '대표승인대기', count: requests.filter(r => r.status === '대표승인대기').length },
    { id: 'approved', label: '승인완료', count: requests.filter(r => r.status === '승인완료').length },
  ];

  // 결재 처리 함수
  const handleApproval = (request, action, comment = '') => {
    const today = new Date().toISOString().split('T')[0];
    const currentStep = request.currentStep;
    const isAccountingStep = currentStep === 1;
    const needsCeoApproval = request.amount >= 1000000; // 100만원 이상은 대표 승인 필요

    setSalesData(prev => prev.map(r => {
      if (r.id !== request.id) return r;

      const newApprovalFlow = [...r.approvalFlow];
      newApprovalFlow[currentStep - 1] = {
        ...newApprovalFlow[currentStep - 1],
        approver: isAccountingStep ? '김경리' : '박대표',
        status: action === 'approve' ? '승인' : '반려',
        date: today,
        comment: comment,
      };

      let newStatus = r.status;
      let newCurrentStep = currentStep;
      let newApprovedDate = r.approvedDate;
      let newApprover = r.approver;

      if (action === 'approve') {
        if (isAccountingStep && needsCeoApproval) {
          // 경리 승인 완료 -> 대표 승인 대기
          newStatus = '대표승인대기';
          newCurrentStep = 2;
        } else {
          // 최종 승인 완료
          newStatus = '승인완료';
          newApprovedDate = today;
          newApprover = isAccountingStep ? '김경리' : '박대표';
        }
      } else {
        // 반려
        newStatus = '반려';
        newApprovedDate = today;
        newApprover = isAccountingStep ? '김경리' : '박대표';
      }

      return {
        ...r,
        approvalFlow: newApprovalFlow,
        status: newStatus,
        currentStep: newCurrentStep,
        approvedDate: newApprovedDate,
        approver: newApprover,
      };
    }));

    alert(`${action === 'approve' ? '승인' : '반려'}이 완료되었습니다.\n품의번호: ${request.requestNo}`);
  };

  // setRequests를 사용해야 하므로 수정
  const processApproval = (request, action, comment = '') => {
    const today = new Date().toISOString().split('T')[0];
    const currentStep = request.currentStep;
    const isAccountingStep = currentStep === 1;
    const needsCeoApproval = request.amount >= 1000000;

    setRequests(prev => prev.map(r => {
      if (r.id !== request.id) return r;

      const newApprovalFlow = [...r.approvalFlow];
      newApprovalFlow[currentStep - 1] = {
        ...newApprovalFlow[currentStep - 1],
        approver: isAccountingStep ? '김경리' : '박대표',
        status: action === 'approve' ? '승인' : '반려',
        date: today,
        comment: comment,
      };

      let newStatus = r.status;
      let newCurrentStep = currentStep;
      let newApprovedDate = r.approvedDate;
      let newApprover = r.approver;

      if (action === 'approve') {
        if (isAccountingStep && needsCeoApproval) {
          newStatus = '대표승인대기';
          newCurrentStep = 2;
        } else {
          newStatus = '승인완료';
          newApprovedDate = today;
          newApprover = isAccountingStep ? '김경리' : '박대표';
        }
      } else {
        newStatus = '반려';
        newApprovedDate = today;
        newApprover = isAccountingStep ? '김경리' : '박대표';
      }

      return {
        ...r,
        approvalFlow: newApprovalFlow,
        status: newStatus,
        currentStep: newCurrentStep,
        approvedDate: newApprovedDate,
        approver: newApprover,
      };
    }));

    setShowPanel(null);
    alert(`${action === 'approve' ? '승인' : '반려'}이 완료되었습니다.\n품의번호: ${request.requestNo}`);
  };

  const filtered = requests.filter(r => {
    const matchSearch = r.requestNo.toLowerCase().includes(search.toLowerCase()) ||
      r.title.includes(search) || r.requester.includes(search);
    if (activeTab === 'list') return matchSearch;
    if (activeTab === 'accountingPending') return matchSearch && r.status === '경리승인대기';
    if (activeTab === 'ceoPending') return matchSearch && r.status === '대표승인대기';
    if (activeTab === 'approved') return matchSearch && r.status === '승인완료';
    return matchSearch;
  });

  // 공통 UX: 품의서 목록 선택
  const {
    selectedIds: requestSelectedIds,
    handleSelect: handleRequestSelect,
    handleSelectAll: handleRequestSelectAll,
    isAllSelected: isRequestAllSelected,
    hasSelection: hasRequestSelection,
    isMultiSelect: isRequestMultiSelect,
    isSelected: isRequestSelected,
  } = useListSelection(filtered);

  const [showDeleteModal, setShowDeleteModal] = useState(false);

  // 통계
  const accountingPendingCount = requests.filter(r => r.status === '경리승인대기').length;
  const ceoPendingCount = requests.filter(r => r.status === '대표승인대기').length;
  const approvedAmount = requests.filter(r => r.status === '승인완료').reduce((sum, r) => sum + r.amount, 0);

  return (
    <div className="space-y-6">
      <PageHeader icon={ClipboardList} title="품의서 목록" />

      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <StatCard icon={FileText} label="전체" value={`${requests.length}건`} color="blue" />
        <StatCard icon={Clock} label="경리승인대기" value={`${accountingPendingCount}건`} color="orange" />
        <StatCard icon={Clock} label="대표승인대기" value={`${ceoPendingCount}건`} color="yellow" />
        <StatCard icon={Check} label="승인완료" value={`${requests.filter(r => r.status === '승인완료').length}건`} color="green" />
        <StatCard icon={DollarSign} label="승인금액" value={`${approvedAmount.toLocaleString()}원`} color="purple" />
      </div>

      {/* 결재 흐름 안내 */}
      <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
        <p className="text-sm text-blue-800">
          <strong>결재 흐름:</strong> 임직원(작성) → 경리(1차승인) → 대표(최종승인)
          <span className="ml-4 text-gray-600">※ 100만원 미만: 경리 단독 승인 / 100만원 이상: 대표 승인 필요</span>
        </p>
      </div>

      <Card>
        <div className="flex justify-between items-center mb-4">
          <div className="flex flex-wrap gap-2">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-full border transition-colors ${activeTab === tab.id ? 'bg-gray-900 text-white border-gray-900' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                  }`}
              >
                <span>{tab.label}</span>
                <span className={activeTab === tab.id ? 'text-white' : 'text-gray-500'}>{tab.count}</span>
              </button>
            ))}
          </div>
          <div className="flex gap-2">
            <SearchInput value={search} onChange={setSearch} placeholder="품의번호, 제목 검색" />
            {isRequestMultiSelect && (
              <Button variant="outline" onClick={() => setShowDeleteModal(true)}>
                <Trash2 className="w-4 h-4" /> 선택 삭제 ({requestSelectedIds.length})
              </Button>
            )}
            <Button variant="primary" onClick={() => setShowPanel('create')}>
              <Plus className="w-4 h-4" /> 품의서 작성
            </Button>
          </div>
        </div>

        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-center w-10">
                <input type="checkbox" checked={isRequestAllSelected} onChange={handleRequestSelectAll} className="rounded" />
              </th>
              <th className="px-4 py-3 text-left">품의번호</th>
              <th className="px-4 py-3 text-left">제목</th>
              <th className="px-4 py-3 text-center">신청부서</th>
              <th className="px-4 py-3 text-center">신청자</th>
              <th className="px-4 py-3 text-right">금액</th>
              <th className="px-4 py-3 text-center">신청일</th>
              <th className="px-4 py-3 text-center">결재현황</th>
              <th className="px-4 py-3 text-center">상태</th>
              <th className="px-4 py-3 text-center">처리</th>
              {hasRequestSelection && <th className="px-4 py-3 text-center">작업</th>}
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map(req => (
              <tr key={req.id} className={`hover:bg-gray-50 ${isRequestSelected(req.id) ? 'bg-blue-50' :
                req.status === '경리승인대기' ? 'bg-orange-50' :
                  req.status === '대표승인대기' ? 'bg-yellow-50' : ''
                }`}>
                <td className="px-4 py-3 text-center">
                  <input type="checkbox" checked={isRequestSelected(req.id)} onChange={() => handleRequestSelect(req.id)} className="rounded" />
                </td>
                <td className="px-4 py-3 font-mono text-blue-600">{req.requestNo}</td>
                <td className="px-4 py-3 font-medium">{req.title}</td>
                <td className="px-4 py-3 text-center">{req.dept}</td>
                <td className="px-4 py-3 text-center">{req.requester}</td>
                <td className="px-4 py-3 text-right">{req.amount.toLocaleString()}</td>
                <td className="px-4 py-3 text-center">{req.requestDate}</td>
                <td className="px-4 py-3 text-center">
                  <div className="flex justify-center gap-1">
                    {req.approvalFlow.map((flow, idx) => (
                      <span key={idx} className={`px-2 py-0.5 rounded text-xs ${flow.status === '승인' ? 'bg-green-100 text-green-700' :
                          flow.status === '반려' ? 'bg-red-100 text-red-700' :
                            flow.status === '대기' ? 'bg-gray-100 text-gray-500' : 'bg-gray-100 text-gray-500'
                        }`}>
                        {flow.role}{flow.status === '승인' ? '✓' : flow.status === '반려' ? '✗' : ''}
                      </span>
                    ))}
                  </div>
                </td>
                <td className="px-4 py-3 text-center">
                  <span className={`px-2 py-1 rounded text-xs font-medium ${req.status === '승인완료' ? 'bg-green-100 text-green-700' :
                      req.status === '경리승인대기' ? 'bg-orange-100 text-orange-700' :
                        req.status === '대표승인대기' ? 'bg-yellow-100 text-yellow-700' :
                          req.status === '반려' ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-600'
                    }`}>{req.status}</span>
                </td>
                <td className="px-4 py-3 text-center">
                  {(req.status === '경리승인대기' || req.status === '대표승인대기') && (
                    <Button size="sm" variant="primary" onClick={() => { setSelectedRequest(req); setShowPanel('approve'); }}>
                      결재
                    </Button>
                  )}
                  {req.status === '승인완료' && (
                    <span className="text-xs text-green-600">{req.approvedDate}</span>
                  )}
                  {req.status === '반려' && (
                    <span className="text-xs text-red-600">반려됨</span>
                  )}
                </td>
                {hasRequestSelection && isRequestSelected(req.id) && (
                  <td className="px-4 py-3 text-center">
                    <div className="flex justify-center gap-1">
                      <Button variant="outline" size="sm" onClick={() => { setSelectedRequest(req); setShowPanel('edit'); }}>
                        <Edit3 className="w-3 h-3" /> 수정
                      </Button>
                      <Button variant="outline" size="sm" onClick={() => setShowDeleteModal(true)}>
                        <Trash2 className="w-3 h-3" /> 삭제
                      </Button>
                    </div>
                  </td>
                )}
                {hasRequestSelection && !isRequestSelected(req.id) && <td className="px-4 py-3"></td>}
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      {/* 결재 모달 */}
      {showPanel === 'approve' && selectedRequest && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-lg w-full mx-4">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold">품의서 결재</h3>
              <button onClick={() => setShowPanel(null)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4">
              <div className="p-4 bg-gray-50 rounded-lg space-y-2">
                <div className="flex justify-between"><span className="text-gray-500">품의번호</span><span className="font-medium">{selectedRequest.requestNo}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">제목</span><span className="font-medium">{selectedRequest.title}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">신청자</span><span>{selectedRequest.dept} {selectedRequest.requester}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">금액</span><span className="font-bold text-blue-600">{selectedRequest.amount.toLocaleString()}원</span></div>
                <div className="flex justify-between"><span className="text-gray-500">현재 결재선</span>
                  <span className={`px-2 py-1 rounded text-xs font-medium ${selectedRequest.currentStep === 1 ? 'bg-orange-100 text-orange-700' : 'bg-yellow-100 text-yellow-700'
                    }`}>{selectedRequest.currentStep === 1 ? '경리 승인' : '대표 승인'}</span>
                </div>
              </div>

              {/* 결재 흐름 표시 */}
              <div className="space-y-2">
                <p className="text-sm font-medium text-gray-700">결재 진행현황</p>
                <div className="flex items-center gap-2">
                  {selectedRequest.approvalFlow.map((flow, idx) => (
                    <div key={idx} className={`flex-1 p-3 rounded-lg border ${flow.status === '승인' ? 'bg-green-50 border-green-200' :
                        flow.status === '반려' ? 'bg-red-50 border-red-200' :
                          idx + 1 === selectedRequest.currentStep ? 'bg-orange-50 border-orange-300' : 'bg-gray-50 border-gray-200'
                      }`}>
                      <div className="text-xs text-gray-500">{flow.step}차 결재</div>
                      <div className="font-medium">{flow.role}</div>
                      <div className={`text-xs ${flow.status === '승인' ? 'text-green-600' :
                          flow.status === '반려' ? 'text-red-600' : 'text-gray-500'
                        }`}>
                        {flow.status === '대기' ? '대기중' : flow.status}
                        {flow.date && ` (${flow.date})`}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <FormField label="결재 의견">
                <textarea
                  id="approvalComment"
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg"
                  placeholder="결재 의견을 입력하세요"
                />
              </FormField>

              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button variant="outline" onClick={() => setShowPanel(null)}>취소</Button>
                <Button variant="outline" className="text-red-600 border-red-200 hover:bg-red-50" onClick={() => {
                  const comment = document.getElementById('approvalComment').value;
                  if (!comment) { alert('반려 시 사유를 입력해주세요.'); return; }
                  processApproval(selectedRequest, 'reject', comment);
                }}>반려</Button>
                <Button variant="primary" onClick={() => {
                  const comment = document.getElementById('approvalComment').value;
                  processApproval(selectedRequest, 'approve', comment);
                }}>승인</Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 지출결의서 관리 (A2-3)
const ExpenseApprovalManagement = ({ mode = 'list' }) => {
  const [activeTab, setActiveTab] = useState('list');
  const [search, setSearch] = useState('');
  const [showPanel, setShowPanel] = useState(mode === 'register');
  const [selectedExpense, setSelectedExpense] = useState(null);

  // 지출결의서: 품의서 승인 후 작성 → 경리승인 → 대표승인 → 지급처리
  const [expenses, setExpenses] = useState([
    {
      id: 1, expenseNo: 'EX-251201-001', purchaseRequestNo: 'PR-251201-001', title: '철강자재 대금지급', expenseDate: '2025-12-01',
      vendor: '금강철강', vendorAccount: '신한 111-222-333444', amount: 8500000, vat: 850000, totalAmount: 9350000,
      paymentMethod: '계좌이체', scheduledPaymentDate: '2025-12-05', actualPaymentDate: '2025-12-05',
      status: '지급완료', requester: '이생산', dept: '생산부',
      approvalFlow: [
        { step: 1, role: '경리', approver: '김경리', status: '승인', date: '2025-12-02', comment: '' },
        { step: 2, role: '대표', approver: '박대표', status: '승인', date: '2025-12-03', comment: '지급 승인' },
      ],
      currentStep: 2
    },
    {
      id: 2, expenseNo: 'EX-251205-001', purchaseRequestNo: 'PR-251205-001', title: '모터부품 대금지급', expenseDate: '2025-12-05',
      vendor: '모터공급사', vendorAccount: '국민 999-888-777666', amount: 3200000, vat: 320000, totalAmount: 3520000,
      paymentMethod: '계좌이체', scheduledPaymentDate: '2025-12-15', actualPaymentDate: '',
      status: '경리승인대기', requester: '박생산', dept: '생산부',
      approvalFlow: [
        { step: 1, role: '경리', approver: '', status: '대기', date: '', comment: '' },
        { step: 2, role: '대표', approver: '', status: '대기', date: '', comment: '' },
      ],
      currentStep: 1
    },
    {
      id: 3, expenseNo: 'EX-251209-001', purchaseRequestNo: 'PR-251209-001', title: '포장재 대금지급', expenseDate: '2025-12-09',
      vendor: '포장재공급사', vendorAccount: '우리 555-666-777888', amount: 5500000, vat: 550000, totalAmount: 6050000,
      paymentMethod: '계좌이체', scheduledPaymentDate: '2025-12-20', actualPaymentDate: '',
      status: '대표승인대기', requester: '김생산', dept: '생산부',
      approvalFlow: [
        { step: 1, role: '경리', approver: '김경리', status: '승인', date: '2025-12-10', comment: '경리 확인' },
        { step: 2, role: '대표', approver: '', status: '대기', date: '', comment: '' },
      ],
      currentStep: 2
    },
    {
      id: 4, expenseNo: 'EX-251210-001', purchaseRequestNo: '', title: '공과금(전기료)', expenseDate: '2025-12-10',
      vendor: '한국전력', vendorAccount: '자동이체', amount: 1250000, vat: 125000, totalAmount: 1375000,
      paymentMethod: '자동이체', scheduledPaymentDate: '2025-12-25', actualPaymentDate: '',
      status: '승인완료', requester: '최총무', dept: '총무부',
      approvalFlow: [
        { step: 1, role: '경리', approver: '김경리', status: '승인', date: '2025-12-10', comment: '정기 지출' },
      ],
      currentStep: 1
    },
  ]);

  const tabs = [
    { id: 'list', label: '결의서 목록', count: expenses.length },
    { id: 'accountingPending', label: '경리승인대기', count: expenses.filter(e => e.status === '경리승인대기').length },
    { id: 'ceoPending', label: '대표승인대기', count: expenses.filter(e => e.status === '대표승인대기').length },
    { id: 'approved', label: '지급대기', count: expenses.filter(e => e.status === '승인완료').length },
    { id: 'paid', label: '지급완료', count: expenses.filter(e => e.status === '지급완료').length },
  ];

  // 결재 처리
  const processExpenseApproval = (expense, action, comment = '') => {
    const today = new Date().toISOString().split('T')[0];
    const currentStep = expense.currentStep;
    const isAccountingStep = currentStep === 1;
    const needsCeoApproval = expense.totalAmount >= 1000000;

    setExpenses(prev => prev.map(e => {
      if (e.id !== expense.id) return e;

      const newApprovalFlow = [...e.approvalFlow];
      newApprovalFlow[currentStep - 1] = {
        ...newApprovalFlow[currentStep - 1],
        approver: isAccountingStep ? '김경리' : '박대표',
        status: action === 'approve' ? '승인' : '반려',
        date: today,
        comment: comment,
      };

      let newStatus = e.status;
      let newCurrentStep = currentStep;

      if (action === 'approve') {
        if (isAccountingStep && needsCeoApproval) {
          newStatus = '대표승인대기';
          newCurrentStep = 2;
        } else {
          newStatus = '승인완료';
        }
      } else {
        newStatus = '반려';
      }

      return {
        ...e,
        approvalFlow: newApprovalFlow,
        status: newStatus,
        currentStep: newCurrentStep,
      };
    }));

    setShowPanel(null);
    alert(`${action === 'approve' ? '승인' : '반려'}이 완료되었습니다.\n결의번호: ${expense.expenseNo}`);
  };

  // 지급 처리
  const processPayment = (expense) => {
    const today = new Date().toISOString().split('T')[0];
    setExpenses(prev => prev.map(e =>
      e.id === expense.id ? { ...e, status: '지급완료', actualPaymentDate: today } : e
    ));
    alert(`지급이 완료되었습니다.\n결의번호: ${expense.expenseNo}\n금액: ${expense.totalAmount.toLocaleString()}원`);
  };

  const filtered = expenses.filter(e => {
    const matchSearch = e.expenseNo.toLowerCase().includes(search.toLowerCase()) ||
      e.title.includes(search) || e.vendor.includes(search);
    if (activeTab === 'list') return matchSearch;
    if (activeTab === 'accountingPending') return matchSearch && e.status === '경리승인대기';
    if (activeTab === 'ceoPending') return matchSearch && e.status === '대표승인대기';
    if (activeTab === 'approved') return matchSearch && e.status === '승인완료';
    if (activeTab === 'paid') return matchSearch && e.status === '지급완료';
    return matchSearch;
  });

  // 공통 UX: 지출결의서 목록 선택
  const {
    selectedIds: expenseSelectedIds,
    handleSelect: handleExpenseSelect,
    handleSelectAll: handleExpenseSelectAll,
    isAllSelected: isExpenseAllSelected,
    hasSelection: hasExpenseSelection,
    isMultiSelect: isExpenseMultiSelect,
    isSelected: isExpenseSelected,
  } = useListSelection(filtered);

  const [showDeleteModal, setShowDeleteModal] = useState(false);

  // 통계
  const accountingPendingAmount = expenses.filter(e => e.status === '경리승인대기').reduce((sum, e) => sum + e.totalAmount, 0);
  const ceoPendingAmount = expenses.filter(e => e.status === '대표승인대기').reduce((sum, e) => sum + e.totalAmount, 0);
  const approvedAmount = expenses.filter(e => e.status === '승인완료').reduce((sum, e) => sum + e.totalAmount, 0);
  const paidAmount = expenses.filter(e => e.status === '지급완료').reduce((sum, e) => sum + e.totalAmount, 0);

  return (
    <div className="space-y-6">
      <PageHeader icon={CreditCard} title="지출결의서 목록" />

      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <StatCard icon={Clock} label="경리승인대기" value={`${accountingPendingAmount.toLocaleString()}원`} color="orange" />
        <StatCard icon={Clock} label="대표승인대기" value={`${ceoPendingAmount.toLocaleString()}원`} color="yellow" />
        <StatCard icon={Check} label="지급대기" value={`${approvedAmount.toLocaleString()}원`} color="blue" />
        <StatCard icon={DollarSign} label="지급완료" value={`${paidAmount.toLocaleString()}원`} color="green" />
        <StatCard icon={FileText} label="전체건수" value={`${expenses.length}건`} color="purple" />
      </div>

      {/* 결재 흐름 안내 */}
      <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
        <p className="text-sm text-blue-800">
          <strong>지출결의 흐름:</strong> 품의서 승인 → 지출결의서 작성 → 경리(1차승인) → 대표(최종승인) → 지급처리
          <span className="ml-4 text-gray-600">※ 100만원 미만: 경리 단독 승인</span>
        </p>
      </div>

      <Card>
        <div className="flex justify-between items-center mb-4">
          <div className="flex flex-wrap gap-2">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-full border transition-colors ${activeTab === tab.id ? 'bg-gray-900 text-white border-gray-900' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                  }`}
              >
                <span>{tab.label}</span>
                <span className={activeTab === tab.id ? 'text-white' : 'text-gray-500'}>{tab.count}</span>
              </button>
            ))}
          </div>
          <div className="flex gap-2">
            <SearchInput value={search} onChange={setSearch} placeholder="결의번호, 제목, 거래처 검색" />
            {isExpenseMultiSelect && (
              <Button variant="outline" onClick={() => setShowDeleteModal(true)}>
                <Trash2 className="w-4 h-4" /> 선택 삭제 ({expenseSelectedIds.length})
              </Button>
            )}
            <Button variant="primary" onClick={() => setShowPanel('create')}><Plus className="w-4 h-4" /> 지출결의서 작성</Button>
          </div>
        </div>

        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-center w-10">
                <input type="checkbox" checked={isExpenseAllSelected} onChange={handleExpenseSelectAll} className="rounded" />
              </th>
              <th className="px-4 py-3 text-left">결의번호</th>
              <th className="px-4 py-3 text-left">품의번호</th>
              <th className="px-4 py-3 text-left">제목</th>
              <th className="px-4 py-3 text-left">거래처</th>
              <th className="px-4 py-3 text-right">합계</th>
              <th className="px-4 py-3 text-center">지급예정일</th>
              <th className="px-4 py-3 text-center">결재현황</th>
              <th className="px-4 py-3 text-center">상태</th>
              <th className="px-4 py-3 text-center">처리</th>
              {hasExpenseSelection && <th className="px-4 py-3 text-center">작업</th>}
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map(exp => (
              <tr key={exp.id} className={`hover:bg-gray-50 ${isExpenseSelected(exp.id) ? 'bg-blue-50' :
                exp.status === '경리승인대기' ? 'bg-orange-50' :
                  exp.status === '대표승인대기' ? 'bg-yellow-50' :
                    exp.status === '승인완료' ? 'bg-blue-50' : ''
                }`}>
                <td className="px-4 py-3 text-center">
                  <input type="checkbox" checked={isExpenseSelected(exp.id)} onChange={() => handleExpenseSelect(exp.id)} className="rounded" />
                </td>
                <td className="px-4 py-3 font-mono text-blue-600">{exp.expenseNo}</td>
                <td className="px-4 py-3 text-gray-500 text-xs">{exp.purchaseRequestNo || '-'}</td>
                <td className="px-4 py-3 font-medium">{exp.title}</td>
                <td className="px-4 py-3">{exp.vendor}</td>
                <td className="px-4 py-3 text-right font-medium">{exp.totalAmount.toLocaleString()}</td>
                <td className="px-4 py-3 text-center">{exp.scheduledPaymentDate}</td>
                <td className="px-4 py-3 text-center">
                  <div className="flex justify-center gap-1">
                    {exp.approvalFlow.map((flow, idx) => (
                      <span key={idx} className={`px-2 py-0.5 rounded text-xs ${flow.status === '승인' ? 'bg-green-100 text-green-700' :
                          flow.status === '반려' ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-500'
                        }`}>
                        {flow.role}{flow.status === '승인' ? '✓' : flow.status === '반려' ? '✗' : ''}
                      </span>
                    ))}
                  </div>
                </td>
                <td className="px-4 py-3 text-center">
                  <span className={`px-2 py-1 rounded text-xs font-medium ${exp.status === '지급완료' ? 'bg-green-100 text-green-700' :
                      exp.status === '승인완료' ? 'bg-blue-100 text-blue-700' :
                        exp.status === '경리승인대기' ? 'bg-orange-100 text-orange-700' :
                          exp.status === '대표승인대기' ? 'bg-yellow-100 text-yellow-700' :
                            exp.status === '반려' ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-600'
                    }`}>{exp.status}</span>
                </td>
                <td className="px-4 py-3 text-center">
                  {(exp.status === '경리승인대기' || exp.status === '대표승인대기') && (
                    <Button size="sm" variant="primary" onClick={() => { setSelectedExpense(exp); setShowPanel('approve'); }}>
                      결재
                    </Button>
                  )}
                  {exp.status === '승인완료' && (
                    <Button size="sm" variant="primary" onClick={() => processPayment(exp)}>지급</Button>
                  )}
                  {exp.status === '지급완료' && (
                    <span className="text-xs text-green-600">{exp.actualPaymentDate}</span>
                  )}
                </td>
                {hasExpenseSelection && isExpenseSelected(exp.id) && (
                  <td className="px-4 py-3 text-center">
                    <div className="flex justify-center gap-1">
                      <Button variant="outline" size="sm" onClick={() => { setSelectedExpense(exp); setShowPanel('edit'); }}>
                        <Edit3 className="w-3 h-3" /> 수정
                      </Button>
                      <Button variant="outline" size="sm" onClick={() => setShowDeleteModal(true)}>
                        <Trash2 className="w-3 h-3" /> 삭제
                      </Button>
                    </div>
                  </td>
                )}
                {hasExpenseSelection && !isExpenseSelected(exp.id) && <td className="px-4 py-3"></td>}
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      {/* 결재 모달 */}
      {showPanel === 'approve' && selectedExpense && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-lg w-full mx-4">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold">지출결의서 결재</h3>
              <button onClick={() => setShowPanel(null)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4">
              <div className="p-4 bg-gray-50 rounded-lg space-y-2">
                <div className="flex justify-between"><span className="text-gray-500">결의번호</span><span className="font-medium">{selectedExpense.expenseNo}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">제목</span><span className="font-medium">{selectedExpense.title}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">거래처</span><span>{selectedExpense.vendor}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">계좌번호</span><span className="text-xs">{selectedExpense.vendorAccount}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">금액</span><span className="font-bold text-blue-600">{selectedExpense.totalAmount.toLocaleString()}원</span></div>
                <div className="flex justify-between"><span className="text-gray-500">지급예정일</span><span>{selectedExpense.scheduledPaymentDate}</span></div>
              </div>

              <div className="space-y-2">
                <p className="text-sm font-medium text-gray-700">결재 진행현황</p>
                <div className="flex items-center gap-2">
                  {selectedExpense.approvalFlow.map((flow, idx) => (
                    <div key={idx} className={`flex-1 p-3 rounded-lg border ${flow.status === '승인' ? 'bg-green-50 border-green-200' :
                        idx + 1 === selectedExpense.currentStep ? 'bg-orange-50 border-orange-300' : 'bg-gray-50 border-gray-200'
                      }`}>
                      <div className="text-xs text-gray-500">{flow.step}차 결재</div>
                      <div className="font-medium">{flow.role}</div>
                      <div className={`text-xs ${flow.status === '승인' ? 'text-green-600' : 'text-gray-500'}`}>
                        {flow.status === '대기' ? '대기중' : flow.status}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <FormField label="결재 의견">
                <textarea
                  id="expenseApprovalComment"
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg"
                  placeholder="결재 의견을 입력하세요"
                />
              </FormField>

              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button variant="outline" onClick={() => setShowPanel(null)}>취소</Button>
                <Button variant="outline" className="text-red-600 border-red-200 hover:bg-red-50" onClick={() => {
                  const comment = document.getElementById('expenseApprovalComment').value;
                  if (!comment) { alert('반려 시 사유를 입력해주세요.'); return; }
                  processExpenseApproval(selectedExpense, 'reject', comment);
                }}>반려</Button>
                <Button variant="primary" onClick={() => {
                  const comment = document.getElementById('expenseApprovalComment').value;
                  processExpenseApproval(selectedExpense, 'approve', comment);
                }}>승인</Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 금전출납부 관리 (A3)
const CashbookManagement = ({ mode = 'list' }) => {
  const [mainTab, setMainTab] = useState('ledger'); // ledger, account, card, monthly, daily
  const [typeFilter, setTypeFilter] = useState('all');
  const [search, setSearch] = useState('');
  const [dateRange, setDateRange] = useState({ start: '2025-12-01', end: '2025-12-15' });
  const [showRegisterModal, setShowRegisterModal] = useState(mode === 'register');
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedEntry, setSelectedEntry] = useState(null);
  const [selectedAccount, setSelectedAccount] = useState('all');

  // 계좌 정보
  const accounts = [
    { id: 'KB001', name: '국민은행 법인계좌', accountNo: '123-456-789012', balance: 45670000, type: '보통예금' },
    { id: 'SH001', name: '신한은행 운영계좌', accountNo: '111-222-333444', balance: 12350000, type: '보통예금' },
    { id: 'KE001', name: '기업은행 급여계좌', accountNo: '999-888-777666', balance: 8500000, type: '보통예금' },
  ];

  // 카드 정보
  const cards = [
    { id: 'CARD001', name: '법인카드 (대표)', cardNo: '**** **** **** 1234', limit: 50000000, used: 12500000, bank: '삼성카드' },
    { id: 'CARD002', name: '법인카드 (경리)', cardNo: '**** **** **** 5678', limit: 10000000, used: 3200000, bank: '신한카드' },
  ];

  // 출납부 데이터 (확장)
  const [entries, setEntries] = useState([
    {
      id: 1, entryNo: 'CB-251201-001', entryDate: '2025-12-01', type: '입금', category: '매출수금',
      description: 'LG전자 매출대금', counterpart: 'LG전자', amount: 5940000, balance: 15940000,
      accountId: 'KB001', account: '국민 123-456-789012', registrant: '김경리', relatedNo: 'SH-251128-001', source: '수금관리'
    },
    {
      id: 2, entryNo: 'CB-251203-001', entryDate: '2025-12-03', type: '출금', category: '원자재구매',
      description: '철강자재 구매대금', counterpart: '금강철강', amount: 9350000, balance: 6590000,
      accountId: 'SH001', account: '신한 111-222-333444', registrant: '박회계', relatedNo: 'EX-251203-001', source: '지출결의서'
    },
    {
      id: 3, entryNo: 'CB-251205-001', entryDate: '2025-12-05', type: '입금', category: '매출수금',
      description: '삼성전자 1차 부분수금', counterpart: '삼성전자', amount: 7000000, balance: 13590000,
      accountId: 'KB001', account: '국민 123-456-789012', registrant: '김경리', relatedNo: 'SH-251201-001', source: '수금관리'
    },
    {
      id: 4, entryNo: 'CB-251208-001', entryDate: '2025-12-08', type: '출금', category: '급여',
      description: '12월 급여 지급', counterpart: '직원급여', amount: 25000000, balance: -11410000,
      accountId: 'KE001', account: '기업 999-888-777666', registrant: '박회계', relatedNo: '', source: '직접등록'
    },
    {
      id: 5, entryNo: 'CB-251210-001', entryDate: '2025-12-10', type: '입금', category: '매출수금',
      description: '현대건설 계약금', counterpart: '현대건설', amount: 35200000, balance: 23790000,
      accountId: 'KB001', account: '국민 123-456-789012', registrant: '김경리', relatedNo: 'SH-251205-001', source: '수금관리'
    },
  ]);

  // 카드 사용내역
  const [cardEntries, setCardEntries] = useState([
    { id: 1, cardId: 'CARD001', useDate: '2025-12-05', merchant: '주유소', amount: 150000, category: '차량유지', approvalNo: '12345678', status: '승인' },
    { id: 2, cardId: 'CARD001', useDate: '2025-12-08', merchant: '사무용품점', amount: 85000, category: '소모품', approvalNo: '23456789', status: '승인' },
    { id: 3, cardId: 'CARD002', useDate: '2025-12-10', merchant: '식당', amount: 120000, category: '접대비', approvalNo: '34567890', status: '승인' },
    { id: 4, cardId: 'CARD001', useDate: '2025-12-12', merchant: '호텔', amount: 350000, category: '출장비', approvalNo: '45678901', status: '승인' },
  ]);

  // 통계 계산
  const totalIncome = entries.filter(e => e.type === '입금').reduce((sum, e) => sum + e.amount, 0);
  const totalExpense = entries.filter(e => e.type === '출금').reduce((sum, e) => sum + e.amount, 0);
  const totalBalance = accounts.reduce((sum, a) => sum + a.balance, 0);
  const totalCardUsed = cards.reduce((sum, c) => sum + c.used, 0);

  // 카테고리별 집계
  const categoryStats = entries.reduce((acc, e) => {
    if (!acc[e.category]) acc[e.category] = { income: 0, expense: 0 };
    if (e.type === '입금') acc[e.category].income += e.amount;
    else acc[e.category].expense += e.amount;
    return acc;
  }, {});

  // 일별 집계
  const dailyStats = entries.reduce((acc, e) => {
    if (!acc[e.entryDate]) acc[e.entryDate] = { income: 0, expense: 0, count: 0 };
    if (e.type === '입금') acc[e.entryDate].income += e.amount;
    else acc[e.entryDate].expense += e.amount;
    acc[e.entryDate].count += 1;
    return acc;
  }, {});

  // 월별 집계
  const monthlyStats = entries.reduce((acc, e) => {
    const month = e.entryDate.substring(0, 7);
    if (!acc[month]) acc[month] = { income: 0, expense: 0, count: 0 };
    if (e.type === '입금') acc[month].income += e.amount;
    else acc[month].expense += e.amount;
    acc[month].count += 1;
    return acc;
  }, {});

  // 필터링
  const filtered = entries.filter(e => {
    const matchSearch = e.entryNo.toLowerCase().includes(search.toLowerCase()) ||
      e.description.includes(search) || e.counterpart.includes(search);
    const matchType = typeFilter === 'all' || e.type === typeFilter;
    const matchAccount = selectedAccount === 'all' || e.accountId === selectedAccount;
    return matchSearch && matchType && matchAccount;
  });

  // 공통 UX: 출납원장 선택
  const {
    selectedIds: ledgerSelectedIds,
    handleSelect: handleLedgerSelect,
    handleSelectAll: handleLedgerSelectAll,
    isAllSelected: isLedgerAllSelected,
    hasSelection: hasLedgerSelection,
    isMultiSelect: isLedgerMultiSelect,
    isSelected: isLedgerSelected,
  } = useListSelection(filtered);

  // 공통 UX: 카드 사용내역 선택
  const {
    selectedIds: cardSelectedIds,
    handleSelect: handleCardSelect,
    handleSelectAll: handleCardSelectAll,
    isAllSelected: isCardAllSelected,
    hasSelection: hasCardSelection,
    isMultiSelect: isCardMultiSelect,
    isSelected: isCardSelected,
  } = useListSelection(cardEntries);

  // 출납 등록
  const handleRegisterEntry = (formData) => {
    const today = new Date().toISOString().split('T')[0];
    const newEntry = {
      id: entries.length + 1,
      entryNo: `CB-${today.replace(/-/g, '').substring(2)}-${String(entries.length + 1).padStart(3, '0')}`,
      entryDate: formData.entryDate || today,
      type: formData.type,
      category: formData.category,
      description: formData.description,
      counterpart: formData.counterpart,
      amount: parseInt(formData.amount),
      balance: 0,
      accountId: formData.accountId,
      account: accounts.find(a => a.id === formData.accountId)?.name || '',
      registrant: '김경리',
      relatedNo: '',
      source: '직접등록'
    };
    setEntries(prev => [...prev, newEntry]);
    alert('출납 내역이 등록되었습니다.');
    setShowRegisterModal(false);
  };

  const mainTabs = [
    { id: 'ledger', label: '출납원장' },
    { id: 'account', label: '계좌별 현황' },
    { id: 'card', label: '법인카드 관리' },
    { id: 'daily', label: '일별 현황' },
    { id: 'monthly', label: '월별 현황' },
    { id: 'category', label: '항목별 집계' },
  ];

  return (
    <div className="space-y-6">
      <PageHeader icon={CreditCard} title="금전출납부 목록" />

      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <StatCard icon={ArrowDownCircle} label="총 입금" value={`${totalIncome.toLocaleString()}원`} color="green" />
        <StatCard icon={ArrowUpCircle} label="총 출금" value={`${totalExpense.toLocaleString()}원`} color="red" />
        <StatCard icon={DollarSign} label="예금잔액" value={`${totalBalance.toLocaleString()}원`} color="blue" />
        <StatCard icon={CreditCard} label="카드사용" value={`${totalCardUsed.toLocaleString()}원`} color="orange" />
        <StatCard icon={FileText} label="거래건수" value={`${entries.length}건`} color="purple" />
      </div>

      {/* 연동 안내 */}
      <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
        <div className="flex items-center gap-2 text-blue-700">
          <AlertCircle className="w-5 h-5" />
          <span className="font-medium">수금/지출 연동</span>
        </div>
        <p className="mt-1 text-sm text-blue-600">
          수금관리에서 수금 등록 시 자동으로 입금 내역이 생성됩니다.
          지출결의서 지급 완료 시 자동으로 출금 내역이 생성됩니다.
        </p>
      </div>

      {/* 메인 탭 */}
      <div className="flex gap-2 border-b">
        {mainTabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => setMainTab(tab.id)}
            className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${mainTab === tab.id
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* 출납원장 탭 */}
      {mainTab === 'ledger' && (
        <Card>
          <div className="flex justify-between items-center mb-4">
            <div className="flex gap-2">
              {[
                { id: 'all', label: '전체' },
                { id: '입금', label: '입금' },
                { id: '출금', label: '출금' },
              ].map(tab => (
                <button
                  key={tab.id}
                  onClick={() => setTypeFilter(tab.id)}
                  className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-full border transition-colors ${typeFilter === tab.id ? 'bg-gray-900 text-white border-gray-900' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                    }`}
                >
                  {tab.label}
                </button>
              ))}
              <select
                value={selectedAccount}
                onChange={e => setSelectedAccount(e.target.value)}
                className="px-3 py-2 border rounded-lg text-sm"
              >
                <option value="all">전체 계좌</option>
                {accounts.map(a => (
                  <option key={a.id} value={a.id}>{a.name}</option>
                ))}
              </select>
            </div>
            <div className="flex gap-2">
              <input type="date" value={dateRange.start} onChange={e => setDateRange(prev => ({ ...prev, start: e.target.value }))}
                className="px-3 py-2 border rounded-lg text-sm" />
              <span className="flex items-center">~</span>
              <input type="date" value={dateRange.end} onChange={e => setDateRange(prev => ({ ...prev, end: e.target.value }))}
                className="px-3 py-2 border rounded-lg text-sm" />
              <SearchInput value={search} onChange={setSearch} placeholder="번호, 내용, 거래처 검색" />
              {isLedgerMultiSelect && (
                <Button variant="outline" onClick={() => setShowDeleteModal(true)}>
                  <Trash2 className="w-4 h-4" /> 선택 삭제 ({ledgerSelectedIds.length})
                </Button>
              )}
              <Button variant="primary" onClick={() => setShowRegisterModal(true)}><Plus className="w-4 h-4" /> 출납 등록</Button>
            </div>
          </div>

          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-center w-10">
                  <input type="checkbox" checked={isLedgerAllSelected} onChange={handleLedgerSelectAll} className="rounded" />
                </th>
                <th className="px-4 py-3 text-left">번호</th>
                <th className="px-4 py-3 text-center">일자</th>
                <th className="px-4 py-3 text-center">구분</th>
                <th className="px-4 py-3 text-left">분류</th>
                <th className="px-4 py-3 text-left">적요</th>
                <th className="px-4 py-3 text-left">거래처</th>
                <th className="px-4 py-3 text-left">계좌</th>
                <th className="px-4 py-3 text-right">금액</th>
                <th className="px-4 py-3 text-center">연동</th>
                <th className="px-4 py-3 text-center">등록자</th>
                {hasLedgerSelection && <th className="px-4 py-3 text-center">작업</th>}
              </tr>
            </thead>
            <tbody className="divide-y">
              {filtered.map(entry => (
                <tr key={entry.id} className={`hover:bg-gray-50 ${isLedgerSelected(entry.id) ? 'bg-blue-50' : ''}`}>
                  <td className="px-4 py-3 text-center">
                    <input type="checkbox" checked={isLedgerSelected(entry.id)} onChange={() => handleLedgerSelect(entry.id)} className="rounded" />
                  </td>
                  <td className="px-4 py-3 font-mono text-blue-600">{entry.entryNo}</td>
                  <td className="px-4 py-3 text-center">{entry.entryDate}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`px-2 py-1 rounded text-xs font-medium ${entry.type === '입금' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                      }`}>{entry.type}</span>
                  </td>
                  <td className="px-4 py-3">{entry.category}</td>
                  <td className="px-4 py-3">{entry.description}</td>
                  <td className="px-4 py-3">{entry.counterpart}</td>
                  <td className="px-4 py-3 text-sm text-gray-600">{entry.account}</td>
                  <td className={`px-4 py-3 text-right font-medium ${entry.type === '입금' ? 'text-green-600' : 'text-red-600'}`}>
                    {entry.type === '입금' ? '+' : '-'}{entry.amount.toLocaleString()}
                  </td>
                  <td className="px-4 py-3 text-center">
                    {entry.source !== '직접등록' ? (
                      <span className="px-2 py-1 rounded text-xs bg-blue-100 text-blue-700">{entry.source}</span>
                    ) : (
                      <span className="text-gray-400">-</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-center text-gray-500">{entry.registrant}</td>
                  {hasLedgerSelection && isLedgerSelected(entry.id) && (
                    <td className="px-4 py-3 text-center">
                      <div className="flex justify-center gap-1">
                        <Button variant="outline" size="sm" onClick={() => { setSelectedEntry(entry); setShowRegisterModal(true); }}>
                          <Edit3 className="w-3 h-3" /> 수정
                        </Button>
                        <Button variant="outline" size="sm" onClick={() => setShowDeleteModal(true)}>
                          <Trash2 className="w-3 h-3" /> 삭제
                        </Button>
                      </div>
                    </td>
                  )}
                  {hasLedgerSelection && !isLedgerSelected(entry.id) && <td className="px-4 py-3"></td>}
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {/* 계좌별 현황 탭 */}
      {mainTab === 'account' && (
        <div className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {accounts.map(account => (
              <Card key={account.id} className="p-4">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                      <DollarSign className="w-5 h-5 text-blue-600" />
                    </div>
                    <div>
                      <p className="font-medium">{account.name}</p>
                      <p className="text-xs text-gray-500">{account.accountNo}</p>
                    </div>
                  </div>
                  <span className="px-2 py-1 rounded text-xs bg-gray-100">{account.type}</span>
                </div>
                <div className="text-right">
                  <p className="text-sm text-gray-500">현재잔액</p>
                  <p className="text-xl font-bold text-blue-600">{account.balance.toLocaleString()}원</p>
                </div>
                <div className="mt-3 pt-3 border-t flex justify-between text-sm">
                  <span className="text-green-600">입금 {entries.filter(e => e.accountId === account.id && e.type === '입금').length}건</span>
                  <span className="text-red-600">출금 {entries.filter(e => e.accountId === account.id && e.type === '출금').length}건</span>
                </div>
              </Card>
            ))}
          </div>

          <Card>
            <h3 className="font-medium mb-4">계좌별 입출금 내역</h3>
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left">계좌명</th>
                  <th className="px-4 py-3 text-left">계좌번호</th>
                  <th className="px-4 py-3 text-right">입금 합계</th>
                  <th className="px-4 py-3 text-right">출금 합계</th>
                  <th className="px-4 py-3 text-right">차액</th>
                  <th className="px-4 py-3 text-right">현재잔액</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {accounts.map(account => {
                  const income = entries.filter(e => e.accountId === account.id && e.type === '입금').reduce((sum, e) => sum + e.amount, 0);
                  const expense = entries.filter(e => e.accountId === account.id && e.type === '출금').reduce((sum, e) => sum + e.amount, 0);
                  return (
                    <tr key={account.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3 font-medium">{account.name}</td>
                      <td className="px-4 py-3 text-gray-600">{account.accountNo}</td>
                      <td className="px-4 py-3 text-right text-green-600">+{income.toLocaleString()}</td>
                      <td className="px-4 py-3 text-right text-red-600">-{expense.toLocaleString()}</td>
                      <td className={`px-4 py-3 text-right font-medium ${income - expense >= 0 ? 'text-blue-600' : 'text-red-600'}`}>
                        {(income - expense).toLocaleString()}
                      </td>
                      <td className="px-4 py-3 text-right font-bold">{account.balance.toLocaleString()}</td>
                    </tr>
                  );
                })}
              </tbody>
              <tfoot className="bg-gray-100 font-medium">
                <tr>
                  <td className="px-4 py-3" colSpan={2}>합계</td>
                  <td className="px-4 py-3 text-right text-green-600">+{totalIncome.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-red-600">-{totalExpense.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-blue-600">{(totalIncome - totalExpense).toLocaleString()}</td>
                  <td className="px-4 py-3 text-right font-bold">{totalBalance.toLocaleString()}</td>
                </tr>
              </tfoot>
            </table>
          </Card>
        </div>
      )}

      {/* 법인카드 관리 탭 */}
      {mainTab === 'card' && (
        <div className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {cards.map(card => (
              <Card key={card.id} className="p-4">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <div className="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center">
                      <CreditCard className="w-5 h-5 text-purple-600" />
                    </div>
                    <div>
                      <p className="font-medium">{card.name}</p>
                      <p className="text-xs text-gray-500">{card.cardNo}</p>
                    </div>
                  </div>
                  <span className="px-2 py-1 rounded text-xs bg-purple-100 text-purple-700">{card.bank}</span>
                </div>
                <div className="space-y-2">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">한도</span>
                    <span>{card.limit.toLocaleString()}원</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">사용액</span>
                    <span className="text-red-600">{card.used.toLocaleString()}원</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div
                      className="bg-purple-500 h-2 rounded-full"
                      style={{ width: `${(card.used / card.limit) * 100}%` }}
                    ></div>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">잔여한도</span>
                    <span className="text-blue-600 font-medium">{(card.limit - card.used).toLocaleString()}원</span>
                  </div>
                </div>
              </Card>
            ))}
          </div>

          <Card>
            <div className="flex justify-between items-center mb-4">
              <h3 className="font-medium">카드 사용내역</h3>
              <div className="flex gap-2">
                {isCardMultiSelect && (
                  <Button variant="outline" onClick={() => setShowDeleteModal(true)}>
                    <Trash2 className="w-4 h-4" /> 선택 삭제 ({cardSelectedIds.length})
                  </Button>
                )}
                <Button variant="outline"><Download className="w-4 h-4" /> 명세서 다운로드</Button>
              </div>
            </div>
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-center w-10">
                    <input type="checkbox" checked={isCardAllSelected} onChange={handleCardSelectAll} className="rounded" />
                  </th>
                  <th className="px-4 py-3 text-center">사용일</th>
                  <th className="px-4 py-3 text-left">카드</th>
                  <th className="px-4 py-3 text-left">가맹점</th>
                  <th className="px-4 py-3 text-left">분류</th>
                  <th className="px-4 py-3 text-right">금액</th>
                  <th className="px-4 py-3 text-center">승인번호</th>
                  <th className="px-4 py-3 text-center">상태</th>
                  {hasCardSelection && <th className="px-4 py-3 text-center">작업</th>}
                </tr>
              </thead>
              <tbody className="divide-y">
                {cardEntries.map(entry => (
                  <tr key={entry.id} className={`hover:bg-gray-50 ${isCardSelected(entry.id) ? 'bg-blue-50' : ''}`}>
                    <td className="px-4 py-3 text-center">
                      <input type="checkbox" checked={isCardSelected(entry.id)} onChange={() => handleCardSelect(entry.id)} className="rounded" />
                    </td>
                    <td className="px-4 py-3 text-center">{entry.useDate}</td>
                    <td className="px-4 py-3">{cards.find(c => c.id === entry.cardId)?.name}</td>
                    <td className="px-4 py-3 font-medium">{entry.merchant}</td>
                    <td className="px-4 py-3">{entry.category}</td>
                    <td className="px-4 py-3 text-right text-red-600">{entry.amount.toLocaleString()}</td>
                    <td className="px-4 py-3 text-center font-mono text-gray-500">{entry.approvalNo}</td>
                    <td className="px-4 py-3 text-center">
                      <span className="px-2 py-1 rounded text-xs bg-green-100 text-green-700">{entry.status}</span>
                    </td>
                    {hasCardSelection && isCardSelected(entry.id) && (
                      <td className="px-4 py-3 text-center">
                        <div className="flex justify-center gap-1">
                          <Button variant="outline" size="sm">
                            <Edit3 className="w-3 h-3" /> 수정
                          </Button>
                          <Button variant="outline" size="sm" onClick={() => setShowDeleteModal(true)}>
                            <Trash2 className="w-3 h-3" /> 삭제
                          </Button>
                        </div>
                      </td>
                    )}
                    {hasCardSelection && !isCardSelected(entry.id) && <td className="px-4 py-3"></td>}
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        </div>
      )}

      {/* 일별 현황 탭 */}
      {mainTab === 'daily' && (
        <Card>
          <h3 className="font-medium mb-4">일별 입출금 현황</h3>
          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-center">일자</th>
                <th className="px-4 py-3 text-center">건수</th>
                <th className="px-4 py-3 text-right">입금</th>
                <th className="px-4 py-3 text-right">출금</th>
                <th className="px-4 py-3 text-right">차액</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {Object.entries(dailyStats).sort((a, b) => b[0].localeCompare(a[0])).map(([date, stats]) => (
                <tr key={date} className="hover:bg-gray-50">
                  <td className="px-4 py-3 text-center font-medium">{date}</td>
                  <td className="px-4 py-3 text-center">{stats.count}건</td>
                  <td className="px-4 py-3 text-right text-green-600">+{stats.income.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-red-600">-{stats.expense.toLocaleString()}</td>
                  <td className={`px-4 py-3 text-right font-medium ${stats.income - stats.expense >= 0 ? 'text-blue-600' : 'text-red-600'}`}>
                    {(stats.income - stats.expense).toLocaleString()}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {/* 월별 현황 탭 */}
      {mainTab === 'monthly' && (
        <Card>
          <h3 className="font-medium mb-4">월별 입출금 현황</h3>
          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-center">월</th>
                <th className="px-4 py-3 text-center">건수</th>
                <th className="px-4 py-3 text-right">입금</th>
                <th className="px-4 py-3 text-right">출금</th>
                <th className="px-4 py-3 text-right">차액</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {Object.entries(monthlyStats).sort((a, b) => b[0].localeCompare(a[0])).map(([month, stats]) => (
                <tr key={month} className="hover:bg-gray-50">
                  <td className="px-4 py-3 text-center font-medium">{month}</td>
                  <td className="px-4 py-3 text-center">{stats.count}건</td>
                  <td className="px-4 py-3 text-right text-green-600">+{stats.income.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-red-600">-{stats.expense.toLocaleString()}</td>
                  <td className={`px-4 py-3 text-right font-medium ${stats.income - stats.expense >= 0 ? 'text-blue-600' : 'text-red-600'}`}>
                    {(stats.income - stats.expense).toLocaleString()}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {/* 항목별 집계 탭 */}
      {mainTab === 'category' && (
        <Card>
          <h3 className="font-medium mb-4">항목별 입출금 집계</h3>
          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left">항목</th>
                <th className="px-4 py-3 text-right">입금</th>
                <th className="px-4 py-3 text-right">출금</th>
                <th className="px-4 py-3 text-right">차액</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {Object.entries(categoryStats).map(([category, stats]) => (
                <tr key={category} className="hover:bg-gray-50">
                  <td className="px-4 py-3 font-medium">{category}</td>
                  <td className="px-4 py-3 text-right text-green-600">{stats.income > 0 ? `+${stats.income.toLocaleString()}` : '-'}</td>
                  <td className="px-4 py-3 text-right text-red-600">{stats.expense > 0 ? `-${stats.expense.toLocaleString()}` : '-'}</td>
                  <td className={`px-4 py-3 text-right font-medium ${stats.income - stats.expense >= 0 ? 'text-blue-600' : 'text-red-600'}`}>
                    {(stats.income - stats.expense).toLocaleString()}
                  </td>
                </tr>
              ))}
            </tbody>
            <tfoot className="bg-gray-100 font-medium">
              <tr>
                <td className="px-4 py-3">합계</td>
                <td className="px-4 py-3 text-right text-green-600">+{totalIncome.toLocaleString()}</td>
                <td className="px-4 py-3 text-right text-red-600">-{totalExpense.toLocaleString()}</td>
                <td className="px-4 py-3 text-right text-blue-600">{(totalIncome - totalExpense).toLocaleString()}</td>
              </tr>
            </tfoot>
          </table>
        </Card>
      )}

      {/* 출납 등록 모달 */}
      {showRegisterModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-lg w-full mx-4">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold">출납 등록</h3>
              <button onClick={() => setShowRegisterModal(false)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4">
              <FormField label="구분" required>
                <div className="flex gap-4">
                  <label className="flex items-center gap-2">
                    <input type="radio" name="entryType" value="입금" defaultChecked />
                    <span className="text-green-600 font-medium">입금</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="radio" name="entryType" value="출금" />
                    <span className="text-red-600 font-medium">출금</span>
                  </label>
                </div>
              </FormField>
              <FormField label="일자" required>
                <input type="date" id="entryDate" defaultValue={new Date().toISOString().split('T')[0]} className="w-full px-3 py-2 border rounded-lg" />
              </FormField>
              <FormField label="계좌" required>
                <select id="accountId" className="w-full px-3 py-2 border rounded-lg">
                  {accounts.map(a => (
                    <option key={a.id} value={a.id}>{a.name} ({a.accountNo})</option>
                  ))}
                </select>
              </FormField>
              <FormField label="분류" required>
                <select id="category" className="w-full px-3 py-2 border rounded-lg">
                  <option value="매출수금">매출수금</option>
                  <option value="원자재구매">원자재구매</option>
                  <option value="급여">급여</option>
                  <option value="임대료">임대료</option>
                  <option value="공과금">공과금</option>
                  <option value="기타">기타</option>
                </select>
              </FormField>
              <FormField label="금액" required>
                <input type="number" id="amount" className="w-full px-3 py-2 border rounded-lg" placeholder="금액 입력" />
              </FormField>
              <FormField label="거래처">
                <input type="text" id="counterpart" className="w-full px-3 py-2 border rounded-lg" placeholder="거래처명 입력" />
              </FormField>
              <FormField label="적요" required>
                <input type="text" id="description" className="w-full px-3 py-2 border rounded-lg" placeholder="적요 입력" />
              </FormField>
              <div className="flex gap-2">
                <Button variant="outline" className="flex-1" onClick={() => setShowRegisterModal(false)}>취소</Button>
                <Button variant="primary" className="flex-1" onClick={() => {
                  const type = document.querySelector('input[name="entryType"]:checked')?.value || '입금';
                  const formData = {
                    type,
                    entryDate: document.getElementById('entryDate').value,
                    accountId: document.getElementById('accountId').value,
                    category: document.getElementById('category').value,
                    amount: document.getElementById('amount').value,
                    counterpart: document.getElementById('counterpart').value || '-',
                    description: document.getElementById('description').value,
                  };
                  if (!formData.amount || !formData.description) {
                    alert('필수 항목을 입력해주세요.');
                    return;
                  }
                  handleRegisterEntry(formData);
                }}><Check className="w-4 h-4" /> 등록</Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 수금 등록 (출하관리 연동) (A4-1)
const CollectionRegister = ({ shipments = [], onUpdateShipment, onNavigate, mode = 'list' }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('pending'); // pending, history, customer, reminder
  const [showRegisterPanel, setShowRegisterPanel] = useState(mode === 'register');
  const [selectedShipment, setSelectedShipment] = useState(null);
  const [showReminderModal, setShowReminderModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedForReminder, setSelectedForReminder] = useState([]);
  const [reminderHistory, setReminderHistory] = useState([
    { id: 1, date: '2025-12-10', customerName: '대우건설', type: '이메일', amount: 8800000, result: '발송완료', sender: '김경리' },
    { id: 2, date: '2025-12-05', customerName: '신흥건설', type: '팩스', amount: 12500000, result: '발송완료', sender: '김경리' },
  ]);

  // 출하완료 건 중 수금 미완료 건 (확장된 데이터)
  const pendingCollections = [
    {
      id: 1, shipmentNo: 'SH-251201-001', splitNo: 'KD-TS-251201-01-S1', orderNo: 'KD-TS-251201-01',
      customerCode: 'C001', customerName: '삼성전자', creditGrade: 'A', grandTotal: 13750000, collectedAmount: 7000000, remainAmount: 6750000,
      dueDate: '2025-12-31', overdueDays: 0, paymentConfirmed: false, lastCollectionDate: '2025-12-08', contactPerson: '김부장', phone: '010-1234-5678', email: 'kim@samsung.com'
    },
    {
      id: 2, shipmentNo: 'SH-251205-001', splitNo: 'KD-BD-251205-01-S1', orderNo: 'KD-BD-251205-01',
      customerCode: 'C003', customerName: '현대건설', creditGrade: 'A', grandTotal: 35200000, collectedAmount: 0, remainAmount: 35200000,
      dueDate: '2026-01-05', overdueDays: 0, paymentConfirmed: false, lastCollectionDate: '-', contactPerson: '이과장', phone: '010-2345-6789', email: 'lee@hyundai.com'
    },
    {
      id: 3, shipmentNo: 'SH-251120-001', splitNo: 'KD-DW-251120-01-S1', orderNo: 'KD-DW-251120-01',
      customerCode: 'C004', customerName: '대우건설', creditGrade: 'B', grandTotal: 8800000, collectedAmount: 0, remainAmount: 8800000,
      dueDate: '2025-12-01', overdueDays: 14, paymentConfirmed: false, lastCollectionDate: '-', contactPerson: '박대리', phone: '010-3456-7890', email: 'park@daewoo.com'
    },
    {
      id: 4, shipmentNo: 'SH-251115-001', splitNo: 'KD-SH-251115-01-S1', orderNo: 'KD-SH-251115-01',
      customerCode: 'C005', customerName: '신흥건설', creditGrade: 'C', grandTotal: 12500000, collectedAmount: 0, remainAmount: 12500000,
      dueDate: '2025-11-30', overdueDays: 15, paymentConfirmed: false, lastCollectionDate: '-', contactPerson: '최과장', phone: '010-4567-8901', email: 'choi@shinheung.com'
    },
  ];

  const [collections, setCollections] = useState(pendingCollections);

  // 공통 UX: 미수금 목록 선택
  const pendingFiltered = collections.filter(c =>
    c.remainAmount > 0 &&
    (c.shipmentNo.toLowerCase().includes(search.toLowerCase()) ||
      c.customerName.includes(search))
  );
  const {
    selectedIds: pendingSelectedIds,
    handleSelect: handlePendingSelect,
    handleSelectAll: handlePendingSelectAll,
    isAllSelected: isPendingAllSelected,
    hasSelection: hasPendingSelection,
    isMultiSelect: isPendingMultiSelect,
    isSelected: isPendingSelected,
  } = useListSelection(pendingFiltered);

  // 공통 UX: 수금 이력 선택
  const historyFiltered = collectionHistory.filter(h =>
    h.shipmentNo.toLowerCase().includes(search.toLowerCase()) ||
    h.customerName.includes(search)
  );
  const {
    selectedIds: historySelectedIds,
    handleSelect: handleHistorySelect,
    handleSelectAll: handleHistorySelectAll,
    isAllSelected: isHistoryAllSelected,
    hasSelection: hasHistorySelection,
    isMultiSelect: isHistoryMultiSelect,
    isSelected: isHistorySelected,
  } = useListSelection(historyFiltered);

  // 수금 이력
  const [collectionHistory, setCollectionHistory] = useState([
    { id: 1, date: '2025-12-08', shipmentNo: 'SH-251201-001', customerName: '삼성전자', amount: 7000000, method: '계좌이체', account: '국민 123-456-789012', registrar: '김경리', note: '1차 입금' },
    { id: 2, date: '2025-12-01', shipmentNo: 'SH-251128-001', customerName: 'LG전자', amount: 15000000, method: '계좌이체', account: '신한 111-222-333444', registrar: '김경리', note: '전액 입금' },
    { id: 3, date: '2025-11-28', shipmentNo: 'SH-251125-001', customerName: '한화건설', amount: 22000000, method: '어음', account: '-', registrar: '김경리', note: '3개월 어음' },
  ]);

  const handleRegisterCollection = (item, amount, method) => {
    const today = new Date().toISOString().split('T')[0];
    const newCollectedAmount = item.collectedAmount + amount;
    const newRemainAmount = item.grandTotal - newCollectedAmount;
    const isFullyPaid = newRemainAmount <= 0;

    setCollections(prev => prev.map(c =>
      c.id === item.id ? {
        ...c,
        collectedAmount: newCollectedAmount,
        remainAmount: newRemainAmount,
        paymentConfirmed: isFullyPaid,
        lastCollectionDate: today
      } : c
    ));

    // 수금 이력 추가
    setCollectionHistory(prev => [{
      id: prev.length + 1,
      date: today,
      shipmentNo: item.shipmentNo,
      customerName: item.customerName,
      amount: amount,
      method: method,
      account: '국민 123-456-789012',
      registrar: '김경리',
      note: isFullyPaid ? '전액 입금' : '부분 입금'
    }, ...prev]);

    // 출하관리 paymentConfirmed 업데이트 (실제 연동)
    if (onUpdateShipment && isFullyPaid) {
      onUpdateShipment(item.shipmentNo, { paymentConfirmed: true });
    }

    alert(`수금이 등록되었습니다.\n\n수금금액: ${amount.toLocaleString()}원\n결제방법: ${method}\n잔액: ${newRemainAmount.toLocaleString()}원${isFullyPaid ? '\n\n✅ 전액 수금 완료 - 출하 가능 상태로 변경됨' : ''}`);
    setShowRegisterPanel(false);
  };

  // 독촉장 발송
  const handleSendReminder = (type) => {
    const today = new Date().toISOString().split('T')[0];
    const newReminders = selectedForReminder.map((item, idx) => ({
      id: reminderHistory.length + idx + 1,
      date: today,
      customerName: item.customerName,
      type: type,
      amount: item.remainAmount,
      result: '발송완료',
      sender: '김경리'
    }));
    setReminderHistory(prev => [...newReminders, ...prev]);
    alert(`${selectedForReminder.length}건의 독촉장이 ${type}로 발송되었습니다.`);
    setShowReminderModal(false);
    setSelectedForReminder([]);
  };

  const totalRemain = collections.reduce((sum, c) => sum + c.remainAmount, 0);
  const totalCollected = collections.reduce((sum, c) => sum + c.collectedAmount, 0);
  const overdueCount = collections.filter(c => c.overdueDays > 0).length;
  const overdueAmount = collections.filter(c => c.overdueDays > 0).reduce((sum, c) => sum + c.remainAmount, 0);

  // 거래처별 집계
  const customerSummary = collections.reduce((acc, c) => {
    if (!acc[c.customerCode]) {
      acc[c.customerCode] = {
        customerCode: c.customerCode,
        customerName: c.customerName,
        creditGrade: c.creditGrade,
        totalAmount: 0,
        collectedAmount: 0,
        remainAmount: 0,
        count: 0,
        maxOverdueDays: 0,
        contactPerson: c.contactPerson,
        phone: c.phone
      };
    }
    acc[c.customerCode].totalAmount += c.grandTotal;
    acc[c.customerCode].collectedAmount += c.collectedAmount;
    acc[c.customerCode].remainAmount += c.remainAmount;
    acc[c.customerCode].count += 1;
    acc[c.customerCode].maxOverdueDays = Math.max(acc[c.customerCode].maxOverdueDays, c.overdueDays);
    return acc;
  }, {});

  const tabs = [
    { id: 'pending', label: '미수금 현황', count: collections.filter(c => c.remainAmount > 0).length },
    { id: 'overdue', label: '연체 관리', count: overdueCount },
    { id: 'history', label: '수금 이력' },
    { id: 'customer', label: '거래처별 현황' },
    { id: 'reminder', label: '독촉장 발송' },
  ];

  return (
    <div className="space-y-6">
      <PageHeader icon={DollarSign} title="수금 목록" />

      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <StatCard icon={FileText} label="미수금 건수" value={`${collections.filter(c => c.remainAmount > 0).length}건`} color="orange" />
        <StatCard icon={AlertCircle} label="미수금 합계" value={`${totalRemain.toLocaleString()}원`} color="red" />
        <StatCard icon={AlertTriangle} label="연체금액" value={`${overdueAmount.toLocaleString()}원`} color="red" />
        <StatCard icon={Check} label="수금완료" value={`${totalCollected.toLocaleString()}원`} color="green" />
        <StatCard icon={TrendingUp} label="수금률" value={`${Math.round(totalCollected / (totalCollected + totalRemain) * 100)}%`} color="blue" />
      </div>

      {/* 연동 안내 */}
      <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
        <div className="flex items-center gap-2 text-blue-700">
          <AlertCircle className="w-5 h-5" />
          <span className="font-medium">출하관리 연동</span>
        </div>
        <p className="mt-1 text-sm text-blue-600">
          수금 완료 시 해당 출하건의 '입금확인' 상태가 자동으로 변경됩니다.
          B/C등급 거래처는 입금확인 후 출고 가능합니다.
        </p>
      </div>

      {/* 탭 네비게이션 */}
      <div className="flex flex-wrap gap-2">
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-full border transition-colors ${activeTab === tab.id
                ? 'bg-gray-900 text-white border-gray-900'
                : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
              }`}
          >
            <span>{tab.label}</span>
            {tab.count !== undefined && (
              <span className={activeTab === tab.id ? 'text-white' : 'text-gray-500'}>{tab.count}</span>
            )}
          </button>
        ))}
      </div>

      {/* 미수금 현황 탭 */}
      {activeTab === 'pending' && (
        <Card>
          <div className="flex justify-between items-center mb-4">
            <h3 className="font-medium">미수금 현황</h3>
            <div className="flex items-center gap-2">
              {isPendingMultiSelect && (
                <Button variant="outline" onClick={() => {
                  const selectedItems = pendingFiltered.filter(c => pendingSelectedIds.includes(c.id));
                  setSelectedForReminder(selectedItems);
                  setShowReminderModal(true);
                }}>
                  <Send className="w-4 h-4" /> 선택 독촉장 ({pendingSelectedIds.length})
                </Button>
              )}
              <SearchInput value={search} onChange={setSearch} placeholder="출하번호, 거래처명 검색" />
            </div>
          </div>

          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-center w-10">
                  <input type="checkbox" checked={isPendingAllSelected} onChange={handlePendingSelectAll} className="rounded" />
                </th>
                <th className="px-4 py-3 text-left">출하번호</th>
                <th className="px-4 py-3 text-left">거래처</th>
                <th className="px-4 py-3 text-center">신용등급</th>
                <th className="px-4 py-3 text-right">매출금액</th>
                <th className="px-4 py-3 text-right">수금액</th>
                <th className="px-4 py-3 text-right">미수잔액</th>
                <th className="px-4 py-3 text-center">결제예정일</th>
                <th className="px-4 py-3 text-center">입금확인</th>
                <th className="px-4 py-3 text-center">최종수금일</th>
                {hasPendingSelection && <th className="px-4 py-3 text-center">작업</th>}
              </tr>
            </thead>
            <tbody className="divide-y">
              {pendingFiltered.map(item => (
                <tr key={item.id} className={`hover:bg-gray-50 ${isPendingSelected(item.id) ? 'bg-blue-50' : item.overdueDays > 0 ? 'bg-red-50' : 'bg-yellow-50'}`}>
                  <td className="px-4 py-3 text-center">
                    <input type="checkbox" checked={isPendingSelected(item.id)} onChange={() => handlePendingSelect(item.id)} className="rounded" />
                  </td>
                  <td className="px-4 py-3 font-mono text-blue-600">{item.shipmentNo}</td>
                  <td className="px-4 py-3 font-medium">{item.customerName}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`px-2 py-1 rounded text-xs font-medium ${item.creditGrade === 'A' ? 'bg-green-100 text-green-700' :
                        item.creditGrade === 'B' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'
                      }`}>{item.creditGrade}</span>
                  </td>
                  <td className="px-4 py-3 text-right">{item.grandTotal.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-green-600">{item.collectedAmount.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-red-600 font-medium">{item.remainAmount.toLocaleString()}</td>
                  <td className="px-4 py-3 text-center">{item.dueDate}</td>
                  <td className="px-4 py-3 text-center">
                    {item.paymentConfirmed ? (
                      <span className="text-green-600 font-medium">✓ 확인</span>
                    ) : (
                      <span className="text-gray-400">- 미확인</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-center text-gray-500">{item.lastCollectionDate}</td>
                  {hasPendingSelection && (
                    <td className="px-4 py-3 text-center">
                      {isPendingSelected(item.id) && (
                        <Button
                          variant="primary"
                          size="sm"
                          onClick={() => { setSelectedShipment(item); setShowRegisterPanel(true); }}
                        >
                          수금등록
                        </Button>
                      )}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {/* 연체 관리 탭 */}
      {activeTab === 'overdue' && (
        <Card>
          <div className="flex justify-between items-center mb-4">
            <h3 className="font-medium">연체 현황</h3>
            <div className="flex gap-2">
              <Button variant="outline" onClick={() => {
                setSelectedForReminder(collections.filter(c => c.overdueDays > 0));
                setShowReminderModal(true);
              }}>
                <Send className="w-4 h-4" /> 일괄 독촉장 발송
              </Button>
            </div>
          </div>

          {overdueCount === 0 ? (
            <div className="text-center py-8 text-gray-500">연체된 미수금이 없습니다.</div>
          ) : (
            <>
              {/* 연체 경고 */}
              <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
                <div className="flex items-center gap-2 text-red-700">
                  <AlertTriangle className="w-5 h-5" />
                  <span className="font-medium">연체 경고: {overdueCount}건 / {overdueAmount.toLocaleString()}원</span>
                </div>
                <p className="mt-1 text-sm text-red-600">결제예정일이 지난 미수금입니다. 신속한 수금 조치가 필요합니다.</p>
              </div>

              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left">출하번호</th>
                    <th className="px-4 py-3 text-left">거래처</th>
                    <th className="px-4 py-3 text-center">신용등급</th>
                    <th className="px-4 py-3 text-right">미수잔액</th>
                    <th className="px-4 py-3 text-center">결제예정일</th>
                    <th className="px-4 py-3 text-center">연체일수</th>
                    <th className="px-4 py-3 text-left">담당자</th>
                    <th className="px-4 py-3 text-center">조치</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {collections.filter(c => c.overdueDays > 0).map(item => (
                    <tr key={item.id} className="hover:bg-gray-50 bg-red-50">
                      <td className="px-4 py-3 font-mono text-blue-600">{item.shipmentNo}</td>
                      <td className="px-4 py-3 font-medium">{item.customerName}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded text-xs font-medium ${item.creditGrade === 'A' ? 'bg-green-100 text-green-700' :
                            item.creditGrade === 'B' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'
                          }`}>{item.creditGrade}</span>
                      </td>
                      <td className="px-4 py-3 text-right text-red-600 font-medium">{item.remainAmount.toLocaleString()}</td>
                      <td className="px-4 py-3 text-center">{item.dueDate}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded text-xs font-medium ${item.overdueDays > 30 ? 'bg-red-200 text-red-800' :
                            item.overdueDays > 14 ? 'bg-orange-200 text-orange-800' : 'bg-yellow-200 text-yellow-800'
                          }`}>{item.overdueDays}일</span>
                      </td>
                      <td className="px-4 py-3">
                        <div className="text-sm">{item.contactPerson}</div>
                        <div className="text-xs text-gray-500">{item.phone}</div>
                      </td>
                      <td className="px-4 py-3 text-center">
                        <div className="flex justify-center gap-1">
                          <button className="p-1 hover:bg-blue-100 rounded" title="전화" onClick={() => alert(`전화걸기: ${item.phone}`)}>
                            <Phone className="w-4 h-4 text-blue-500" />
                          </button>
                          <button className="p-1 hover:bg-orange-100 rounded" title="독촉장"
                            onClick={() => { setSelectedForReminder([item]); setShowReminderModal(true); }}>
                            <Send className="w-4 h-4 text-orange-500" />
                          </button>
                          <Button variant="primary" size="sm" onClick={() => { setSelectedShipment(item); setShowRegisterPanel(true); }}>
                            수금
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </>
          )}
        </Card>
      )}

      {/* 수금 이력 탭 */}
      {activeTab === 'history' && (
        <Card>
          <div className="flex justify-between items-center mb-4">
            <h3 className="font-medium">수금 이력</h3>
            <div className="flex items-center gap-2">
              {isHistoryMultiSelect && (
                <Button variant="outline" onClick={() => setShowDeleteModal(true)}>
                  <Trash2 className="w-4 h-4" /> 선택 삭제 ({historySelectedIds.length})
                </Button>
              )}
              <SearchInput value={search} onChange={setSearch} placeholder="출하번호, 거래처명 검색" />
            </div>
          </div>

          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-center w-10">
                  <input type="checkbox" checked={isHistoryAllSelected} onChange={handleHistorySelectAll} className="rounded" />
                </th>
                <th className="px-4 py-3 text-center">수금일</th>
                <th className="px-4 py-3 text-left">출하번호</th>
                <th className="px-4 py-3 text-left">거래처</th>
                <th className="px-4 py-3 text-right">수금금액</th>
                <th className="px-4 py-3 text-center">결제방법</th>
                <th className="px-4 py-3 text-left">입금계좌</th>
                <th className="px-4 py-3 text-center">등록자</th>
                <th className="px-4 py-3 text-left">비고</th>
                {hasHistorySelection && <th className="px-4 py-3 text-center">작업</th>}
              </tr>
            </thead>
            <tbody className="divide-y">
              {historyFiltered.map(item => (
                <tr key={item.id} className={`hover:bg-gray-50 ${isHistorySelected(item.id) ? 'bg-blue-50' : ''}`}>
                  <td className="px-4 py-3 text-center">
                    <input type="checkbox" checked={isHistorySelected(item.id)} onChange={() => handleHistorySelect(item.id)} className="rounded" />
                  </td>
                  <td className="px-4 py-3 text-center">{item.date}</td>
                  <td className="px-4 py-3 font-mono text-blue-600">{item.shipmentNo}</td>
                  <td className="px-4 py-3 font-medium">{item.customerName}</td>
                  <td className="px-4 py-3 text-right text-green-600 font-medium">{item.amount.toLocaleString()}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`px-2 py-1 rounded text-xs ${item.method === '계좌이체' ? 'bg-blue-100 text-blue-700' :
                        item.method === '현금' ? 'bg-green-100 text-green-700' :
                          item.method === '어음' ? 'bg-purple-100 text-purple-700' : 'bg-gray-100 text-gray-700'
                      }`}>{item.method}</span>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-600">{item.account}</td>
                  <td className="px-4 py-3 text-center">{item.registrar}</td>
                  <td className="px-4 py-3 text-sm text-gray-500">{item.note}</td>
                  {hasHistorySelection && (
                    <td className="px-4 py-3 text-center">
                      {isHistorySelected(item.id) && (
                        <div className="flex justify-center gap-1">
                          <button className="p-1 hover:bg-gray-100 rounded" title="수정">
                            <Edit3 className="w-4 h-4 text-blue-500" />
                          </button>
                          <button className="p-1 hover:bg-red-100 rounded" title="삭제"
                            onClick={() => { if (window.confirm('이 수금 이력을 삭제하시겠습니까?')) setCollectionHistory(prev => prev.filter(h => h.id !== item.id)); }}>
                            <Trash2 className="w-4 h-4 text-red-500" />
                          </button>
                        </div>
                      )}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {/* 거래처별 현황 탭 */}
      {activeTab === 'customer' && (
        <Card>
          <div className="flex justify-between items-center mb-4">
            <h3 className="font-medium">거래처별 미수금 현황</h3>
          </div>

          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left">거래처코드</th>
                <th className="px-4 py-3 text-left">거래처명</th>
                <th className="px-4 py-3 text-center">신용등급</th>
                <th className="px-4 py-3 text-center">건수</th>
                <th className="px-4 py-3 text-right">매출총액</th>
                <th className="px-4 py-3 text-right">수금액</th>
                <th className="px-4 py-3 text-right">미수잔액</th>
                <th className="px-4 py-3 text-center">최대연체</th>
                <th className="px-4 py-3 text-left">담당자</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {Object.values(customerSummary).filter(c => c.remainAmount > 0).map(item => (
                <tr key={item.customerCode} className={`hover:bg-gray-50 ${item.maxOverdueDays > 0 ? 'bg-red-50' : ''}`}>
                  <td className="px-4 py-3 font-medium">{item.customerCode}</td>
                  <td className="px-4 py-3">{item.customerName}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`px-2 py-1 rounded text-xs font-medium ${item.creditGrade === 'A' ? 'bg-green-100 text-green-700' :
                        item.creditGrade === 'B' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'
                      }`}>{item.creditGrade}</span>
                  </td>
                  <td className="px-4 py-3 text-center">{item.count}건</td>
                  <td className="px-4 py-3 text-right">{item.totalAmount.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-green-600">{item.collectedAmount.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-red-600 font-medium">{item.remainAmount.toLocaleString()}</td>
                  <td className="px-4 py-3 text-center">
                    {item.maxOverdueDays > 0 ? (
                      <span className="text-red-600 font-medium">{item.maxOverdueDays}일</span>
                    ) : (
                      <span className="text-gray-400">-</span>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <div className="text-sm">{item.contactPerson}</div>
                    <div className="text-xs text-gray-500">{item.phone}</div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {/* 독촉장 발송 탭 */}
      {activeTab === 'reminder' && (
        <Card>
          <div className="flex justify-between items-center mb-4">
            <h3 className="font-medium">독촉장 발송 이력</h3>
            <Button variant="primary" onClick={() => {
              const overdueItems = collections.filter(c => c.overdueDays > 0);
              if (overdueItems.length === 0) {
                alert('발송 대상(연체 미수금)이 없습니다.');
                return;
              }
              setSelectedForReminder(overdueItems);
              setShowReminderModal(true);
            }}>
              <Send className="w-4 h-4" /> 독촉장 발송
            </Button>
          </div>

          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-center">발송일</th>
                <th className="px-4 py-3 text-left">거래처</th>
                <th className="px-4 py-3 text-center">발송방법</th>
                <th className="px-4 py-3 text-right">독촉금액</th>
                <th className="px-4 py-3 text-center">결과</th>
                <th className="px-4 py-3 text-center">담당자</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {reminderHistory.map(item => (
                <tr key={item.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3 text-center">{item.date}</td>
                  <td className="px-4 py-3 font-medium">{item.customerName}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`px-2 py-1 rounded text-xs ${item.type === '이메일' ? 'bg-blue-100 text-blue-700' :
                        item.type === '팩스' ? 'bg-purple-100 text-purple-700' : 'bg-gray-100 text-gray-700'
                      }`}>{item.type}</span>
                  </td>
                  <td className="px-4 py-3 text-right text-red-600">{item.amount.toLocaleString()}</td>
                  <td className="px-4 py-3 text-center">
                    <span className="px-2 py-1 rounded text-xs bg-green-100 text-green-700">{item.result}</span>
                  </td>
                  <td className="px-4 py-3 text-center">{item.sender}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}

      {/* 수금 등록 모달 */}
      {showRegisterPanel && selectedShipment && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-lg w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold">수금 등록</h3>
              <button onClick={() => setShowRegisterPanel(false)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4">
              <div className="p-4 bg-gray-50 rounded-lg">
                <div className="grid grid-cols-2 gap-4">
                  <div><p className="text-sm text-gray-500">출하번호</p><p className="font-mono">{selectedShipment.shipmentNo}</p></div>
                  <div><p className="text-sm text-gray-500">거래처</p><p className="font-medium">{selectedShipment.customerName}</p></div>
                  <div><p className="text-sm text-gray-500">매출금액</p><p>{selectedShipment.grandTotal.toLocaleString()}원</p></div>
                  <div><p className="text-sm text-gray-500">미수잔액</p><p className="text-red-600 font-medium">{selectedShipment.remainAmount.toLocaleString()}원</p></div>
                  {selectedShipment.overdueDays > 0 && (
                    <div className="col-span-2">
                      <p className="text-sm text-gray-500">연체현황</p>
                      <p className="text-red-600 font-medium">{selectedShipment.overdueDays}일 연체</p>
                    </div>
                  )}
                </div>
              </div>
              <FormField label="수금금액" required>
                <input type="number" id="collectionAmount" defaultValue={selectedShipment.remainAmount} className="w-full px-3 py-2 border rounded-lg" placeholder="수금금액 입력" />
                <div className="flex gap-2 mt-2">
                  <button onClick={() => document.getElementById('collectionAmount').value = selectedShipment.remainAmount} className="px-3 py-1 text-xs bg-blue-100 text-blue-700 rounded hover:bg-blue-200">전액</button>
                  <button onClick={() => document.getElementById('collectionAmount').value = Math.floor(selectedShipment.remainAmount / 2)} className="px-3 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200">50%</button>
                </div>
              </FormField>
              <FormField label="결제방법" required>
                <select id="paymentMethod" className="w-full px-3 py-2 border rounded-lg"><option value="계좌이체">계좌이체</option><option value="현금">현금</option><option value="어음">어음</option><option value="카드">카드</option></select>
              </FormField>
              <FormField label="입금계좌">
                <select className="w-full px-3 py-2 border rounded-lg"><option>국민 123-456-789012 (주)금도방재</option><option>신한 111-222-333444 (주)금도방재</option></select>
              </FormField>
              <FormField label="비고">
                <textarea className="w-full px-3 py-2 border rounded-lg" rows={2} placeholder="수금 관련 메모"></textarea>
              </FormField>
              <div className="flex gap-2">
                <Button variant="outline" className="flex-1" onClick={() => setShowRegisterPanel(false)}>취소</Button>
                <Button variant="primary" className="flex-1" onClick={() => { const amount = parseInt(document.getElementById('collectionAmount').value) || 0; const method = document.getElementById('paymentMethod').value; if (amount <= 0) { alert('수금금액을 입력해주세요.'); return; } if (amount > selectedShipment.remainAmount) { alert('수금금액이 미수잔액을 초과할 수 없습니다.'); return; } handleRegisterCollection(selectedShipment, amount, method); }}><Check className="w-4 h-4" /> 수금 등록</Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 독촉장 발송 모달 */}
      {showReminderModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-lg w-full mx-4">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold">독촉장 발송</h3>
              <button onClick={() => setShowReminderModal(false)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4">
              <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                <p className="text-sm font-medium text-yellow-800">발송 대상: {selectedForReminder.length}건</p>
                <p className="text-sm text-yellow-700">총 독촉금액: {selectedForReminder.reduce((sum, i) => sum + i.remainAmount, 0).toLocaleString()}원</p>
              </div>
              <div className="space-y-2 max-h-40 overflow-y-auto">
                {selectedForReminder.map(item => (
                  <div key={item.id} className="flex justify-between items-center p-2 bg-gray-50 rounded">
                    <span className="font-medium">{item.customerName}</span>
                    <span className="text-red-600">{item.remainAmount.toLocaleString()}원</span>
                  </div>
                ))}
              </div>
              <FormField label="발송 방법">
                <div className="flex gap-4">
                  {['이메일', '팩스', 'SMS'].map(type => (
                    <label key={type} className="flex items-center gap-2">
                      <input type="radio" name="reminderType" value={type} defaultChecked={type === '이메일'} />
                      <span>{type}</span>
                    </label>
                  ))}
                </div>
              </FormField>
              <FormField label="발송 메시지">
                <textarea className="w-full px-3 py-2 border rounded-lg" rows={3} defaultValue="안녕하세요. 결제 예정일이 경과된 미수금에 대해 안내 드립니다. 빠른 시일 내 입금 부탁드립니다."></textarea>
              </FormField>
              <div className="flex gap-2">
                <Button variant="outline" className="flex-1" onClick={() => setShowReminderModal(false)}>취소</Button>
                <Button variant="primary" className="flex-1" onClick={() => {
                  const type = document.querySelector('input[name="reminderType"]:checked')?.value || '이메일';
                  handleSendReminder(type);
                }}><Send className="w-4 h-4" /> 발송</Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 어음관리 (A4-3)
const BillManagement = () => {
  const [search, setSearch] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');

  const [bills, setBills] = useState([
    {
      id: 1, billNo: 'BL-251201-001', customerName: '삼성전자', amount: 6750000,
      issueDate: '2025-12-01', dueDate: '2026-03-01', status: '보유중', note: '3개월 어음'
    },
    {
      id: 2, billNo: 'BL-251105-001', customerName: '대우건설', amount: 8800000,
      issueDate: '2025-11-05', dueDate: '2026-02-05', status: '보유중', note: '3개월 어음'
    },
  ]);

  const statusFilters = [
    { id: 'all', label: '전체' },
    { id: '보유중', label: '보유중' },
    { id: '만기도래', label: '만기도래' },
    { id: '추심완료', label: '추심완료' },
  ];

  return (
    <div className="space-y-6">
      <PageHeader icon={FileText} title="어음 목록" />

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatCard icon={FileText} label="보유어음" value={`${bills.length}건`} color="blue" />
        <StatCard icon={DollarSign} label="보유금액" value={`${bills.reduce((sum, b) => sum + b.amount, 0).toLocaleString()}원`} color="purple" />
        <StatCard icon={Clock} label="만기도래" value={`${bills.filter(b => b.status === '만기도래').length}건`} color="orange" />
        <StatCard icon={Check} label="추심완료" value={`${bills.filter(b => b.status === '추심완료').length}건`} color="green" />
      </div>

      <Card>
        <div className="flex justify-between items-center mb-4">
          <div className="flex gap-2">
            {statusFilters.map(filter => (
              <button
                key={filter.id}
                onClick={() => setFilterStatus(filter.id)}
                className={`px-4 py-2 rounded-lg text-sm font-medium ${filterStatus === filter.id ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
              >
                {filter.label}
              </button>
            ))}
          </div>
          <div className="flex gap-2">
            <SearchInput value={search} onChange={setSearch} placeholder="어음번호, 거래처명 검색" />
            <Button variant="primary"><Plus className="w-4 h-4" /> 어음 등록</Button>
          </div>
        </div>

        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left">어음번호</th>
              <th className="px-4 py-3 text-left">거래처</th>
              <th className="px-4 py-3 text-right">금액</th>
              <th className="px-4 py-3 text-center">발행일</th>
              <th className="px-4 py-3 text-center">만기일</th>
              <th className="px-4 py-3 text-center">상태</th>
              <th className="px-4 py-3 text-left">비고</th>
              <th className="px-4 py-3 text-center">관리</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {bills.map(bill => (
              <tr key={bill.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 font-mono text-blue-600">{bill.billNo}</td>
                <td className="px-4 py-3 font-medium">{bill.customerName}</td>
                <td className="px-4 py-3 text-right font-medium">{bill.amount.toLocaleString()}</td>
                <td className="px-4 py-3 text-center">{bill.issueDate}</td>
                <td className="px-4 py-3 text-center">{bill.dueDate}</td>
                <td className="px-4 py-3 text-center"><StatusBadge status={bill.status} /></td>
                <td className="px-4 py-3 text-gray-500">{bill.note}</td>
                <td className="px-4 py-3 text-center">
                  <button className="p-1 hover:bg-gray-100 rounded"><Eye className="w-4 h-4 text-gray-500" /></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
};

// 원가관리 (A5)
const CostAnalysisManagement = () => {
  const [activeTab, setActiveTab] = useState('summary');
  const [search, setSearch] = useState('');
  const [selectedOrder, setSelectedOrder] = useState(null);

  // 수주별 원가 데이터
  const costData = [
    {
      id: 1, orderNo: 'KD-TS-251201-01', customerName: '삼성전자', siteName: '삼성 서초사옥',
      saleAmount: 12500000, materialCost: 4500000, laborCost: 2000000, outsourcingCost: 1500000, overheadCost: 800000,
      totalCost: 8800000, profit: 3700000, profitRate: 29.6
    },
    {
      id: 2, orderNo: 'KD-SL-251203-01', customerName: 'LG전자', siteName: 'LG 트윈타워',
      saleAmount: 5400000, materialCost: 1800000, laborCost: 900000, outsourcingCost: 600000, overheadCost: 350000,
      totalCost: 3650000, profit: 1750000, profitRate: 32.4
    },
    {
      id: 3, orderNo: 'KD-BD-251205-01', customerName: '현대건설', siteName: '현대 본사',
      saleAmount: 32000000, materialCost: 12000000, laborCost: 5000000, outsourcingCost: 4000000, overheadCost: 2000000,
      totalCost: 23000000, profit: 9000000, profitRate: 28.1
    },
  ];

  const tabs = [
    { id: 'summary', label: '원가요약', icon: BarChart3 },
    { id: 'material', label: '자재비', icon: Box },
    { id: 'outsourcing', label: '외주비', icon: Truck },
    { id: 'labor', label: '인건비', icon: Users },
    { id: 'overhead', label: '경비', icon: CreditCard },
    { id: 'manufacturing', label: '제조원가', icon: Factory },
  ];

  const totalSale = costData.reduce((sum, c) => sum + c.saleAmount, 0);
  const totalCost = costData.reduce((sum, c) => sum + c.totalCost, 0);
  const totalProfit = costData.reduce((sum, c) => sum + c.profit, 0);
  const avgProfitRate = (totalProfit / totalSale * 100).toFixed(1);

  return (
    <div className="space-y-6">
      <PageHeader icon={Calculator} title="원가 분석" />

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatCard icon={DollarSign} label="총 매출" value={`${totalSale.toLocaleString()}원`} color="blue" />
        <StatCard icon={ShoppingCart} label="총 원가" value={`${totalCost.toLocaleString()}원`} color="orange" />
        <StatCard icon={TrendingUp} label="총 이익" value={`${totalProfit.toLocaleString()}원`} color="green" />
        <StatCard icon={BarChart3} label="평균이익률" value={`${avgProfitRate}%`} color="purple" />
      </div>

      {/* 탭 */}
      <div className="flex gap-2 border-b">
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors ${activeTab === tab.id
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
          >
            <tab.icon className="w-4 h-4" />
            {tab.label}
          </button>
        ))}
      </div>

      {activeTab === 'summary' && (
        <Card>
          <div className="flex justify-between items-center mb-4">
            <h3 className="font-medium">수주별 원가 현황</h3>
            <SearchInput value={search} onChange={setSearch} placeholder="수주번호, 거래처명 검색" />
          </div>

          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left">수주번호</th>
                <th className="px-4 py-3 text-left">거래처</th>
                <th className="px-4 py-3 text-right">매출액</th>
                <th className="px-4 py-3 text-right">자재비</th>
                <th className="px-4 py-3 text-right">인건비</th>
                <th className="px-4 py-3 text-right">외주비</th>
                <th className="px-4 py-3 text-right">경비</th>
                <th className="px-4 py-3 text-right">총원가</th>
                <th className="px-4 py-3 text-right">이익</th>
                <th className="px-4 py-3 text-center">이익률</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {costData.map(item => (
                <tr key={item.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3 font-mono text-blue-600">{item.orderNo}</td>
                  <td className="px-4 py-3">{item.customerName}</td>
                  <td className="px-4 py-3 text-right">{item.saleAmount.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-orange-600">{item.materialCost.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-blue-600">{item.laborCost.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-purple-600">{item.outsourcingCost.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right text-gray-600">{item.overheadCost.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right font-medium text-red-600">{item.totalCost.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right font-medium text-green-600">{item.profit.toLocaleString()}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`px-2 py-1 rounded text-xs font-medium ${item.profitRate >= 30 ? 'bg-green-100 text-green-700' :
                        item.profitRate >= 20 ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'
                      }`}>{item.profitRate}%</span>
                  </td>
                </tr>
              ))}
            </tbody>
            <tfoot className="bg-gray-100 font-medium">
              <tr>
                <td className="px-4 py-3" colSpan={2}>합계</td>
                <td className="px-4 py-3 text-right">{totalSale.toLocaleString()}</td>
                <td className="px-4 py-3 text-right">{costData.reduce((sum, c) => sum + c.materialCost, 0).toLocaleString()}</td>
                <td className="px-4 py-3 text-right">{costData.reduce((sum, c) => sum + c.laborCost, 0).toLocaleString()}</td>
                <td className="px-4 py-3 text-right">{costData.reduce((sum, c) => sum + c.outsourcingCost, 0).toLocaleString()}</td>
                <td className="px-4 py-3 text-right">{costData.reduce((sum, c) => sum + c.overheadCost, 0).toLocaleString()}</td>
                <td className="px-4 py-3 text-right text-red-600">{totalCost.toLocaleString()}</td>
                <td className="px-4 py-3 text-right text-green-600">{totalProfit.toLocaleString()}</td>
                <td className="px-4 py-3 text-center">{avgProfitRate}%</td>
              </tr>
            </tfoot>
          </table>
        </Card>
      )}

      {activeTab === 'material' && (
        <Card title="자재비 상세">
          <div className="space-y-4">
            {costData.map(item => (
              <div key={item.id} className="p-4 border rounded-lg">
                <div className="flex justify-between items-center mb-2">
                  <span className="font-mono text-blue-600">{item.orderNo}</span>
                  <span className="font-medium text-orange-600">{item.materialCost.toLocaleString()}원</span>
                </div>
                <div className="text-sm text-gray-500">{item.customerName} - {item.siteName}</div>
                <div className="mt-2 h-2 bg-gray-100 rounded-full overflow-hidden">
                  <div className="h-full bg-orange-500" style={{ width: `${(item.materialCost / item.saleAmount) * 100}%` }} />
                </div>
                <div className="text-xs text-gray-400 mt-1">매출대비 {((item.materialCost / item.saleAmount) * 100).toFixed(1)}%</div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {activeTab === 'manufacturing' && (
        <Card title="제조원가 분석">
          <div className="grid grid-cols-2 gap-6">
            <div>
              <h4 className="font-medium mb-4">원가 구성비</h4>
              <div className="space-y-3">
                {[
                  { label: '자재비', value: costData.reduce((sum, c) => sum + c.materialCost, 0), color: 'orange' },
                  { label: '인건비', value: costData.reduce((sum, c) => sum + c.laborCost, 0), color: 'blue' },
                  { label: '외주비', value: costData.reduce((sum, c) => sum + c.outsourcingCost, 0), color: 'purple' },
                  { label: '경비', value: costData.reduce((sum, c) => sum + c.overheadCost, 0), color: 'gray' },
                ].map(item => (
                  <div key={item.label} className="flex items-center gap-3">
                    <span className="w-16 text-sm">{item.label}</span>
                    <div className="flex-1 h-4 bg-gray-100 rounded-full overflow-hidden">
                      <div className={`h-full bg-${item.color}-500`} style={{ width: `${(item.value / totalCost) * 100}%` }} />
                    </div>
                    <span className="w-20 text-right text-sm">{((item.value / totalCost) * 100).toFixed(1)}%</span>
                    <span className="w-24 text-right text-sm">{(item.value / 10000).toLocaleString()}만</span>
                  </div>
                ))}
              </div>
            </div>
            <div>
              <h4 className="font-medium mb-4">이익률 분포</h4>
              <div className="space-y-3">
                {costData.map(item => (
                  <div key={item.id} className="flex items-center gap-3">
                    <span className="w-32 text-sm truncate">{item.customerName}</span>
                    <div className="flex-1 h-4 bg-gray-100 rounded-full overflow-hidden">
                      <div className={`h-full ${item.profitRate >= 30 ? 'bg-green-500' : item.profitRate >= 20 ? 'bg-blue-500' : 'bg-red-500'
                        }`} style={{ width: `${item.profitRate}%` }} />
                    </div>
                    <span className="w-12 text-right text-sm font-medium">{item.profitRate}%</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </Card>
      )}

      {['outsourcing', 'labor', 'overhead'].includes(activeTab) && (
        <Card title={`${tabs.find(t => t.id === activeTab)?.label} 상세`}>
          <p className="text-gray-500 text-center py-8">상세 데이터가 표시됩니다.</p>
        </Card>
      )}
    </div>
  );
};

// =============================================
// 시스템관리 컴포넌트
// =============================================

// 사용자관리
const UserManagement = () => {
  const [search, setSearch] = useState('');
  const [showPanel, setShowPanel] = useState(false);
  const [selectedUser, setSelectedUser] = useState(null);
  const [panelMode, setPanelMode] = useState('create');

  const [users, setUsers] = useState([
    {
      id: 1, userId: 'admin', userName: '관리자', email: 'admin@kd.com', dept: '시스템관리',
      role: '시스템관리자', phone: '010-1111-1111', status: '활성', lastLogin: '2025-12-09 09:30', createdAt: '2024-01-01'
    },
    {
      id: 2, userId: 'sales01', userName: '김판매', email: 'sales01@kd.com', dept: '판매부',
      role: '판매담당', phone: '010-2222-2222', status: '활성', lastLogin: '2025-12-09 08:45', createdAt: '2024-03-15'
    },
    {
      id: 3, userId: 'prod01', userName: '이생산', email: 'prod01@kd.com', dept: '생산부',
      role: '생산담당', phone: '010-3333-3333', status: '활성', lastLogin: '2025-12-08 17:20', createdAt: '2024-06-01'
    },
    {
      id: 4, userId: 'qa01', userName: '박품질', email: 'qa01@kd.com', dept: '품질관리부',
      role: '품질담당', phone: '010-4444-4444', status: '비활성', lastLogin: '2025-11-30 15:00', createdAt: '2024-09-01'
    },
  ]);

  // 통계
  const activeCount = users.filter(u => u.status === '활성').length;
  const inactiveCount = users.filter(u => u.status === '비활성').length;
  const deptGroups = [...new Set(users.map(u => u.dept))].length;

  const filtered = users.filter(u =>
    u.userId.toLowerCase().includes(search.toLowerCase()) ||
    u.userName.includes(search) ||
    u.dept.includes(search) ||
    u.email.toLowerCase().includes(search.toLowerCase())
  );

  const handleCreateUser = () => {
    setPanelMode('create');
    setSelectedUser(null);
    setShowPanel(true);
  };

  const handleEditUser = (user) => {
    setPanelMode('edit');
    setSelectedUser(user);
    setShowPanel(true);
  };

  const handleToggleStatus = (user) => {
    const newStatus = user.status === '활성' ? '비활성' : '활성';
    setUsers(prev => prev.map(u => u.id === user.id ? { ...u, status: newStatus } : u));
    alert(`${user.userName} 사용자가 ${newStatus} 상태로 변경되었습니다.`);
  };

  return (
    <div className="space-y-6">
      <PageHeader icon={Users} title="사용자 목록" />

      {/* 통계 카드 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatCard icon={Users} label="전체 사용자" value={`${users.length}명`} color="blue" />
        <StatCard icon={Check} label="활성 사용자" value={`${activeCount}명`} color="green" />
        <StatCard icon={XCircle} label="비활성 사용자" value={`${inactiveCount}명`} color="red" />
        <StatCard icon={Building} label="부서 수" value={`${deptGroups}개`} color="purple" />
      </div>

      {/* 검색 및 등록 */}
      <Card>
        <div className="flex justify-between items-center mb-4">
          <SearchInput value={search} onChange={setSearch} placeholder="사용자ID, 이름, 부서 검색" />
          <Button variant="primary" onClick={handleCreateUser}><Plus className="w-4 h-4" /> 사용자등록</Button>
        </div>

        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left">사용자ID</th>
              <th className="px-4 py-3 text-left">이름</th>
              <th className="px-4 py-3 text-left">이메일</th>
              <th className="px-4 py-3 text-left">부서</th>
              <th className="px-4 py-3 text-left">권한</th>
              <th className="px-4 py-3 text-center">상태</th>
              <th className="px-4 py-3 text-center">최종로그인</th>
              <th className="px-4 py-3 text-center">관리</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map(user => (
              <tr key={user.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 font-medium">{user.userId}</td>
                <td className="px-4 py-3">{user.userName}</td>
                <td className="px-4 py-3 text-gray-600">{user.email}</td>
                <td className="px-4 py-3">{user.dept}</td>
                <td className="px-4 py-3">
                  <span className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">{user.role}</span>
                </td>
                <td className="px-4 py-3 text-center">
                  <span className={`px-2 py-1 rounded text-xs ${user.status === '활성' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600'
                    }`}>{user.status}</span>
                </td>
                <td className="px-4 py-3 text-center text-gray-600 text-xs">{user.lastLogin}</td>
                <td className="px-4 py-3 text-center">
                  <div className="flex justify-center gap-1">
                    <button onClick={() => handleEditUser(user)} className="p-1 hover:bg-gray-100 rounded" title="수정">
                      <Edit3 className="w-4 h-4 text-gray-500" />
                    </button>
                    <button onClick={() => handleToggleStatus(user)}
                      className={`p-1 rounded ${user.status === '활성' ? 'hover:bg-red-100' : 'hover:bg-green-100'}`}
                      title={user.status === '활성' ? '비활성화' : '활성화'}>
                      {user.status === '활성' ?
                        <XCircle className="w-4 h-4 text-red-500" /> :
                        <Check className="w-4 h-4 text-green-500" />}
                    </button>
                    <button className="p-1 hover:bg-gray-100 rounded" title="비밀번호초기화">
                      <Key className="w-4 h-4 text-gray-500" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
};

// 권한관리
const RoleManagement = () => {
  const [selectedRole, setSelectedRole] = useState(null);
  const [showPanel, setShowPanel] = useState(false);

  const roles = [
    {
      id: 1, roleCode: 'ADMIN', roleName: '시스템관리자', description: '시스템 전체 관리 권한',
      userCount: 1, permissions: ['전체관리', '사용자관리', '권한관리', '시스템설정'], status: '활성'
    },
    {
      id: 2, roleCode: 'SALES', roleName: '판매담당', description: '판매 관련 권한',
      userCount: 5, permissions: ['견적관리', '수주관리', '거래처관리', '매출조회'], status: '활성'
    },
    {
      id: 3, roleCode: 'PRODUCTION', roleName: '생산담당', description: '생산 관련 권한',
      userCount: 8, permissions: ['작업지시관리', '작업실적', '생산현황'], status: '활성'
    },
    {
      id: 4, roleCode: 'QA', roleName: '품질담당', description: '품질 검사 관련 권한',
      userCount: 3, permissions: ['검사관리', '부적합관리', '품질현황'], status: '활성'
    },
    {
      id: 5, roleCode: 'ACCOUNTING', roleName: '회계담당', description: '회계 및 재무 관련 권한',
      userCount: 2, permissions: ['매출관리', '세금계산서', '수금관리', '미수금관리'], status: '활성'
    },
  ];

  const menuPermissions = [
    { group: '기준정보', menus: ['품목기준관리', '공정기준관리', '품질기준관리', '거래처기준관리'] },
    { group: '판매관리', menus: ['견적관리', '수주관리', '거래처관리', '출하관리'] },
    { group: '생산관리', menus: ['작업지시관리', '작업실적', '생산현황판'] },
    { group: '품질관리', menus: ['수입검사', '중간검사', '제품검사', '부적합관리'] },
    { group: '회계관리', menus: ['매출관리', '세금계산서', '수금관리', '미수금관리'] },
    { group: '시스템관리', menus: ['사용자관리', '권한관리', '시스템설정'] },
  ];

  return (
    <div className="space-y-6">
      <PageHeader icon={ShieldCheck} title="권한 설정" />

      <div className="grid grid-cols-3 gap-6">
        {/* 권한 목록 */}
        <Card title="권한 목록" className="col-span-1">
          <div className="space-y-2">
            {roles.map(role => (
              <div
                key={role.id}
                onClick={() => setSelectedRole(role)}
                className={`p-3 rounded-lg border cursor-pointer transition-colors ${selectedRole?.id === role.id ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:bg-gray-50'
                  }`}
              >
                <div className="flex justify-between items-start">
                  <div>
                    <div className="font-medium">{role.roleName}</div>
                    <div className="text-xs text-gray-500 mt-1">{role.roleCode}</div>
                  </div>
                  <span className="text-xs text-gray-500">{role.userCount}명</span>
                </div>
                <div className="text-sm text-gray-600 mt-2">{role.description}</div>
              </div>
            ))}
          </div>
          <Button variant="primary" className="w-full mt-4" onClick={() => setShowPanel(true)}>
            <Plus className="w-4 h-4" /> 권한추가
          </Button>
        </Card>

        {/* 권한 상세 */}
        <Card title={selectedRole ? `${selectedRole.roleName} 권한설정` : '권한을 선택하세요'} className="col-span-2">
          {selectedRole ? (
            <div className="space-y-6">
              {/* 기본 정보 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">권한코드</label>
                  <input type="text" value={selectedRole.roleCode} readOnly
                    className="w-full px-3 py-2 border rounded-lg bg-gray-50" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">권한명</label>
                  <input type="text" value={selectedRole.roleName}
                    className="w-full px-3 py-2 border rounded-lg" />
                </div>
              </div>

              {/* 메뉴별 권한 설정 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-3">메뉴 접근 권한</label>
                <div className="space-y-4">
                  {menuPermissions.map(group => (
                    <div key={group.group} className="border rounded-lg p-4">
                      <div className="flex items-center gap-2 mb-3">
                        <input type="checkbox" id={`group-${group.group}`} className="rounded border-gray-300" />
                        <label htmlFor={`group-${group.group}`} className="font-medium">{group.group}</label>
                      </div>
                      <div className="grid grid-cols-4 gap-3 ml-6">
                        {group.menus.map(menu => (
                          <label key={menu} className="flex items-center gap-2 text-sm">
                            <input type="checkbox" className="rounded border-gray-300"
                              defaultChecked={selectedRole.permissions.some(p => menu.includes(p) || p.includes(menu.slice(0, 2)))} />
                            {menu}
                          </label>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button variant="outline">취소</Button>
                <Button variant="primary" onClick={() => alert('권한이 저장되었습니다.')}>저장</Button>
              </div>
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center h-64 text-gray-500">
              <ShieldCheck className="w-12 h-12 mb-2 opacity-50" />
              <p>좌측에서 권한을 선택하세요</p>
            </div>
          )}
        </Card>
      </div>
    </div>
  );
};

// 시스템설정
const SystemSettings = () => {
  const [activeTab, setActiveTab] = useState('general');
  const [settings, setSettings] = useState({
    companyName: '(주)금동방화',
    businessNo: '123-45-67890',
    ceo: '홍길동',
    address: '서울시 강남구 테헤란로 123',
    phone: '02-1234-5678',
    fax: '02-1234-5679',
    email: 'info@kd.com',
    logo: '',
    // 번호 설정
    orderPrefix: 'KD',
    quotePrefix: 'KD-PR',
    lotPrefix: 'KD',
    // 시스템 설정
    sessionTimeout: 30,
    maxLoginAttempts: 5,
    passwordExpireDays: 90,
    autoLogout: true,
    // 알림 설정
    emailNotification: true,
    smsNotification: false,
    overdueAlert: true,
    stockAlert: true,
  });

  const tabs = [
    { id: 'general', label: '회사정보', icon: Building },
    { id: 'number', label: '번호규칙', icon: Hash },
    { id: 'security', label: '보안설정', icon: ShieldCheck },
    { id: 'notification', label: '알림설정', icon: Bell },
  ];

  const handleSave = () => {
    alert('설정이 저장되었습니다.');
  };

  return (
    <div className="space-y-6">
      <PageHeader icon={Settings} title="시스템설정" />

      <div className="flex gap-6">
        {/* 탭 메뉴 */}
        <div className="w-48 space-y-1">
          {tabs.map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`w-full flex items-center gap-2 px-4 py-3 rounded-lg text-left transition-colors ${activeTab === tab.id ? 'bg-gray-900 text-white' : 'text-gray-600 hover:bg-gray-100'
                }`}
            >
              <tab.icon className="w-5 h-5" />
              {tab.label}
            </button>
          ))}
        </div>

        {/* 설정 내용 */}
        <Card className="flex-1">
          {activeTab === 'general' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold">회사 기본정보</h3>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">회사명</label>
                  <input type="text" value={settings.companyName}
                    onChange={e => setSettings(prev => ({ ...prev, companyName: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">사업자번호</label>
                  <input type="text" value={settings.businessNo}
                    onChange={e => setSettings(prev => ({ ...prev, businessNo: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">대표자</label>
                  <input type="text" value={settings.ceo}
                    onChange={e => setSettings(prev => ({ ...prev, ceo: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">대표전화</label>
                  <input type="text" value={settings.phone}
                    onChange={e => setSettings(prev => ({ ...prev, phone: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg" />
                </div>
                <div className="col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-1">주소</label>
                  <input type="text" value={settings.address}
                    onChange={e => setSettings(prev => ({ ...prev, address: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">이메일</label>
                  <input type="email" value={settings.email}
                    onChange={e => setSettings(prev => ({ ...prev, email: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">팩스</label>
                  <input type="text" value={settings.fax}
                    onChange={e => setSettings(prev => ({ ...prev, fax: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg" />
                </div>
              </div>
            </div>
          )}

          {activeTab === 'number' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold">번호 생성 규칙</h3>
              <div className="space-y-4">
                <div className="p-4 bg-gray-50 rounded-lg">
                  <h4 className="font-medium mb-3">수주번호 형식</h4>
                  <div className="grid grid-cols-3 gap-4">
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">접두어</label>
                      <input type="text" value={settings.orderPrefix} readOnly
                        className="w-full px-3 py-2 border rounded-lg bg-white" />
                    </div>
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">형식</label>
                      <input type="text" value="KD-[모델]-YYMMDD-##" readOnly
                        className="w-full px-3 py-2 border rounded-lg bg-white" />
                    </div>
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">예시</label>
                      <input type="text" value="KD-TS-251209-01" readOnly
                        className="w-full px-3 py-2 border rounded-lg bg-gray-100" />
                    </div>
                  </div>
                </div>
                <div className="p-4 bg-gray-50 rounded-lg">
                  <h4 className="font-medium mb-3">검사 LOT 형식</h4>
                  <div className="space-y-2 text-sm">
                    <div className="flex justify-between"><span>입고검사:</span><span className="font-mono">YYMMDD-##</span></div>
                    <div className="flex justify-between"><span>중간검사:</span><span className="font-mono">KD-WE-YYMMDD-##-(공정)</span></div>
                    <div className="flex justify-between"><span>제품검사:</span><span className="font-mono">KD-SA-YYMMDD-##</span></div>
                    <div className="flex justify-between"><span>검사LOT:</span><span className="font-mono">KD-QC-YYMMDD-##</span></div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'security' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold">보안 설정</h3>
              <div className="space-y-4">
                <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <div className="font-medium">세션 타임아웃</div>
                    <div className="text-sm text-gray-500">미사용 시 자동 로그아웃 시간</div>
                  </div>
                  <div className="flex items-center gap-2">
                    <input type="number" value={settings.sessionTimeout}
                      onChange={e => setSettings(prev => ({ ...prev, sessionTimeout: parseInt(e.target.value) }))}
                      className="w-20 px-3 py-2 border rounded-lg text-right" />
                    <span className="text-gray-600">분</span>
                  </div>
                </div>
                <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <div className="font-medium">로그인 시도 제한</div>
                    <div className="text-sm text-gray-500">연속 로그인 실패 시 계정 잠금</div>
                  </div>
                  <div className="flex items-center gap-2">
                    <input type="number" value={settings.maxLoginAttempts}
                      onChange={e => setSettings(prev => ({ ...prev, maxLoginAttempts: parseInt(e.target.value) }))}
                      className="w-20 px-3 py-2 border rounded-lg text-right" />
                    <span className="text-gray-600">회</span>
                  </div>
                </div>
                <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <div className="font-medium">비밀번호 유효기간</div>
                    <div className="text-sm text-gray-500">비밀번호 변경 주기</div>
                  </div>
                  <div className="flex items-center gap-2">
                    <input type="number" value={settings.passwordExpireDays}
                      onChange={e => setSettings(prev => ({ ...prev, passwordExpireDays: parseInt(e.target.value) }))}
                      className="w-20 px-3 py-2 border rounded-lg text-right" />
                    <span className="text-gray-600">일</span>
                  </div>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'notification' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold">알림 설정</h3>
              <div className="space-y-4">
                <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <div className="font-medium">이메일 알림</div>
                    <div className="text-sm text-gray-500">중요 이벤트 이메일 알림</div>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" checked={settings.emailNotification}
                      onChange={e => setSettings(prev => ({ ...prev, emailNotification: e.target.checked }))}
                      className="sr-only peer" />
                    <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-500"></div>
                  </label>
                </div>
                <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <div className="font-medium">연체 알림</div>
                    <div className="text-sm text-gray-500">미수금 연체 발생 시 알림</div>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" checked={settings.overdueAlert}
                      onChange={e => setSettings(prev => ({ ...prev, overdueAlert: e.target.checked }))}
                      className="sr-only peer" />
                    <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-500"></div>
                  </label>
                </div>
                <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <div className="font-medium">재고 알림</div>
                    <div className="text-sm text-gray-500">안전재고 미달 시 알림</div>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" checked={settings.stockAlert}
                      onChange={e => setSettings(prev => ({ ...prev, stockAlert: e.target.checked }))}
                      className="sr-only peer" />
                    <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-500"></div>
                  </label>
                </div>
              </div>
            </div>
          )}

          <div className="flex justify-end gap-2 pt-6 mt-6 border-t">
            <Button variant="outline">초기화</Button>
            <Button variant="primary" onClick={handleSave}>저장</Button>
          </div>
        </Card>
      </div>
    </div>
  );
};

// 거래처 목록
const CustomerList = ({ customers = initialCustomers, onNavigate, hideAccountingInfo = false }) => {
  const [customerList, setCustomerList] = useState(customers);
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  const tabs = [
    { id: 'all', label: '전체', count: customerList.length },
    { id: 'sales', label: '매출', count: customerList.filter(c => c.customerType === '매출').length },
    { id: 'purchase', label: '매입', count: customerList.filter(c => c.customerType === '매입').length },
    { id: 'both', label: '매입매출', count: customerList.filter(c => c.customerType === '매입매출').length },
    { id: 'active', label: '활성', count: customerList.filter(c => c.isActive !== false).length },
    { id: 'inactive', label: '비활성', count: customerList.filter(c => c.isActive === false).length },
  ];

  const filtered = customerList
    .filter(c => activeTab === 'all' ||
      (activeTab === 'sales' && c.customerType === '매출') ||
      (activeTab === 'purchase' && c.customerType === '매입') ||
      (activeTab === 'both' && c.customerType === '매입매출') ||
      (activeTab === 'active' && c.isActive !== false) ||
      (activeTab === 'inactive' && c.isActive === false))
    .filter(c =>
      c.customerCode.toLowerCase().includes(search.toLowerCase()) ||
      c.customerName.includes(search) ||
      c.ceo?.includes(search) ||
      c.businessNo?.includes(search)
    )
    .sort((a, b) => b.id - a.id); // ID 기준 내림차순 (최신 등록 최상단)

  // 목록 선택 훅
  const {
    selectedIds,
    handleSelect,
    handleSelectAll,
    clearSelection,
    isAllSelected,
    hasSelection,
    isMultiSelect,
    isSelected,
  } = useListSelection(filtered);

  // 삭제 핸들러
  const handleDelete = (customer) => {
    if (window.confirm(`'${customer.customerName}' 거래처를 삭제하시겠습니까?`)) {
      setCustomerList(prev => prev.filter(c => c.id !== customer.id));
    }
  };

  const handleBulkDelete = () => {
    setCustomerList(prev => prev.filter(c => !selectedIds.includes(c.id)));
    clearSelection();
    setShowDeleteModal(false);
  };

  // 통계
  const totalReceivables = customerList.reduce((sum, c) => sum + (c.receivables?.total || 0), 0);
  const overdueReceivables = customerList.reduce((sum, c) => sum + (c.receivables?.overdue || 0), 0);
  const gradeACount = customerList.filter(c => c.creditGrade === 'A').length;
  const gradeCCount = customerList.filter(c => c.creditGrade === 'C').length;

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Users}
        title="거래처 목록"
        actions={
          <Button variant="primary" onClick={() => onNavigate('customer-register')}>
            <Plus className="w-4 h-4" /> 거래처 등록
          </Button>
        }
      />

      {/* 대시보드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <DashboardCard icon={Users} title="전체 거래처" value={`${customers.length}개`} color="blue" />
        {!hideAccountingInfo && (
          <>
            <DashboardCard icon={DollarSign} title="총 미수금" value={`${totalReceivables.toLocaleString()}원`} color="yellow" />
            <DashboardCard icon={AlertCircle} title="연체 미수금" value={`${overdueReceivables.toLocaleString()}원`} color="red" />
            <DashboardCard icon={CheckCircle} title="A등급 거래처" value={`${gradeACount}개`} color="green" />
          </>
        )}
        {hideAccountingInfo && (
          <>
            <DashboardCard icon={TrendingUp} title="매출처" value={`${customers.filter(c => c.customerType === '매출').length}개`} color="green" />
            <DashboardCard icon={ShoppingCart} title="매입처" value={`${customers.filter(c => c.customerType === '매입').length}개`} color="orange" />
            <DashboardCard icon={CheckCircle} title="활성 거래처" value={`${customers.filter(c => c.isActive !== false).length}개`} color="purple" />
          </>
        )}
      </div>

      <SearchInput placeholder="거래처코드, 거래처명, 대표자명, 사업자번호 검색..." value={search} onChange={setSearch} />
      <TabFilter tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />

      {/* 선택 삭제 버튼 (2개 이상 선택 시) */}
      {isMultiSelect && (
        <div className="flex justify-end">
          <Button variant="danger" size="sm" onClick={() => setShowDeleteModal(true)}>
            <Trash2 className="w-4 h-4" /> 선택 삭제 ({selectedIds.length})
          </Button>
        </div>
      )}

      {/* 테이블 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-center w-10">
                <input
                  type="checkbox"
                  checked={isAllSelected}
                  onChange={handleSelectAll}
                  className="w-4 h-4 rounded border-gray-300"
                />
              </th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">번호</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">거래처코드</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">거래처명</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">구분</th>
              <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">대표자</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">사업자번호</th>
              {!hideAccountingInfo && <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">신용등급</th>}
              {!hideAccountingInfo && <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">미수금</th>}
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">연락처</th>
              {hasSelection && <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>}
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map((customer, idx) => (
              <tr key={customer.id} className={`hover:bg-gray-50 cursor-pointer ${isSelected(customer.id) ? 'bg-blue-50' : ''}`} onClick={() => onNavigate('customer-detail', customer)}>
                <td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                  <input
                    type="checkbox"
                    checked={isSelected(customer.id)}
                    onChange={() => handleSelect(customer.id)}
                    className="w-4 h-4 rounded border-gray-300"
                  />
                </td>
                <td className="px-4 py-3 text-sm text-gray-500">{filtered.length - idx}</td>
                <td className="px-4 py-3 text-sm font-mono text-blue-600">{customer.customerCode}</td>
                <td className="px-4 py-3 text-sm font-medium text-gray-900">{customer.customerName}</td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-0.5 rounded text-xs ${customer.customerType === '매출' ? 'bg-blue-100 text-blue-700' :
                      customer.customerType === '매입' ? 'bg-orange-100 text-orange-700' :
                        'bg-green-100 text-green-700'
                    }`}>
                    {customer.customerType}
                  </span>
                </td>
                <td className="px-4 py-3 text-center">
                  <span className={`px-2 py-0.5 rounded text-xs ${customer.isActive !== false ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
                    }`}>
                    {customer.isActive !== false ? '활성' : '비활성'}
                  </span>
                </td>
                <td className="px-4 py-3 text-sm text-gray-900">{customer.ceo}</td>
                <td className="px-4 py-3 text-sm font-mono text-gray-600">{customer.businessNo}</td>
                {!hideAccountingInfo && <td className="px-4 py-3"><CreditGradeBadge grade={customer.creditGrade} /></td>}
                {!hideAccountingInfo && (
                  <td className="px-4 py-3 text-right">
                    <div className="text-sm font-medium text-gray-900">{(customer.receivables?.total / 10000 || 0).toLocaleString()}만원</div>
                    {customer.receivables?.overdue > 0 && (
                      <div className="text-xs text-red-500">연체 {(customer.receivables.overdue / 10000).toLocaleString()}만원</div>
                    )}
                  </td>
                )}
                <td className="px-4 py-3 text-sm text-gray-600">{customer.phone}</td>
                {hasSelection && isSelected(customer.id) && (
                  <td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                    <div className="flex items-center justify-center gap-1">
                      <button
                        onClick={() => onNavigate('customer-edit', customer)}
                        className="p-1.5 text-gray-500 hover:text-green-600 hover:bg-green-50 rounded"
                        title="수정"
                      >
                        <Edit className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => handleDelete(customer)}
                        className="p-1.5 text-gray-500 hover:text-red-600 hover:bg-red-50 rounded"
                        title="삭제"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                )}
                {hasSelection && !isSelected(customer.id) && <td className="px-4 py-3"></td>}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-md w-full mx-4">
            <h3 className="text-lg font-bold mb-4">거래처 삭제</h3>
            <p className="text-gray-600 mb-6">선택한 {selectedIds.length}개 거래처를 삭제하시겠습니까?</p>
            <div className="flex justify-end gap-2">
              <Button variant="ghost" onClick={() => setShowDeleteModal(false)}>취소</Button>
              <Button variant="danger" onClick={handleBulkDelete}>삭제</Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 거래처 상세 페이지 - 섹션 기반 (탭 제거)
const CustomerDetail = ({ customer, onNavigate, hideAccountingInfo = false }) => {
  if (!customer) {
    return (
      <div className="p-8 text-center text-gray-500">
        <Users className="w-12 h-12 mx-auto mb-4 text-gray-300" />
        <p>거래처 정보를 찾을 수 없습니다.</p>
        <Button variant="outline" className="mt-4" onClick={() => onNavigate('customer-list')}>목록으로</Button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <PageHeader icon={Users} title="거래처 상세" actions={
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => onNavigate('customer-list')}><ArrowLeft className="w-4 h-4" /> 목록</Button>
          <Button variant="primary" onClick={() => onNavigate('customer-edit', customer)}><Edit className="w-4 h-4" /> 수정</Button>
        </div>
      } />

      {/* 거래처 요약 정보 */}
      <div className="bg-blue-50 rounded-xl p-5 border border-blue-100">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <Building className="w-6 h-6 text-blue-600" />
            <div>
              <h3 className="font-bold text-blue-900 text-lg">{customer.customerName}</h3>
              <p className="text-sm text-blue-600">{customer.customerCode}</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            {!hideAccountingInfo && <CreditGradeBadge grade={customer.creditGrade} />}
            <span className={`px-2 py-1 rounded text-xs ${customer.customerType === '매출' ? 'bg-blue-100 text-blue-700' :
                customer.customerType === '매입' ? 'bg-orange-100 text-orange-700' :
                  'bg-green-100 text-green-700'
              }`}>{customer.customerType}</span>
          </div>
        </div>
        <div className={`grid ${hideAccountingInfo ? 'grid-cols-2' : 'grid-cols-3'} gap-4 text-sm`}>
          <div><span className="text-gray-500">대표자</span><p className="font-medium">{customer.ceo || customer.ceoName || '-'}</p></div>
          <div><span className="text-gray-500">사업자번호</span><p className="font-medium font-mono">{customer.businessNo || '-'}</p></div>
          {!hideAccountingInfo && <div><span className="text-gray-500">결제조건</span><p className="font-medium">{customer.paymentTerms || customer.paymentTerm || '-'}</p></div>}
        </div>
      </div>

      {/* 기본정보 섹션 */}
      <Card title="기본정보">
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="bg-gray-50 rounded-lg p-4">
              <h4 className="text-sm font-medium text-gray-500 mb-2">사업자 정보</h4>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between"><span className="text-gray-500">업태</span><span>{customer.businessType || '-'}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">종목</span><span>{customer.businessItem || '-'}</span></div>
                {!hideAccountingInfo && <div className="flex justify-between"><span className="text-gray-500">결제방법</span><span>{customer.paymentMethod || '-'}</span></div>}
              </div>
            </div>
            <div className="bg-gray-50 rounded-lg p-4">
              <h4 className="text-sm font-medium text-gray-500 mb-2">연락처 정보</h4>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between"><span className="text-gray-500">전화</span><span>{customer.phone || '-'}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">팩스</span><span>{customer.fax || '-'}</span></div>
                <div className="flex justify-between"><span className="text-gray-500">이메일</span><span>{customer.email || '-'}</span></div>
              </div>
            </div>
          </div>
          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="text-sm font-medium text-gray-500 mb-2">주소</h4>
            <p className="text-sm">{customer.address || '-'} {customer.addressDetail || ''}</p>
          </div>
          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="text-sm font-medium text-gray-500 mb-2">담당자 목록</h4>
            <div className="space-y-2">
              {(customer.contacts || []).length > 0 ? (customer.contacts || []).map(contact => (
                <div key={contact.id} className="flex items-center justify-between text-sm p-2 bg-white rounded border">
                  <div className="flex items-center gap-2">
                    <span className="font-medium">{contact.name}</span>
                    <span className="text-gray-500">{contact.position}</span>
                    {contact.isPrimary && <span className="px-1.5 py-0.5 bg-blue-100 text-blue-700 text-xs rounded">주담당</span>}
                  </div>
                  <div className="flex items-center gap-4 text-gray-600"><span>{contact.phone}</span><span>{contact.email}</span></div>
                </div>
              )) : <p className="text-sm text-gray-400">등록된 담당자가 없습니다.</p>}
            </div>
          </div>
          {!hideAccountingInfo && customer.creditNote && (
            <div className="bg-yellow-50 rounded-lg p-4 border border-yellow-200">
              <h4 className="text-sm font-medium text-yellow-700 mb-2">신용 메모</h4>
              <p className="text-sm text-yellow-800">{customer.creditNote}</p>
            </div>
          )}
        </div>
      </Card>

      {/* 거래내역 섹션 (회계정보 표시 시) */}
      {!hideAccountingInfo && (
        <Card title="거래내역">
          <div className="bg-white rounded-lg border">
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-2 text-left text-xs text-gray-500">일자</th>
                  <th className="px-4 py-2 text-left text-xs text-gray-500">구분</th>
                  <th className="px-4 py-2 text-right text-xs text-gray-500">금액</th>
                  <th className="px-4 py-2 text-right text-xs text-gray-500">잔액</th>
                  <th className="px-4 py-2 text-left text-xs text-gray-500">비고</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {(customer.transactions || []).length > 0 ? (customer.transactions || []).map((tx, idx) => (
                  <tr key={idx} className="hover:bg-gray-50">
                    <td className="px-4 py-2">{tx.date || '-'}</td>
                    <td className="px-4 py-2"><span className={`px-2 py-0.5 rounded text-xs ${tx.type === '입금' ? 'bg-green-100 text-green-700' : 'bg-blue-100 text-blue-700'}`}>{tx.type}</span></td>
                    <td className="px-4 py-2 text-right font-medium">{(tx.amount || 0).toLocaleString()}원</td>
                    <td className="px-4 py-2 text-right">{(tx.balance || 0).toLocaleString()}원</td>
                    <td className="px-4 py-2 text-gray-600">{tx.note || '-'}</td>
                  </tr>
                )) : (
                  <tr><td colSpan="5" className="px-4 py-8 text-center text-gray-400">거래내역이 없습니다.</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {/* 미수금현황 섹션 (회계정보 표시 시) */}
      {!hideAccountingInfo && (
        <Card title="미수금현황">
          <div className="grid grid-cols-3 gap-4">
            <div className="bg-blue-50 rounded-lg p-4 text-center">
              <p className="text-sm text-gray-500">총 미수금</p>
              <p className="text-2xl font-bold text-blue-600">{(customer.receivables?.total || 0).toLocaleString()}원</p>
            </div>
            <div className="bg-red-50 rounded-lg p-4 text-center">
              <p className="text-sm text-gray-500">연체 미수금</p>
              <p className="text-2xl font-bold text-red-600">{(customer.receivables?.overdue || 0).toLocaleString()}원</p>
            </div>
            <div className="bg-yellow-50 rounded-lg p-4 text-center">
              <p className="text-sm text-gray-500">연체 일수</p>
              <p className="text-2xl font-bold text-yellow-600">{customer.receivables?.overdueDays || 0}일</p>
            </div>
          </div>
        </Card>
      )}

      {/* 변경이력 섹션 */}
      <Card title="변경이력">
        <div className="text-sm text-gray-500 text-center py-8">변경이력이 없습니다.</div>
      </Card>
    </div>
  );
};

// 거래처 등록/수정 페이지
const CustomerRegister = ({ customer, onNavigate, isEdit = false, hideAccountingInfo = false }) => {
  const [formData, setFormData] = useState(customer || {
    customerType: '매출', creditGrade: 'B', paymentMethod: '계좌이체', customerCode: '', customerName: '', ceo: '',
    businessNo: '', businessType: '', businessItem: '', phone: '', fax: '', email: '', address: '', addressDetail: '',
    paymentTerms: '', creditLimit: 0, creditNote: '', contacts: [],
  });

  // 유효성 검사 규칙
  const validationRules = {
    customerType: { required: true, label: '거래처구분', message: '거래처구분을 선택해주세요.' },
    customerName: { required: true, label: '거래처명', message: '거래처명을 입력해주세요.' },
  };

  const { errors, hasError, getFieldError, validateForm, clearFieldError } = useFormValidation(formData, validationRules);

  const handleChange = (field, value) => {
    setFormData({ ...formData, [field]: value });
    clearFieldError(field);
  };

  const handleSave = () => {
    if (!validateForm()) {
      // 첫 번째 에러 필드로 스크롤
      const firstErrorField = Object.keys(errors).find(key => errors[key]);
      if (firstErrorField) {
        const errorElement = document.querySelector(`[data-field="${firstErrorField}"]`);
        errorElement?.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
      return;
    }
    alert(isEdit ? '거래처가 수정되었습니다.' : '거래처가 등록되었습니다.');
    onNavigate('customer-list');
  };

  return (
    <div className="space-y-6">
      <PageHeader icon={Users} title={isEdit ? '거래처 수정' : '거래처 등록'} actions={
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => onNavigate('customer-list')}><X className="w-4 h-4" /> 취소</Button>
          <Button variant="primary" onClick={handleSave}><Check className="w-4 h-4" /> {isEdit ? '수정' : '등록'}</Button>
        </div>
      } />
      <Card title="기본 정보">
        <div className="grid grid-cols-2 gap-4">
          <FormField label="거래처구분" required error={hasError('customerType')} errorMessage={getFieldError('customerType')}>
            <select data-field="customerType" value={formData.customerType} onChange={(e) => handleChange('customerType', e.target.value)} className={getInputClassName(hasError('customerType'))}>
              <option value="">선택하세요</option>
              <option value="고객사">고객사</option><option value="공급업체">공급업체</option>
            </select>
          </FormField>
          <FormField label="거래처코드"><input type="text" value={formData.customerCode} placeholder="자동생성" className="w-full px-3 py-2 border rounded-lg bg-gray-50" disabled /></FormField>
          <FormField label="거래처명" required error={hasError('customerName')} errorMessage={getFieldError('customerName')}>
            <input data-field="customerName" type="text" value={formData.customerName} onChange={(e) => handleChange('customerName', e.target.value)} placeholder="거래처명 입력" className={getInputClassName(hasError('customerName'))} />
          </FormField>
          <FormField label="대표자"><input type="text" value={formData.ceo} onChange={(e) => setFormData({ ...formData, ceo: e.target.value })} placeholder="대표자명" className="w-full px-3 py-2 border rounded-lg" /></FormField>
          <FormField label="사업자번호"><input type="text" value={formData.businessNo} onChange={(e) => setFormData({ ...formData, businessNo: e.target.value })} placeholder="000-00-00000" className="w-full px-3 py-2 border rounded-lg" /></FormField>
          <FormField label="업태"><input type="text" value={formData.businessType} onChange={(e) => setFormData({ ...formData, businessType: e.target.value })} placeholder="업태" className="w-full px-3 py-2 border rounded-lg" /></FormField>
          <FormField label="종목"><input type="text" value={formData.businessItem} onChange={(e) => setFormData({ ...formData, businessItem: e.target.value })} placeholder="종목" className="w-full px-3 py-2 border rounded-lg" /></FormField>
        </div>
      </Card>
      <Card title="연락처 정보">
        <div className="grid grid-cols-2 gap-4">
          <FormField label="전화번호"><input type="text" value={formData.phone} onChange={(e) => setFormData({ ...formData, phone: e.target.value })} placeholder="000-0000-0000" className="w-full px-3 py-2 border rounded-lg" /></FormField>
          <FormField label="팩스번호"><input type="text" value={formData.fax} onChange={(e) => setFormData({ ...formData, fax: e.target.value })} placeholder="000-0000-0000" className="w-full px-3 py-2 border rounded-lg" /></FormField>
          <FormField label="이메일"><input type="email" value={formData.email} onChange={(e) => setFormData({ ...formData, email: e.target.value })} placeholder="example@company.com" className="w-full px-3 py-2 border rounded-lg" /></FormField>
        </div>
        <div className="mt-4">
          <FormField label="주소">
            <input type="text" value={formData.address} onChange={(e) => setFormData({ ...formData, address: e.target.value })} placeholder="주소" className="w-full px-3 py-2 border rounded-lg mb-2" />
            <input type="text" value={formData.addressDetail} onChange={(e) => setFormData({ ...formData, addressDetail: e.target.value })} placeholder="상세주소" className="w-full px-3 py-2 border rounded-lg" />
          </FormField>
        </div>
      </Card>
      {!hideAccountingInfo && (
        <Card title="신용/결제 정보">
          <div className="grid grid-cols-2 gap-4">
            <FormField label="신용등급">
              <select value={formData.creditGrade} onChange={(e) => setFormData({ ...formData, creditGrade: e.target.value })} className="w-full px-3 py-2 border rounded-lg">
                <option value="A">A등급 (우량)</option><option value="B">B등급 (일반)</option><option value="C">C등급 (관리)</option>
              </select>
            </FormField>
            <FormField label="결제방법">
              <select value={formData.paymentMethod} onChange={(e) => setFormData({ ...formData, paymentMethod: e.target.value })} className="w-full px-3 py-2 border rounded-lg">
                <option value="계좌이체">계좌이체</option><option value="현금">현금</option><option value="어음">어음</option><option value="카드">카드</option>
              </select>
            </FormField>
            <FormField label="결제조건"><input type="text" value={formData.paymentTerms} onChange={(e) => setFormData({ ...formData, paymentTerms: e.target.value })} placeholder="예: 월말 익월 15일" className="w-full px-3 py-2 border rounded-lg" /></FormField>
            <FormField label="신용한도"><input type="number" value={formData.creditLimit} onChange={(e) => setFormData({ ...formData, creditLimit: parseInt(e.target.value) || 0 })} placeholder="0" className="w-full px-3 py-2 border rounded-lg" /></FormField>
          </div>
          <div className="mt-4">
            <FormField label="신용 메모"><textarea value={formData.creditNote} onChange={(e) => setFormData({ ...formData, creditNote: e.target.value })} placeholder="신용 관련 메모" rows={3} className="w-full px-3 py-2 border rounded-lg" /></FormField>
          </div>
        </Card>
      )}
    </div>
  );
};

// 거래처 상세 패널 (레거시 - 호환용) - 섹션 기반 (탭 제거)
const CustomerDetailPanel = ({ customer, onEdit, onClose, hideAccountingInfo = false }) => {
  return (
    <div className="h-full flex flex-col">
      <div className="flex-1 overflow-y-auto p-6 space-y-6">
        {/* 기본 정보 요약 */}
        <div className="bg-blue-50 rounded-xl p-5 border border-blue-100">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <Building className="w-6 h-6 text-blue-600" />
              <div>
                <h3 className="font-bold text-blue-900 text-lg">{customer.customerName}</h3>
                <p className="text-sm text-blue-600">{customer.customerCode}</p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              {!hideAccountingInfo && <CreditGradeBadge grade={customer.creditGrade} />}
              <span className={`px-2 py-1 rounded text-xs ${customer.customerType === '고객사' ? 'bg-blue-100 text-blue-700' : 'bg-purple-100 text-purple-700'}`}>
                {customer.customerType}
              </span>
            </div>
          </div>
          <div className={`grid ${hideAccountingInfo ? 'grid-cols-2' : 'grid-cols-3'} gap-4 text-sm`}>
            <div>
              <span className="text-gray-500">대표자</span>
              <p className="font-medium">{customer.ceo}</p>
            </div>
            <div>
              <span className="text-gray-500">사업자번호</span>
              <p className="font-medium font-mono">{customer.businessNo}</p>
            </div>
            {!hideAccountingInfo && (
              <div>
                <span className="text-gray-500">결제조건</span>
                <p className="font-medium">{customer.paymentTerms}</p>
              </div>
            )}
          </div>
        </div>

        {/* 기본정보 섹션 */}
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-bold text-gray-900 mb-4">기본정보</h3>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="bg-gray-50 rounded-lg p-4">
                <h4 className="text-sm font-medium text-gray-500 mb-2">사업자 정보</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between"><span className="text-gray-500">업태</span><span>{customer.businessType || '-'}</span></div>
                  <div className="flex justify-between"><span className="text-gray-500">종목</span><span>{customer.businessItem || '-'}</span></div>
                  {!hideAccountingInfo && <div className="flex justify-between"><span className="text-gray-500">결제방법</span><span>{customer.paymentMethod || '-'}</span></div>}
                </div>
              </div>
              <div className="bg-gray-50 rounded-lg p-4">
                <h4 className="text-sm font-medium text-gray-500 mb-2">연락처 정보</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between"><span className="text-gray-500">전화</span><span>{customer.phone || '-'}</span></div>
                  <div className="flex justify-between"><span className="text-gray-500">팩스</span><span>{customer.fax || '-'}</span></div>
                  <div className="flex justify-between"><span className="text-gray-500">이메일</span><span>{customer.email || '-'}</span></div>
                </div>
              </div>
            </div>
            <div className="bg-gray-50 rounded-lg p-4">
              <h4 className="text-sm font-medium text-gray-500 mb-2">주소</h4>
              <p className="text-sm">{customer.address || '-'} {customer.addressDetail || ''}</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-4">
              <h4 className="text-sm font-medium text-gray-500 mb-2">담당자 목록</h4>
              <div className="space-y-2">
                {(customer.contacts || []).length > 0 ? customer.contacts.map(contact => (
                  <div key={contact.id} className="flex items-center justify-between text-sm p-2 bg-white rounded border">
                    <div className="flex items-center gap-2">
                      <span className="font-medium">{contact.name}</span>
                      <span className="text-gray-500">{contact.position}</span>
                      {contact.isPrimary && <span className="px-1.5 py-0.5 bg-blue-100 text-blue-700 text-xs rounded">주담당</span>}
                    </div>
                    <div className="flex items-center gap-4 text-gray-600">
                      <span>{contact.phone}</span>
                      <span>{contact.email}</span>
                    </div>
                  </div>
                )) : <p className="text-sm text-gray-400">등록된 담당자가 없습니다.</p>}
              </div>
            </div>
            {!hideAccountingInfo && customer.creditNote && (
              <div className="bg-yellow-50 rounded-lg p-4 border border-yellow-200">
                <h4 className="text-sm font-medium text-yellow-700 mb-2">신용 메모</h4>
                <p className="text-sm text-yellow-800">{customer.creditNote}</p>
              </div>
            )}
          </div>
        </div>

        {/* 거래내역 섹션 (회계정보 표시 시) */}
        {!hideAccountingInfo && (
          <div className="bg-white rounded-xl border p-5">
            <h3 className="font-bold text-gray-900 mb-4">거래내역</h3>
            <div className="bg-white rounded-lg border">
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-2 text-left text-xs text-gray-500">일자</th>
                    <th className="px-4 py-2 text-left text-xs text-gray-500">구분</th>
                    <th className="px-4 py-2 text-right text-xs text-gray-500">금액</th>
                    <th className="px-4 py-2 text-right text-xs text-gray-500">잔액</th>
                    <th className="px-4 py-2 text-left text-xs text-gray-500">비고</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {(customer.transactions || []).length > 0 ? customer.transactions.map((tx, idx) => (
                    <tr key={idx} className="hover:bg-gray-50">
                      <td className="px-4 py-2">{tx.date}</td>
                      <td className="px-4 py-2">
                        <span className={`px-2 py-0.5 rounded text-xs ${tx.type === '입금' ? 'bg-green-100 text-green-700' : 'bg-blue-100 text-blue-700'}`}>{tx.type}</span>
                      </td>
                      <td className="px-4 py-2 text-right font-medium">{(tx.amount || 0).toLocaleString()}원</td>
                      <td className="px-4 py-2 text-right">{(tx.balance || 0).toLocaleString()}원</td>
                      <td className="px-4 py-2 text-gray-600">{tx.note || '-'}</td>
                    </tr>
                  )) : (
                    <tr><td colSpan="5" className="px-4 py-8 text-center text-gray-400">거래내역이 없습니다.</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* 미수금현황 섹션 (회계정보 표시 시) */}
        {!hideAccountingInfo && (
          <div className="bg-white rounded-xl border p-5">
            <h3 className="font-bold text-gray-900 mb-4">미수금현황</h3>
            <div className="grid grid-cols-3 gap-4">
              <div className="bg-blue-50 rounded-lg p-4 text-center">
                <p className="text-sm text-gray-500">총 미수금</p>
                <p className="text-2xl font-bold text-blue-600">{(customer.receivables?.total || 0).toLocaleString()}원</p>
              </div>
              <div className="bg-red-50 rounded-lg p-4 text-center">
                <p className="text-sm text-gray-500">연체 미수금</p>
                <p className="text-2xl font-bold text-red-600">{(customer.receivables?.overdue || 0).toLocaleString()}원</p>
              </div>
              <div className="bg-yellow-50 rounded-lg p-4 text-center">
                <p className="text-sm text-gray-500">연체 일수</p>
                <p className="text-2xl font-bold text-yellow-600">{customer.receivables?.overdueDays || 0}일</p>
              </div>
            </div>
          </div>
        )}

        {/* 변경이력 섹션 */}
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-bold text-gray-900 mb-4">변경이력</h3>
          <div className="text-sm text-gray-500 text-center py-8">
            변경이력이 없습니다.
          </div>
        </div>
      </div>

      {/* 하단 버튼 */}
      <div className="p-4 border-t bg-white flex gap-3">
        <Button variant="secondary" className="flex-1" onClick={onClose}>닫기</Button>
        <Button variant="primary" className="flex-1" onClick={onEdit}>
          <Edit className="w-4 h-4" /> 수정
        </Button>
      </div>
    </div>
  );
};

// 거래처 폼 패널
const CustomerFormPanel = ({ formData, setFormData, onSave, onCancel, isEdit, hideAccountingInfo = false }) => {
  return (
    <div className="h-full flex flex-col">
      <div className="flex-1 overflow-y-auto p-6 space-y-6">
        {/* 기본정보 */}
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-bold text-gray-900 mb-4">기본 정보</h3>
          <div className="grid grid-cols-2 gap-4">
            <FormField label="거래처구분" required>
              <select className="w-full border rounded-lg px-3 py-2 text-sm" value={formData.customerType || ''} onChange={(e) => setFormData({ ...formData, customerType: e.target.value })}>
                <option value="고객사">고객사</option>
                <option value="공급업체">공급업체</option>
                <option value="기타">기타</option>
              </select>
            </FormField>
            <FormField label="거래처명(상호)" required>
              <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="거래처명 입력" value={formData.customerName || ''} onChange={(e) => setFormData({ ...formData, customerName: e.target.value })} />
            </FormField>
            <FormField label="대표자명" required>
              <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="대표자명 입력" value={formData.ceo || ''} onChange={(e) => setFormData({ ...formData, ceo: e.target.value })} />
            </FormField>
            <FormField label="사업자등록번호" required>
              <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="000-00-00000" value={formData.businessNo || ''} onChange={(e) => setFormData({ ...formData, businessNo: e.target.value })} />
            </FormField>
            <FormField label="업태">
              <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="업태 입력" value={formData.businessType || ''} onChange={(e) => setFormData({ ...formData, businessType: e.target.value })} />
            </FormField>
            <FormField label="종목">
              <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="종목 입력" value={formData.businessItem || ''} onChange={(e) => setFormData({ ...formData, businessItem: e.target.value })} />
            </FormField>
          </div>
        </div>

        {/* 연락처 정보 */}
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-bold text-gray-900 mb-4">연락처 정보</h3>
          <div className="grid grid-cols-2 gap-4">
            <FormField label="전화번호">
              <input type="tel" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="02-0000-0000" value={formData.phone || ''} onChange={(e) => setFormData({ ...formData, phone: e.target.value })} />
            </FormField>
            <FormField label="팩스번호">
              <input type="tel" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="02-0000-0000" value={formData.fax || ''} onChange={(e) => setFormData({ ...formData, fax: e.target.value })} />
            </FormField>
            <div className="col-span-2">
              <FormField label="이메일">
                <input type="email" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="email@company.com" value={formData.email || ''} onChange={(e) => setFormData({ ...formData, email: e.target.value })} />
              </FormField>
            </div>
            <div className="col-span-2">
              <FormField label="주소">
                <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="주소 입력" value={formData.address || ''} onChange={(e) => setFormData({ ...formData, address: e.target.value })} />
              </FormField>
            </div>
            <div className="col-span-2">
              <FormField label="상세주소">
                <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="상세주소 입력" value={formData.addressDetail || ''} onChange={(e) => setFormData({ ...formData, addressDetail: e.target.value })} />
              </FormField>
            </div>
          </div>
        </div>

        {/* 신용정보 - 회계 정보 숨김 옵션 적용 */}
        {!hideAccountingInfo && (
          <div className="bg-white rounded-xl border p-5">
            <h3 className="font-bold text-gray-900 mb-4">신용 및 결제 정보</h3>
            <div className="grid grid-cols-2 gap-4">
              <FormField label="신용등급" required>
                <select className="w-full border rounded-lg px-3 py-2 text-sm" value={formData.creditGrade || ''} onChange={(e) => setFormData({ ...formData, creditGrade: e.target.value })}>
                  <option value="A">A (우량)</option>
                  <option value="B">B (관리)</option>
                  <option value="C">C (위험)</option>
                </select>
              </FormField>
              <FormField label="결제방법">
                <select className="w-full border rounded-lg px-3 py-2 text-sm" value={formData.paymentMethod || ''} onChange={(e) => setFormData({ ...formData, paymentMethod: e.target.value })}>
                  <option value="계좌이체">계좌이체</option>
                  <option value="현금">현금</option>
                  <option value="어음">어음</option>
                  <option value="카드">카드</option>
                </select>
              </FormField>
              <div className="col-span-2">
                <FormField label="결제조건">
                  <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="월말 마감 익월 10일 결제" value={formData.paymentTerms || ''} onChange={(e) => setFormData({ ...formData, paymentTerms: e.target.value })} />
                </FormField>
              </div>
              <div className="col-span-2">
                <FormField label="신용 메모">
                  <textarea className="w-full border rounded-lg px-3 py-2 text-sm resize-none" rows={2} placeholder="신용 관련 특이사항" value={formData.creditNote || ''} onChange={(e) => setFormData({ ...formData, creditNote: e.target.value })} />
                </FormField>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 하단 버튼 */}
      <div className="p-4 border-t bg-white flex gap-3">
        <Button variant="secondary" className="flex-1" onClick={onCancel}>취소</Button>
        <Button variant="primary" className="flex-1" onClick={onSave}>
          <CheckCircle className="w-4 h-4" /> {isEdit ? '수정 완료' : '등록 완료'}
        </Button>
      </div>
    </div>
  );
};

// ============ 현장 관리 ============

const SiteList = ({ sites = initialSites, onNavigate }) => {
  const [siteList, setSiteList] = useState(sites);
  const [search, setSearch] = useState('');
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  const filtered = siteList
    .filter(s =>
      s.siteCode.toLowerCase().includes(search.toLowerCase()) ||
      s.siteName.includes(search) ||
      s.customerName.includes(search)
    )
    .sort((a, b) => b.id - a.id); // ID 기준 내림차순 (최신 등록 최상단)

  // 목록 선택 훅
  const {
    selectedIds,
    handleSelect,
    handleSelectAll,
    clearSelection,
    isAllSelected,
    hasSelection,
    isMultiSelect,
    isSelected,
  } = useListSelection(filtered);

  // 삭제 핸들러
  const handleDelete = (site) => {
    if (window.confirm(`'${site.siteName}' 현장을 삭제하시겠습니까?`)) {
      setSiteList(prev => prev.filter(s => s.id !== site.id));
    }
  };

  const handleBulkDelete = () => {
    setSiteList(prev => prev.filter(s => !selectedIds.includes(s.id)));
    clearSelection();
    setShowDeleteModal(false);
  };

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Building}
        title="현장 목록"
        actions={
          <Button variant="primary" onClick={() => onNavigate('site-register')}>
            <Plus className="w-4 h-4" /> 현장 등록
          </Button>
        }
      />

      <SearchInput placeholder="현장코드, 현장명, 거래처명 검색..." value={search} onChange={setSearch} />

      {/* 선택 삭제 버튼 (2개 이상 선택 시) */}
      {isMultiSelect && (
        <div className="flex justify-end">
          <Button variant="danger" size="sm" onClick={() => setShowDeleteModal(true)}>
            <Trash2 className="w-4 h-4" /> 선택 삭제 ({selectedIds.length})
          </Button>
        </div>
      )}

      {/* 테이블 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-center w-10">
                <input
                  type="checkbox"
                  checked={isAllSelected}
                  onChange={handleSelectAll}
                  className="w-4 h-4 rounded border-gray-300"
                />
              </th>
              <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 w-12">번호</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">현장코드</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">현장명</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">거래처</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">주소</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">등록일</th>
              {hasSelection && <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>}
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map((site, index) => (
              <tr key={site.id} className={`hover:bg-gray-50 cursor-pointer ${isSelected(site.id) ? 'bg-blue-50' : ''}`} onClick={() => onNavigate('site-detail', site)}>
                <td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                  <input
                    type="checkbox"
                    checked={isSelected(site.id)}
                    onChange={() => handleSelect(site.id)}
                    className="w-4 h-4 rounded border-gray-300"
                  />
                </td>
                <td className="px-4 py-3 text-center text-sm text-gray-500">{filtered.length - index}</td>
                <td className="px-4 py-3 text-sm font-mono text-blue-600">{site.siteCode}</td>
                <td className="px-4 py-3 text-sm font-medium text-gray-900">{site.siteName}</td>
                <td className="px-4 py-3 text-sm text-gray-900">{site.customerName}</td>
                <td className="px-4 py-3 text-sm text-gray-600">{site.siteAddress}</td>
                <td className="px-4 py-3 text-sm text-gray-600">{site.registeredDate || '-'}</td>
                {hasSelection && isSelected(site.id) && (
                  <td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                    <div className="flex items-center justify-center gap-1">
                      <button
                        onClick={() => onNavigate('site-edit', site)}
                        className="p-1.5 text-gray-500 hover:text-green-600 hover:bg-green-50 rounded"
                        title="수정"
                      >
                        <Edit className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => handleDelete(site)}
                        className="p-1.5 text-gray-500 hover:text-red-600 hover:bg-red-50 rounded"
                        title="삭제"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                )}
                {hasSelection && !isSelected(site.id) && <td className="px-4 py-3"></td>}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-md w-full mx-4">
            <h3 className="text-lg font-bold mb-4">현장 삭제</h3>
            <p className="text-gray-600 mb-6">선택한 {selectedIds.length}개 현장을 삭제하시겠습니까?</p>
            <div className="flex justify-end gap-2">
              <Button variant="ghost" onClick={() => setShowDeleteModal(false)}>취소</Button>
              <Button variant="danger" onClick={handleBulkDelete}>삭제</Button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
};

// 현장 상세 패널
const SiteDetailPanel = ({ site, onEdit, onClose }) => {
  const getStatusColor = (status) => {
    const colors = {
      '설치완료': 'bg-green-100 text-green-700',
      '설치중': 'bg-blue-100 text-blue-700',
      '출하대기': 'bg-yellow-100 text-yellow-700',
      '생산중': 'bg-purple-100 text-purple-700',
    };
    return colors[status] || 'bg-gray-100 text-gray-700';
  };

  return (
    <div className="h-full flex flex-col">
      <div className="flex-1 overflow-y-auto p-6 space-y-6">
        {/* 현장 정보 요약 */}
        <div className="bg-green-50 rounded-xl p-5 border border-green-100">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <MapPin className="w-6 h-6 text-green-600" />
              <div>
                <h3 className="font-bold text-green-900 text-lg">{site.siteName}</h3>
                <p className="text-sm text-green-600">{site.siteCode}</p>
              </div>
            </div>
            <span className={`px-3 py-1 rounded text-sm font-medium ${getStatusColor(site.status)}`}>{site.status}</span>
          </div>
          <div className="grid grid-cols-3 gap-4 text-sm">
            <div>
              <span className="text-gray-500">거래처</span>
              <p className="font-medium">{site.customerName}</p>
            </div>
            <div>
              <span className="text-gray-500">설치예정일</span>
              <p className="font-medium">{site.installScheduledDate}</p>
            </div>
            <div>
              <span className="text-gray-500">진행률</span>
              <div className="flex items-center gap-2 mt-1">
                <div className="flex-1 h-2 bg-green-200 rounded-full overflow-hidden">
                  <div className="h-full bg-green-500" style={{ width: `${site.progress}%` }} />
                </div>
                <span className="font-medium">{site.progress}%</span>
              </div>
            </div>
          </div>
        </div>

        {/* 기본정보 */}
        <div className="space-y-4">
          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="text-sm font-medium text-gray-500 mb-2">현장 주소</h4>
            <p className="text-sm">{site.siteAddress}</p>
            <p className="text-sm text-gray-500 mt-1">연락처: {site.siteContact}</p>
          </div>
          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="text-sm font-medium text-gray-500 mb-2">설치 담당자</h4>
            <div className="flex items-center gap-4">
              <span className="font-medium">{site.installManager}</span>
              <span className="text-gray-600">{site.installManagerPhone}</span>
            </div>
          </div>
          {site.note && (
            <div className="bg-yellow-50 rounded-lg p-4 border border-yellow-200">
              <h4 className="text-sm font-medium text-yellow-700 mb-2">특이사항</h4>
              <p className="text-sm text-yellow-800">{site.note}</p>
            </div>
          )}
        </div>
      </div>

      <div className="p-4 border-t bg-white flex gap-3">
        <Button variant="secondary" className="flex-1" onClick={onClose}>닫기</Button>
        <Button variant="primary" className="flex-1" onClick={onEdit}>
          <Edit className="w-4 h-4" /> 수정
        </Button>
      </div>
    </div>
  );
};

// 현장 폼 패널
const SiteFormPanel = ({ formData, setFormData, onSave, onCancel, isEdit }) => {
  return (
    <div className="h-full flex flex-col">
      <div className="flex-1 overflow-y-auto p-6 space-y-6">
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-bold text-gray-900 mb-4">현장 정보</h3>
          <div className="grid grid-cols-2 gap-4">
            <FormField label="현장명" required>
              <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="현장명 입력" value={formData.siteName || ''} onChange={(e) => setFormData({ ...formData, siteName: e.target.value })} />
            </FormField>
            <FormField label="거래처" required>
              <select className="w-full border rounded-lg px-3 py-2 text-sm" value={formData.customerId || ''} onChange={(e) => setFormData({ ...formData, customerId: e.target.value })}>
                <option value="">거래처 선택</option>
                {initialCustomers.filter(c => c.customerType === '고객사').map(c => (
                  <option key={c.id} value={c.id}>{c.customerName}</option>
                ))}
              </select>
            </FormField>
            <div className="col-span-2">
              <FormField label="현장주소" required>
                <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="현장 주소 입력" value={formData.siteAddress || ''} onChange={(e) => setFormData({ ...formData, siteAddress: e.target.value })} />
              </FormField>
            </div>
            <FormField label="현장연락처">
              <input type="tel" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="02-0000-0000" value={formData.siteContact || ''} onChange={(e) => setFormData({ ...formData, siteContact: e.target.value })} />
            </FormField>
            <FormField label="진행상태">
              <select className="w-full border rounded-lg px-3 py-2 text-sm" value={formData.status || ''} onChange={(e) => setFormData({ ...formData, status: e.target.value })}>
                <option value="수주확정">수주확정</option>
                <option value="생산중">생산중</option>
                <option value="출하대기">출하대기</option>
                <option value="설치중">설치중</option>
                <option value="설치완료">설치완료</option>
              </select>
            </FormField>
          </div>
        </div>

        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-bold text-gray-900 mb-4">설치 담당자</h3>
          <div className="grid grid-cols-2 gap-4">
            <FormField label="담당자명">
              <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="설치담당자명" value={formData.installManager || ''} onChange={(e) => setFormData({ ...formData, installManager: e.target.value })} />
            </FormField>
            <FormField label="연락처">
              <input type="tel" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="010-0000-0000" value={formData.installManagerPhone || ''} onChange={(e) => setFormData({ ...formData, installManagerPhone: e.target.value })} />
            </FormField>
            <FormField label="설치예정일">
              <input type="date" className="w-full border rounded-lg px-3 py-2 text-sm" value={formData.installScheduledDate || ''} onChange={(e) => setFormData({ ...formData, installScheduledDate: e.target.value })} />
            </FormField>
            <FormField label="설치완료일">
              <input type="date" className="w-full border rounded-lg px-3 py-2 text-sm" value={formData.installCompletedDate || ''} onChange={(e) => setFormData({ ...formData, installCompletedDate: e.target.value })} />
            </FormField>
            <div className="col-span-2">
              <FormField label="특이사항">
                <textarea className="w-full border rounded-lg px-3 py-2 text-sm resize-none" rows={3} placeholder="현장 특이사항 입력" value={formData.note || ''} onChange={(e) => setFormData({ ...formData, note: e.target.value })} />
              </FormField>
            </div>
          </div>
        </div>
      </div>

      <div className="p-4 border-t bg-white flex gap-3">
        <Button variant="secondary" className="flex-1" onClick={onCancel}>취소</Button>
        <Button variant="primary" className="flex-1" onClick={onSave}>
          <CheckCircle className="w-4 h-4" /> {isEdit ? '수정 완료' : '등록 완료'}
        </Button>
      </div>
    </div>
  );
};

// 현장 상세 페이지
const SiteDetail = ({ site, onNavigate }) => {
  const getStatusColor = (status) => { const colors = { '설치완료': 'bg-green-100 text-green-700', '설치중': 'bg-blue-100 text-blue-700', '출하대기': 'bg-yellow-100 text-yellow-700', '생산중': 'bg-purple-100 text-purple-700' }; return colors[status] || 'bg-gray-100 text-gray-700'; };

  // site가 없을 때 에러 처리
  if (!site) {
    return (
      <div className="space-y-6">
        <PageHeader icon={Building} title="현장 상세" actions={<Button variant="secondary" onClick={() => onNavigate('site')}><ArrowLeft className="w-4 h-4" /> 목록으로</Button>} />
        <div className="bg-white rounded-xl border p-8 text-center">
          <AlertCircle className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">현장 정보를 찾을 수 없습니다</h3>
          <p className="text-gray-500 mb-4">요청하신 현장 정보가 존재하지 않거나 삭제되었습니다.</p>
          <Button variant="primary" onClick={() => onNavigate('site')}>목록으로 돌아가기</Button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 상단 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
          <Building className="w-6 h-6 text-blue-500" />
          현장 상세
        </h1>
        <div className="flex items-center justify-end gap-2">
          <Button variant="outline" size="sm" onClick={() => onNavigate('site')}><List className="w-4 h-4" /> 목록</Button>
          <Button variant="primary" size="sm" onClick={() => onNavigate('site-edit', site)}><Edit className="w-4 h-4" /> 수정</Button>
        </div>
      </div>
      {/* 기본정보 섹션 */}
      <Card title="기본정보">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4">
          <div>
            <p className="text-sm text-gray-500 mb-1">현장코드</p>
            <p className="font-mono font-medium">{site.siteCode}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">현장명</p>
            <p className="font-medium">{site.siteName}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">진행상태</p>
            <span className={`px-2 py-1 rounded text-xs font-medium ${getStatusColor(site.status)}`}>{site.status}</span>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">거래처</p>
            <p className="font-medium">{site.customerName}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">설치예정일</p>
            <p className="font-medium">{site.installScheduledDate || '-'}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">진행률</p>
            <div className="flex items-center gap-2">
              <div className="flex-1 h-2 bg-gray-200 rounded-full overflow-hidden">
                <div className="h-full bg-blue-500" style={{ width: `${site.progress}%` }} />
              </div>
              <span className="font-medium text-sm">{site.progress}%</span>
            </div>
          </div>
          <div className="md:col-span-2 lg:col-span-3">
            <p className="text-sm text-gray-500 mb-1">현장주소</p>
            <p className="font-medium">{site.siteAddress}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">현장연락처</p>
            <p className="font-medium">{site.siteContact || '-'}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">설치담당자</p>
            <p className="font-medium">{site.installManager || '-'}</p>
          </div>
          <div>
            <p className="text-sm text-gray-500 mb-1">담당자 연락처</p>
            <p className="font-medium">{site.installManagerPhone || '-'}</p>
          </div>
          {site.note && (
            <div className="md:col-span-2 lg:col-span-3">
              <p className="text-sm text-gray-500 mb-1">특이사항</p>
              <p className="font-medium text-yellow-700">{site.note}</p>
            </div>
          )}
        </div>
      </Card>
      {/* 수주내역 섹션 */}
      <Card title="수주내역"><div className="bg-white rounded-lg border"><table className="w-full text-sm"><thead className="bg-gray-50"><tr><th className="px-4 py-2 text-left text-xs text-gray-500">수주번호</th><th className="px-4 py-2 text-left text-xs text-gray-500">제품</th><th className="px-4 py-2 text-right text-xs text-gray-500">수량</th><th className="px-4 py-2 text-right text-xs text-gray-500">금액</th></tr></thead><tbody className="divide-y">{site.orders?.length > 0 ? site.orders.map((order, idx) => (<tr key={idx} className="hover:bg-gray-50"><td className="px-4 py-2 font-mono text-blue-600">{order.orderNo}</td><td className="px-4 py-2">{order.product}</td><td className="px-4 py-2 text-right">{order.qty}EA</td><td className="px-4 py-2 text-right font-medium">{order.amount.toLocaleString()}원</td></tr>)) : (<tr><td colSpan={4} className="text-center py-8 text-gray-500">수주 내역이 없습니다.</td></tr>)}</tbody></table></div></Card>
      {/* 출고내역 섹션 */}
      <Card title="출고내역"><div className="bg-white rounded-lg border"><table className="w-full text-sm"><thead className="bg-gray-50"><tr><th className="px-4 py-2 text-left text-xs text-gray-500">출하번호</th><th className="px-4 py-2 text-left text-xs text-gray-500">출하일</th><th className="px-4 py-2 text-right text-xs text-gray-500">수량</th><th className="px-4 py-2 text-left text-xs text-gray-500">상태</th></tr></thead><tbody className="divide-y">{site.shipments?.length > 0 ? site.shipments.map((ship, idx) => (<tr key={idx} className="hover:bg-gray-50"><td className="px-4 py-2 font-mono text-blue-600">{ship.shipmentNo}</td><td className="px-4 py-2">{ship.date}</td><td className="px-4 py-2 text-right">{ship.qty}EA</td><td className="px-4 py-2"><span className={`px-2 py-0.5 rounded text-xs ${ship.status === '배송완료' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'}`}>{ship.status}</span></td></tr>)) : (<tr><td colSpan={4} className="text-center py-8 text-gray-500">출고 내역이 없습니다.</td></tr>)}</tbody></table></div></Card>
      {/* 변경이력 섹션 */}
      <Card title="변경이력"><div className="space-y-3 p-4">{site.history?.length > 0 ? site.history.map((h, idx) => (<div key={idx} className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg"><div className="w-2 h-2 mt-2 rounded-full bg-blue-500" /><div className="flex-1"><div className="flex items-center justify-between"><span className="font-medium text-sm">{h.action}</span><span className="text-xs text-gray-500">{h.date}</span></div><p className="text-sm text-gray-600 mt-1">{h.note}</p><p className="text-xs text-gray-400 mt-1">{h.by}</p></div></div>)) : (<div className="text-center py-8 text-gray-500">변경 이력이 없습니다.</div>)}</div></Card>
    </div>
  );
};

// 현장 등록/수정 페이지
const SiteRegister = ({ site, onNavigate, isEdit = false }) => {
  // 채번규칙에 따른 현장코드 생성 (PJ-YYMMDD-##)
  const generateSiteCode = () => {
    const now = new Date();
    const yy = String(now.getFullYear()).slice(-2);
    const mm = String(now.getMonth() + 1).padStart(2, '0');
    const dd = String(now.getDate()).padStart(2, '0');
    const seq = String(Math.floor(Math.random() * 99) + 1).padStart(2, '0');
    return `PJ-${yy}${mm}${dd}-${seq}`;
  };
  const [formData, setFormData] = useState(site || { siteCode: generateSiteCode(), siteName: '', customerId: '', customerName: '', siteAddress: '', siteContact: '', status: '수주확정', installManager: '', installManagerPhone: '', installScheduledDate: '', installCompletedDate: '', note: '', progress: 0 });
  const handleSave = () => { alert(isEdit ? '현장 정보가 수정되었습니다.' : `현장이 등록되었습니다.\n현장코드: ${formData.siteCode}`); onNavigate('site'); };
  return (
    <div className="space-y-6">
      <PageHeader icon={Building} title={isEdit ? '현장 수정' : '현장 등록'} actions={<Button variant="secondary" onClick={() => onNavigate('site')}><ArrowLeft className="w-4 h-4" /> 목록으로</Button>} />
      <Card title="현장 정보"><div className="grid grid-cols-2 gap-4 p-4"><FormField label="현장명" required><input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="현장명 입력" value={formData.siteName || ''} onChange={(e) => setFormData({ ...formData, siteName: e.target.value })} /></FormField><FormField label="거래처" required><select className="w-full border rounded-lg px-3 py-2 text-sm" value={formData.customerId || ''} onChange={(e) => setFormData({ ...formData, customerId: e.target.value })}><option value="">거래처 선택</option>{initialCustomers.filter(c => c.customerType === '고객사').map(c => (<option key={c.id} value={c.id}>{c.customerName}</option>))}</select></FormField><div className="col-span-2"><FormField label="현장주소" required><input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="현장 주소 입력" value={formData.siteAddress || ''} onChange={(e) => setFormData({ ...formData, siteAddress: e.target.value })} /></FormField></div><FormField label="현장연락처"><input type="tel" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="02-0000-0000" value={formData.siteContact || ''} onChange={(e) => setFormData({ ...formData, siteContact: e.target.value })} /></FormField><FormField label="진행상태"><select className="w-full border rounded-lg px-3 py-2 text-sm" value={formData.status || ''} onChange={(e) => setFormData({ ...formData, status: e.target.value })}><option value="수주확정">수주확정</option><option value="생산중">생산중</option><option value="출하대기">출하대기</option><option value="설치중">설치중</option><option value="설치완료">설치완료</option></select></FormField></div></Card>
      <Card title="설치 담당자"><div className="grid grid-cols-2 gap-4 p-4"><FormField label="담당자명"><input type="text" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="설치담당자명" value={formData.installManager || ''} onChange={(e) => setFormData({ ...formData, installManager: e.target.value })} /></FormField><FormField label="연락처"><input type="tel" className="w-full border rounded-lg px-3 py-2 text-sm" placeholder="010-0000-0000" value={formData.installManagerPhone || ''} onChange={(e) => setFormData({ ...formData, installManagerPhone: e.target.value })} /></FormField><FormField label="설치예정일"><input type="date" className="w-full border rounded-lg px-3 py-2 text-sm" value={formData.installScheduledDate || ''} onChange={(e) => setFormData({ ...formData, installScheduledDate: e.target.value })} /></FormField><FormField label="설치완료일"><input type="date" className="w-full border rounded-lg px-3 py-2 text-sm" value={formData.installCompletedDate || ''} onChange={(e) => setFormData({ ...formData, installCompletedDate: e.target.value })} /></FormField><div className="col-span-2"><FormField label="특이사항"><textarea className="w-full border rounded-lg px-3 py-2 text-sm resize-none" rows={3} placeholder="현장 특이사항 입력" value={formData.note || ''} onChange={(e) => setFormData({ ...formData, note: e.target.value })} /></FormField></div></div></Card>
      <div className="flex justify-end gap-3"><Button variant="secondary" onClick={() => onNavigate('site')}>취소</Button><Button variant="primary" onClick={handleSave}><CheckCircle className="w-4 h-4" /> {isEdit ? '수정 완료' : '등록 완료'}</Button></div>
    </div>
  );
};

// ============ 견적수식관리 ============

// 견적수식관리 메인 컴포넌트
const QuoteFormulaManagement = ({ onNavigate }) => {
  const [activeSection, setActiveSection] = useState('formula'); // formula, classification, price-formula, auto-quote
  const [selectedProduct, setSelectedProduct] = useState('common');
  const [selectedCategory, setSelectedCategory] = useState('basic-info');
  const [showProductDropdown, setShowProductDropdown] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [showFormulaModal, setShowFormulaModal] = useState(false);
  const [showCategoryModal, setShowCategoryModal] = useState(false);
  const [showClassificationModal, setShowClassificationModal] = useState(false);
  const [showPriceFormulaModal, setShowPriceFormulaModal] = useState(false);
  const [formulas, setFormulas] = useState(initialQuoteFormulas);
  const [categories, setCategories] = useState(formulaCategories);
  const [classifications, setClassifications] = useState(initialPriceClassifications);
  const [priceFormulas, setPriceFormulas] = useState(initialPriceFormulas);
  const [editingItem, setEditingItem] = useState(null);

  // 새 수식 폼
  const [formulaForm, setFormulaForm] = useState({
    productId: 'common',
    categoryId: 'basic-info',
    name: '',
    variable: '',
    type: 'formula',
    formula: '',
    resultType: 'item',
    description: '',
    process: null,
    itemCode: '',
    itemName: '',
    unit: 'EA',
    qtyFormula: '',
  });

  // 새 카테고리 폼
  const [categoryForm, setCategoryForm] = useState({ name: '' });

  // 새 분류 폼
  const [classificationForm, setClassificationForm] = useState({
    name: '',
    description: '',
    selectedCategories: [],
  });

  // 단가 수식 폼
  const [priceFormulaForm, setPriceFormulaForm] = useState({
    classificationId: null,
    formula: '',
    description: '',
    isActive: true,
    qtyCalc: 'UP',
  });

  // 현재 제품의 수식 필터링
  const filteredFormulas = formulas.filter(f =>
    f.productId === selectedProduct && f.categoryId === selectedCategory
  );

  // 카테고리별 수식 개수
  const getCategoryFormulaCount = (categoryId) => {
    return formulas.filter(f => f.productId === selectedProduct && f.categoryId === categoryId).length;
  };

  // 제품 선택
  const handleProductSelect = (productId) => {
    setSelectedProduct(productId);
    setShowProductDropdown(false);
  };

  // 수식 추가
  const handleAddFormula = () => {
    if (!formulaForm.name || !formulaForm.variable) {
      alert('이름과 변수는 필수입니다.');
      return;
    }

    const newFormula = {
      id: Date.now(),
      ...formulaForm,
      order: filteredFormulas.length + 1,
    };

    setFormulas([...formulas, newFormula]);
    setShowFormulaModal(false);
    setFormulaForm({
      productId: selectedProduct,
      categoryId: selectedCategory,
      name: '',
      variable: '',
      type: 'formula',
      formula: '',
      resultType: 'item',
      description: '',
      process: null,
      itemCode: '',
      itemName: '',
      unit: 'EA',
      qtyFormula: '',
    });
  };

  // 카테고리 추가
  const handleAddCategory = () => {
    if (!categoryForm.name) {
      alert('카테고리 이름을 입력하세요.');
      return;
    }

    const newCategory = {
      id: categoryForm.name.toLowerCase().replace(/\s+/g, '-'),
      name: categoryForm.name,
      order: categories.length + 1,
    };

    setCategories([...categories, newCategory]);
    setShowCategoryModal(false);
    setCategoryForm({ name: '' });
  };

  // 수식 삭제
  const handleDeleteFormula = (id) => {
    if (confirm('이 수식을 삭제하시겠습니까?')) {
      setFormulas(formulas.filter(f => f.id !== id));
    }
  };

  // 분류 추가
  const handleAddClassification = () => {
    if (!classificationForm.name) {
      alert('분류명을 입력하세요.');
      return;
    }

    const newClassification = {
      id: Date.now(),
      name: classificationForm.name,
      description: classificationForm.description,
      categories: classificationForm.selectedCategories,
      itemCount: classificationForm.selectedCategories.length,
    };

    setClassifications([...classifications, newClassification]);
    setShowClassificationModal(false);
    setClassificationForm({ name: '', description: '', selectedCategories: [] });
  };

  // 단가 수식 추가
  const handleAddPriceFormula = () => {
    if (!priceFormulaForm.classificationId || !priceFormulaForm.formula) {
      alert('분류 그룹과 수식을 입력하세요.');
      return;
    }

    const classification = classifications.find(c => c.id === priceFormulaForm.classificationId);
    const newPriceFormula = {
      id: Date.now(),
      ...priceFormulaForm,
      classificationName: classification?.name || '',
    };

    setPriceFormulas([...priceFormulas, newPriceFormula]);
    setShowPriceFormulaModal(false);
    setPriceFormulaForm({ classificationId: null, formula: '', description: '', isActive: true, qtyCalc: 'UP' });
  };

  const sections = [
    { id: 'formula', label: '품목 수식 관리', icon: Calculator },
    { id: 'classification', label: '분류 관리', icon: Layers },
    { id: 'price-formula', label: '단가 수식 관리', icon: DollarSign },
    { id: 'auto-quote', label: '자동 견적 산출', icon: Zap },
  ];

  return (
    <div className="space-y-6">
      {/* 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <Calculator className="w-6 h-6 text-blue-500" />
          견적수식 목록
        </h1>
      </div>

      {/* 섹션 탭 */}
      <div className="flex gap-2 border-b pb-2">
        {sections.map(section => (
          <button
            key={section.id}
            onClick={() => setActiveSection(section.id)}
            className={`flex items-center gap-2 px-4 py-2 rounded-t-lg text-sm font-medium transition-colors ${activeSection === section.id
                ? 'bg-blue-500 text-white'
                : 'text-gray-600 hover:bg-gray-100'
              }`}
          >
            <section.icon className="w-4 h-4" />
            {section.label}
          </button>
        ))}
      </div>

      {/* 품목 수식 관리 섹션 */}
      {activeSection === 'formula' && (
        <Card>
          <div className="space-y-4">
            {/* 제품 선택 */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <span className="text-sm font-medium text-gray-700">제품 선택</span>
                <div className="relative">
                  <button
                    onClick={() => setShowProductDropdown(!showProductDropdown)}
                    className="flex items-center gap-2 px-4 py-2 border rounded-lg bg-white min-w-[200px] justify-between"
                  >
                    <span>{quoteProducts.find(p => p.id === selectedProduct)?.name}</span>
                    <span className="text-xs text-gray-500">
                      {formulas.filter(f => f.productId === selectedProduct).length}개 수식
                    </span>
                    <ChevronDown className="w-4 h-4 text-gray-400" />
                  </button>

                  {showProductDropdown && (
                    <div className="absolute top-full left-0 mt-1 w-64 bg-white border rounded-lg shadow-lg z-10">
                      <div className="p-2 border-b">
                        <div className="relative">
                          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                          <input
                            type="text"
                            placeholder="제품 검색..."
                            className="w-full pl-9 pr-3 py-2 text-sm border rounded-lg"
                          />
                        </div>
                      </div>
                      <div className="py-1">
                        {quoteProducts.map(product => (
                          <button
                            key={product.id}
                            onClick={() => handleProductSelect(product.id)}
                            className={`w-full px-4 py-2 text-left text-sm hover:bg-gray-50 flex items-center justify-between ${selectedProduct === product.id ? 'bg-blue-50 text-blue-700' : ''
                              }`}
                          >
                            <span>{product.name}</span>
                            <span className="text-xs text-gray-500">{product.formulaCount}개 수식</span>
                          </button>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              </div>

              <div className="flex items-center gap-2">
                <button
                  onClick={() => setEditMode(!editMode)}
                  className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm ${editMode ? 'bg-blue-500 text-white' : 'border text-gray-700 hover:bg-gray-50'
                    }`}
                >
                  <Settings className="w-4 h-4" />
                  {editMode ? '완료' : '수정'}
                </button>
                <button
                  onClick={() => setShowCategoryModal(true)}
                  className="flex items-center gap-2 px-4 py-2 border rounded-lg text-sm text-gray-700 hover:bg-gray-50"
                >
                  <Plus className="w-4 h-4" />
                  카테고리 추가
                </button>
              </div>
            </div>

            {/* 카테고리 탭 */}
            <div className="flex items-center gap-2 flex-wrap">
              <span className="text-xs text-gray-500">카테고리 선택 (실행 순서) - 예: 1 2 3</span>
              <div className="flex gap-2 flex-wrap">
                {categories.map((cat, idx) => (
                  <button
                    key={cat.id}
                    onClick={() => setSelectedCategory(cat.id)}
                    className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-sm border transition-colors ${selectedCategory === cat.id
                        ? 'bg-gray-900 text-white border-gray-900'
                        : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                      }`}
                  >
                    {editMode && <GripVertical className="w-3 h-3 text-gray-400" />}
                    <span className="inline-flex items-center justify-center w-5 h-5 bg-blue-100 text-blue-700 rounded-full text-xs font-medium">
                      {idx + 1}
                    </span>
                    {cat.name}
                    <span className="text-xs opacity-70">{getCategoryFormulaCount(cat.id)}</span>
                    {editMode && (
                      <>
                        <Edit2 className="w-3 h-3 text-gray-400 cursor-pointer hover:text-blue-500" />
                        <Trash2 className="w-3 h-3 text-gray-400 cursor-pointer hover:text-red-500" />
                      </>
                    )}
                  </button>
                ))}
              </div>
            </div>

            {/* 수식 테이블 */}
            <div className="border rounded-lg overflow-hidden">
              <div className="flex items-center justify-between px-4 py-3 bg-gray-50 border-b">
                <div className="flex items-center gap-2">
                  <span className="font-medium">{categories.find(c => c.id === selectedCategory)?.name}</span>
                  <button className="text-sm text-blue-600 hover:underline">카테고리에 수식 추가</button>
                </div>
                <button
                  onClick={() => {
                    setFormulaForm({ ...formulaForm, productId: selectedProduct, categoryId: selectedCategory });
                    setShowFormulaModal(true);
                  }}
                  className="flex items-center gap-2 px-3 py-1.5 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
                >
                  <Plus className="w-4 h-4" />
                  수식 추가
                </button>
              </div>

              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 w-12">순서</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">이름</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">변수</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 w-20">타입</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">수식/범위</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 w-20">결과 타입</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">설명</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 w-24">작업</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {filteredFormulas.map((formula, idx) => (
                    <tr key={formula.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <GripVertical className="w-4 h-4 text-gray-300 cursor-grab" />
                          <span className="text-sm text-gray-500">{idx + 1}</span>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-sm font-medium">{formula.name}</td>
                      <td className="px-4 py-3 text-sm font-mono text-gray-600">{formula.variable}</td>
                      <td className="px-4 py-3">
                        <span className={`inline-flex px-2 py-0.5 rounded text-xs font-medium ${formula.type === 'input' ? 'bg-green-100 text-green-700' :
                            formula.type === 'formula' ? 'bg-blue-100 text-blue-700' :
                              'bg-purple-100 text-purple-700'
                          }`}>
                          {formula.type === 'input' ? '계산식' : formula.type === 'formula' ? '계산식' : '조회'}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-sm font-mono text-gray-600">{formula.formula}</td>
                      <td className="px-4 py-3 text-sm text-gray-500">{formula.resultType === 'item' ? '품목' : '출력'}</td>
                      <td className="px-4 py-3 text-sm text-gray-500">{formula.description}</td>
                      <td className="px-4 py-3">
                        <div className="flex items-center justify-center gap-2">
                          <button className="p-1 hover:bg-gray-100 rounded">
                            <Edit2 className="w-4 h-4 text-gray-400" />
                          </button>
                          <button
                            onClick={() => handleDeleteFormula(formula.id)}
                            className="p-1 hover:bg-gray-100 rounded"
                          >
                            <Trash2 className="w-4 h-4 text-gray-400 hover:text-red-500" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                  {filteredFormulas.length === 0 && (
                    <tr>
                      <td colSpan={8} className="px-4 py-8 text-center text-gray-500">
                        이 카테고리에 등록된 수식이 없습니다.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </Card>
      )}

      {/* 분류 관리 섹션 */}
      {activeSection === 'classification' && (
        <Card title="단가 계산 분류 관리" subtitle="카테고리들을 묶는 분류를 생성하고 관리합니다"
          action={
            <button
              onClick={() => setShowClassificationModal(true)}
              className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
            >
              <Plus className="w-4 h-4" />
              분류 추가
            </button>
          }
        >
          <div className="mb-4">
            <div className="relative max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder="분류명, 설명, 카테고리로 검색..."
                className="w-full pl-9 pr-4 py-2 border rounded-lg text-sm"
              />
            </div>
          </div>

          <div className="space-y-4">
            {classifications.map(classification => (
              <div key={classification.id} className="border rounded-lg p-4">
                <div className="flex items-center justify-between mb-2">
                  <div>
                    <h3 className="font-medium text-gray-900">{classification.name}</h3>
                    <p className="text-sm text-gray-500">{classification.description}</p>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-500">{classification.itemCount}개</span>
                    <button className="p-1 hover:bg-gray-100 rounded">
                      <Edit2 className="w-4 h-4 text-gray-400" />
                    </button>
                    <button className="p-1 hover:bg-gray-100 rounded">
                      <Trash2 className="w-4 h-4 text-gray-400 hover:text-red-500" />
                    </button>
                  </div>
                </div>
                <div className="flex flex-wrap gap-2">
                  {classification.categories.map(cat => (
                    <span key={cat} className="px-2 py-1 bg-gray-100 text-gray-700 rounded text-xs">
                      {cat}
                    </span>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* 단가 수식 관리 섹션 */}
      {activeSection === 'price-formula' && (
        <Card title="단가 수식 관리" subtitle="분류 그룹 또는 개별 품목에 단가 계산 수식을 연결합니다"
          action={
            <button
              onClick={() => setShowPriceFormulaModal(true)}
              className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
            >
              <Plus className="w-4 h-4" />
              단가 수식 추가
            </button>
          }
        >
          <div className="mb-4">
            <div className="relative max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder="수식명, 품목명, 그룹명으로 검색..."
                className="w-full pl-9 pr-4 py-2 border rounded-lg text-sm"
              />
            </div>
          </div>

          <div className="space-y-4">
            {priceFormulas.map(pf => {
              const classification = classifications.find(c => c.id === pf.classificationId);
              return (
                <div key={pf.id} className="border rounded-lg p-4">
                  <div className="flex items-center gap-3 mb-3">
                    <input type="checkbox" checked={pf.isActive} readOnly className="w-4 h-4 rounded" />
                    <h3 className="font-medium text-gray-900">{pf.classificationName}</h3>
                    <span className="px-2 py-0.5 bg-blue-100 text-blue-700 rounded text-xs">그룹</span>
                    <span className="text-sm text-gray-500">{classification?.itemCount || 0}개 품목</span>
                    <div className="ml-auto flex items-center gap-2">
                      <button className="p-1 hover:bg-gray-100 rounded">
                        <Edit2 className="w-4 h-4 text-gray-400" />
                      </button>
                      <button className="p-1 hover:bg-gray-100 rounded">
                        <Trash2 className="w-4 h-4 text-gray-400 hover:text-red-500" />
                      </button>
                    </div>
                  </div>
                  <div className="flex flex-wrap gap-2 mb-2">
                    {classification?.categories.map(cat => (
                      <span key={cat} className="px-2 py-1 bg-gray-100 text-gray-700 rounded text-xs">
                        {cat}
                      </span>
                    ))}
                  </div>
                  <div className="flex items-center gap-4 text-sm text-gray-500">
                    <span>적용 수식: <span className="font-mono">{pf.formula}</span></span>
                    <span>수량 계산: {pf.qtyCalc}</span>
                  </div>
                </div>
              );
            })}

            {priceFormulas.length === 0 && (
              <div className="text-center py-8 text-gray-500">
                등록된 단가 수식이 없습니다.
              </div>
            )}
          </div>
        </Card>
      )}

      {/* 자동 견적 산출 섹션 */}
      {activeSection === 'auto-quote' && (
        <AutoQuoteCalculator formulas={formulas} categories={categories} />
      )}

      {/* 수식 추가 모달 */}
      {showFormulaModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[90vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between p-4 border-b flex-shrink-0">
              <div>
                <h2 className="text-lg font-bold">수식 추가</h2>
                <p className="text-sm text-gray-500">수식 정보를 입력하세요.</p>
              </div>
              <button onClick={() => setShowFormulaModal(false)} className="p-2 hover:bg-gray-100 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-4 space-y-4 max-h-[60vh] overflow-y-auto">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">제품 *</label>
                  <select
                    value={formulaForm.productId}
                    onChange={e => setFormulaForm({ ...formulaForm, productId: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  >
                    {quoteProducts.map(p => (
                      <option key={p.id} value={p.id}>{p.name}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">카테고리 *</label>
                  <select
                    value={formulaForm.categoryId}
                    onChange={e => setFormulaForm({ ...formulaForm, categoryId: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg text-sm"
                  >
                    {categories.map(c => (
                      <option key={c.id} value={c.id}>{c.name}</option>
                    ))}
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">이름 *</label>
                <input
                  type="text"
                  value={formulaForm.name}
                  onChange={e => setFormulaForm({ ...formulaForm, name: e.target.value })}
                  placeholder="예: 스크린 가로"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">변수 *</label>
                <input
                  type="text"
                  value={formulaForm.variable}
                  onChange={e => setFormulaForm({ ...formulaForm, variable: e.target.value })}
                  placeholder="예: W1_스크린"
                  className="w-full px-3 py-2 border rounded-lg text-sm font-mono"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">타입 *</label>
                <select
                  value={formulaForm.type}
                  onChange={e => setFormulaForm({ ...formulaForm, type: e.target.value })}
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                >
                  <option value="input">입력값</option>
                  <option value="formula">계산식</option>
                  <option value="lookup">조회</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">결과 출력 *</label>
                <div className="flex gap-4">
                  <label className="flex items-center gap-2">
                    <input
                      type="radio"
                      checked={formulaForm.resultType === 'item'}
                      onChange={() => setFormulaForm({ ...formulaForm, resultType: 'item' })}
                    />
                    <span className="text-sm">변수에 저장</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input
                      type="radio"
                      checked={formulaForm.resultType === 'output'}
                      onChange={() => setFormulaForm({ ...formulaForm, resultType: 'output' })}
                    />
                    <span className="text-sm">품목/수량 출력</span>
                  </label>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">계산식 *</label>
                <input
                  type="text"
                  value={formulaForm.formula}
                  onChange={e => setFormulaForm({ ...formulaForm, formula: e.target.value })}
                  placeholder="예: W0 + 140, SUM(W0, H0), ROUND(M * 2.5, 2)"
                  className="w-full px-3 py-2 border rounded-lg text-sm font-mono"
                />
                <div className="flex gap-2 mt-2">
                  <button className="flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:bg-blue-50 rounded">
                    <Search className="w-3 h-3" /> 변수 검색
                  </button>
                  <button className="flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:bg-blue-50 rounded">
                    <HelpCircle className="w-3 h-3" /> 함수 도움말
                  </button>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">설명</label>
                <input
                  type="text"
                  value={formulaForm.description}
                  onChange={e => setFormulaForm({ ...formulaForm, description: e.target.value })}
                  placeholder="수식에 대한 설명을 입력하세요."
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
            </div>
            <div className="flex justify-end gap-2 p-4 border-t">
              <button
                onClick={() => setShowFormulaModal(false)}
                className="px-4 py-2 text-gray-700 border rounded-lg hover:bg-gray-50"
              >
                <X className="w-4 h-4 inline mr-1" /> 취소
              </button>
              <button
                onClick={handleAddFormula}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
              >
                <Save className="w-4 h-4 inline mr-1" /> 저장
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 카테고리 추가 모달 */}
      {showCategoryModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-4 border-b sticky top-0 bg-white z-10">
              <div>
                <h2 className="text-lg font-bold">카테고리 추가</h2>
                <p className="text-sm text-gray-500">새로운 카테고리 이름을 입력하세요.</p>
              </div>
              <button onClick={() => setShowCategoryModal(false)} className="p-2 hover:bg-gray-100 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-4">
              <label className="block text-sm font-medium text-gray-700 mb-1">카테고리 이름 *</label>
              <input
                type="text"
                value={categoryForm.name}
                onChange={e => setCategoryForm({ name: e.target.value })}
                placeholder="예: 공정비, 원단비 등"
                className="w-full px-3 py-2 border rounded-lg text-sm"
              />
            </div>
            <div className="flex justify-end gap-2 p-4 border-t">
              <button
                onClick={() => setShowCategoryModal(false)}
                className="px-4 py-2 text-gray-700 border rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleAddCategory}
                className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
              >
                <Plus className="w-4 h-4" /> 추가
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 분류 추가 모달 */}
      {showClassificationModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-4 border-b sticky top-0 bg-white z-10">
              <div>
                <h2 className="text-lg font-bold">분류 추가</h2>
                <p className="text-sm text-gray-500">카테고리들을 묶는 분류를 설정합니다.</p>
              </div>
              <button onClick={() => setShowClassificationModal(false)} className="p-2 hover:bg-gray-100 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">분류명 *</label>
                <input
                  type="text"
                  value={classificationForm.name}
                  onChange={e => setClassificationForm({ ...classificationForm, name: e.target.value })}
                  placeholder="예: 오픈형 제품, 면적 기반 제품"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">설명 (선택)</label>
                <input
                  type="text"
                  value={classificationForm.description}
                  onChange={e => setClassificationForm({ ...classificationForm, description: e.target.value })}
                  placeholder="분류에 대한 설명"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">포함할 카테고리 *</label>
                <p className="text-xs text-gray-500 mb-2">수식 관리에서 생성된 카테고리를 선택하세요</p>
                <div className="space-y-2 max-h-48 overflow-y-auto border rounded-lg p-2">
                  {categories.map(cat => (
                    <label key={cat.id} className="flex items-center gap-2 p-2 hover:bg-gray-50 rounded">
                      <input
                        type="checkbox"
                        checked={classificationForm.selectedCategories.includes(cat.name)}
                        onChange={e => {
                          if (e.target.checked) {
                            setClassificationForm({
                              ...classificationForm,
                              selectedCategories: [...classificationForm.selectedCategories, cat.name]
                            });
                          } else {
                            setClassificationForm({
                              ...classificationForm,
                              selectedCategories: classificationForm.selectedCategories.filter(c => c !== cat.name)
                            });
                          }
                        }}
                        className="w-4 h-4 rounded"
                      />
                      <span className="text-sm">{cat.name}</span>
                      <span className="text-xs text-gray-500">{getCategoryFormulaCount(cat.id)}개 수식</span>
                    </label>
                  ))}
                </div>
                {classificationForm.selectedCategories.length > 0 && (
                  <div className="mt-2 p-2 bg-blue-50 rounded-lg">
                    <p className="text-xs text-blue-700 mb-1">선택된 카테고리 ({classificationForm.selectedCategories.length}개)</p>
                    <div className="flex flex-wrap gap-1">
                      {classificationForm.selectedCategories.map(cat => (
                        <span key={cat} className="px-2 py-0.5 bg-white text-blue-700 rounded text-xs">
                          {cat}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>
            <div className="flex justify-end gap-2 p-4 border-t">
              <button
                onClick={() => setShowClassificationModal(false)}
                className="px-4 py-2 text-gray-700 border rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleAddClassification}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
              >
                추가
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 단가 수식 연결 모달 */}
      {showPriceFormulaModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-4 border-b sticky top-0 bg-white z-10">
              <div>
                <h2 className="text-lg font-bold">단가 수식 연결</h2>
                <p className="text-sm text-gray-500">분류 그룹 또는 품목에 적용할 단가 계산 수식을 연결합니다</p>
              </div>
              <button onClick={() => setShowPriceFormulaModal(false)} className="p-2 hover:bg-gray-100 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">분류 그룹</label>
                <select
                  value={priceFormulaForm.classificationId || ''}
                  onChange={e => setPriceFormulaForm({ ...priceFormulaForm, classificationId: Number(e.target.value) })}
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                >
                  <option value="">분류 그룹 선택</option>
                  {classifications.map(c => (
                    <option key={c.id} value={c.id}>
                      {c.name} - {c.categories.join(', ')}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">단가 계산 수식 *</label>
                <input
                  type="text"
                  value={priceFormulaForm.formula}
                  onChange={e => setPriceFormulaForm({ ...priceFormulaForm, formula: e.target.value })}
                  placeholder="예: W0 * H0 / 1000000"
                  className="w-full px-3 py-2 border rounded-lg text-sm font-mono"
                />
                <div className="flex gap-2 mt-2">
                  <button className="flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:bg-blue-50 rounded">
                    <Search className="w-3 h-3" /> 변수 검색
                  </button>
                  <button className="flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:bg-blue-50 rounded">
                    <HelpCircle className="w-3 h-3" /> 함수 도움말
                  </button>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">설명 (선택)</label>
                <input
                  type="text"
                  value={priceFormulaForm.description}
                  onChange={e => setPriceFormulaForm({ ...priceFormulaForm, description: e.target.value })}
                  placeholder="단가 수식 연결에 대한 설명"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={priceFormulaForm.isActive}
                  onChange={e => setPriceFormulaForm({ ...priceFormulaForm, isActive: e.target.checked })}
                  className="w-4 h-4 rounded"
                />
                <span className="text-sm">활성화</span>
              </label>
            </div>
            <div className="flex justify-end gap-2 p-4 border-t">
              <button
                onClick={() => setShowPriceFormulaModal(false)}
                className="px-4 py-2 text-gray-700 border rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleAddPriceFormula}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
              >
                추가
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 자동 견적 산출 컴포넌트
const AutoQuoteCalculator = ({ formulas, categories }) => {
  const [inputs, setInputs] = useState({
    PC: '스크린',      // 제품 카테고리
    W0: 2000,          // 오픈사이즈 가로
    H0: 2500,          // 오픈사이즈 세로
    GT: '벽면형',      // 가이드레일 설치유형
    V: '220',          // 모터 전원
    WIRE: '유선',      // 유/무선
    CT: '매립',        // 연동제어기 유형
    QTY: 1,            // 수량
    floor: '',         // 층수
    symbol: '',        // 부호
  });
  const [calculatedResult, setCalculatedResult] = useState(null);
  const [showSummary, setShowSummary] = useState(true);
  const [groupByProcess, setGroupByProcess] = useState(false);
  const [showQuoteModal, setShowQuoteModal] = useState(false);

  // 견적 계산
  const handleCalculate = () => {
    const result = formulaEngine.calculateQuoteItems(inputs, formulas, itemPriceMaster);
    setCalculatedResult(result);
  };

  // 초기화
  const handleReset = () => {
    setInputs({
      PC: '스크린',
      W0: 2000,
      H0: 2500,
      GT: '벽면형',
      V: '220',
      WIRE: '유선',
      CT: '매립',
      QTY: 1,
      floor: '',
      symbol: '',
    });
    setCalculatedResult(null);
  };

  // 공정별 그룹화
  const getGroupedItems = () => {
    if (!calculatedResult?.items) return {};
    return calculatedResult.items.reduce((acc, item) => {
      const key = item.process || '기타';
      if (!acc[key]) acc[key] = [];
      acc[key].push(item);
      return acc;
    }, {});
  };

  // 카테고리별 합계
  const getCategorySummary = () => {
    if (!calculatedResult?.items) return [];
    const summary = {};
    calculatedResult.items.forEach(item => {
      const cat = item.category || 'etc';
      if (!summary[cat]) summary[cat] = { name: cat, count: 0, amount: 0 };
      summary[cat].count += item.qty;
      summary[cat].amount += item.amount;
    });
    return Object.values(summary);
  };

  const groupedItems = getGroupedItems();
  const categorySummary = getCategorySummary();

  return (
    <Card title="자동 견적 산출" subtitle="오픈사이즈와 옵션을 입력하면 자동으로 품목과 가격을 산출합니다">
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
        {/* 입력 폼 */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="font-medium text-gray-900 flex items-center gap-2">
              <Settings className="w-4 h-4" />
              견적 입력
            </h3>
            <button
              onClick={handleReset}
              className="text-xs text-gray-500 hover:text-gray-700"
            >
              초기화
            </button>
          </div>

          <div className="border rounded-lg p-4 bg-gradient-to-b from-gray-50 to-white space-y-4">
            {/* 기본정보 */}
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">층수</label>
                <input
                  type="text"
                  value={inputs.floor}
                  onChange={e => setInputs({ ...inputs, floor: e.target.value })}
                  placeholder="예: 1층, B1"
                  className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">부호</label>
                <input
                  type="text"
                  value={inputs.symbol}
                  onChange={e => setInputs({ ...inputs, symbol: e.target.value })}
                  placeholder="예: A, B, C"
                  className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
            </div>

            {/* 제품유형 */}
            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1">제품 유형 (PC) *</label>
              <div className="grid grid-cols-2 gap-2">
                {['스크린', '철재'].map(type => (
                  <button
                    key={type}
                    onClick={() => setInputs({ ...inputs, PC: type })}
                    className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${inputs.PC === type
                        ? 'bg-blue-500 text-white shadow-md'
                        : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                      }`}
                  >
                    {type}
                  </button>
                ))}
              </div>
            </div>

            {/* 오픈사이즈 */}
            <div className="p-3 bg-blue-50 rounded-lg">
              <label className="block text-xs font-medium text-blue-700 mb-2">오픈사이즈 (mm) *</label>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <span className="text-xs text-blue-600">가로 (W0)</span>
                  <input
                    type="number"
                    value={inputs.W0}
                    onChange={e => setInputs({ ...inputs, W0: Number(e.target.value) })}
                    className="w-full px-3 py-2 border border-blue-200 rounded-lg text-sm font-mono bg-white focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <span className="text-xs text-blue-600">세로 (H0)</span>
                  <input
                    type="number"
                    value={inputs.H0}
                    onChange={e => setInputs({ ...inputs, H0: Number(e.target.value) })}
                    className="w-full px-3 py-2 border border-blue-200 rounded-lg text-sm font-mono bg-white focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>
            </div>

            {/* 설치유형 */}
            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1">가이드레일 설치 유형 (GT)</label>
              <select
                value={inputs.GT}
                onChange={e => setInputs({ ...inputs, GT: e.target.value })}
                className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500"
              >
                <option value="벽면형">벽면형</option>
                <option value="코너형">코너형</option>
              </select>
            </div>

            {/* 모터 설정 */}
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">모터 전원 (V)</label>
                <select
                  value={inputs.V}
                  onChange={e => setInputs({ ...inputs, V: e.target.value })}
                  className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500"
                >
                  <option value="220">220V</option>
                  <option value="380">380V</option>
                </select>
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">유/무선</label>
                <select
                  value={inputs.WIRE}
                  onChange={e => setInputs({ ...inputs, WIRE: e.target.value })}
                  className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500"
                >
                  <option value="유선">유선</option>
                  <option value="무선">무선</option>
                </select>
              </div>
            </div>

            {/* 제어기 설정 */}
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">연동제어기 (CT)</label>
                <select
                  value={inputs.CT}
                  onChange={e => setInputs({ ...inputs, CT: e.target.value })}
                  className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500"
                >
                  <option value="매립">매립형</option>
                  <option value="노출">노출형</option>
                </select>
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">수량 (QTY)</label>
                <input
                  type="number"
                  value={inputs.QTY}
                  onChange={e => setInputs({ ...inputs, QTY: Math.max(1, Number(e.target.value)) })}
                  min={1}
                  className="w-full px-3 py-2 border rounded-lg text-sm font-mono focus:ring-2 focus:ring-blue-500"
                />
              </div>
            </div>
          </div>

          {/* 계산 버튼 */}
          <button
            onClick={handleCalculate}
            className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-lg hover:from-blue-600 hover:to-blue-700 shadow-lg hover:shadow-xl transition-all font-medium"
          >
            <Calculator className="w-5 h-5" />
            견적 산출
          </button>

          {/* 산출 요약 (계산 결과가 있을 때) */}
          {calculatedResult?.summary && (
            <div className="border rounded-lg p-4 bg-gradient-to-b from-green-50 to-white">
              <div className="flex items-center justify-between mb-3">
                <h4 className="text-sm font-medium text-green-800">산출 정보</h4>
                <button
                  onClick={() => setShowSummary(!showSummary)}
                  className="text-xs text-green-600 hover:text-green-800"
                >
                  {showSummary ? '접기' : '펼치기'}
                </button>
              </div>
              {showSummary && (
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-gray-600">제품유형</span>
                    <span className="font-medium">{calculatedResult.summary.productType}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">오픈사이즈</span>
                    <span className="font-mono">{calculatedResult.summary.openSize}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">제작사이즈</span>
                    <span className="font-mono text-blue-600">{calculatedResult.summary.productionSize}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">면적 (M)</span>
                    <span className="font-mono">{calculatedResult.summary.area} ㎡</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">중량 (K)</span>
                    <span className="font-mono">{calculatedResult.summary.weight} kg</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">모터용량</span>
                    <span className="font-medium text-orange-600">{calculatedResult.summary.motorCapacity}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">샤프트</span>
                    <span className="font-medium">{calculatedResult.summary.shaftInch}</span>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* 산출 결과 */}
        <div className="xl:col-span-2 space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="font-medium text-gray-900 flex items-center gap-2">
              <FileText className="w-4 h-4" />
              산출 결과
              {calculatedResult?.items && (
                <span className="text-sm font-normal text-gray-500">
                  ({calculatedResult.items.length}개 품목)
                </span>
              )}
            </h3>
            {calculatedResult?.items && (
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setGroupByProcess(!groupByProcess)}
                  className={`px-3 py-1 text-xs rounded-full transition-colors ${groupByProcess ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'
                    }`}
                >
                  공정별 보기
                </button>
                <button
                  onClick={() => setShowQuoteModal(true)}
                  className="px-3 py-1 bg-green-500 text-white text-xs rounded-full hover:bg-green-600"
                >
                  견적서 생성
                </button>
              </div>
            )}
          </div>

          {calculatedResult?.items ? (
            <div className="space-y-4">
              {/* 품목 테이블 */}
              <div className="border rounded-lg overflow-hidden max-h-96 overflow-y-auto">
                {groupByProcess ? (
                  // 공정별 그룹 뷰
                  Object.entries(groupedItems).map(([process, items]) => (
                    <div key={process}>
                      <div className="bg-gray-100 px-4 py-2 font-medium text-sm text-gray-700 sticky top-0">
                        {process} ({items.length}개)
                      </div>
                      <table className="w-full">
                        <tbody className="divide-y">
                          {items.map(item => (
                            <tr key={item.id} className="hover:bg-gray-50">
                              <td className="px-4 py-2 text-sm">
                                <div className="font-medium">{item.itemName}</div>
                                <div className="text-xs text-gray-500">{item.itemCode}</div>
                              </td>
                              <td className="px-3 py-2 text-sm font-mono text-gray-600">{item.spec}</td>
                              <td className="px-3 py-2 text-sm text-right">{item.qty} {item.unit}</td>
                              <td className="px-3 py-2 text-sm text-right">{item.unitPrice.toLocaleString()}</td>
                              <td className="px-3 py-2 text-sm text-right font-medium text-blue-600">{item.amount.toLocaleString()}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  ))
                ) : (
                  // 전체 목록 뷰
                  <table className="w-full">
                    <thead className="bg-gray-50 sticky top-0">
                      <tr>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500">품목</th>
                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">규격</th>
                        <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">수량</th>
                        <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">단가</th>
                        <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">금액</th>
                        <th className="px-3 py-2 text-center text-xs font-medium text-gray-500">공정</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {calculatedResult.items.map(item => (
                        <tr key={item.id} className="hover:bg-gray-50">
                          <td className="px-4 py-2 text-sm">
                            <div className="font-medium">{item.itemName}</div>
                            <div className="text-xs text-gray-400">{item.itemCode}</div>
                          </td>
                          <td className="px-3 py-2 text-sm font-mono text-gray-600">{item.spec}</td>
                          <td className="px-3 py-2 text-sm text-right">{item.qty} <span className="text-gray-400">{item.unit}</span></td>
                          <td className="px-3 py-2 text-sm text-right">{item.unitPrice.toLocaleString()}</td>
                          <td className="px-3 py-2 text-sm text-right font-medium">{item.amount.toLocaleString()}</td>
                          <td className="px-3 py-2 text-center">
                            <span className={`px-2 py-0.5 rounded text-xs ${item.process === '스크린' ? 'bg-green-100 text-green-700' :
                                item.process === '절곡' ? 'bg-orange-100 text-orange-700' :
                                  item.process === '샤프트' ? 'bg-purple-100 text-purple-700' :
                                    item.process === '조립' ? 'bg-blue-100 text-blue-700' :
                                      item.process === '검사' ? 'bg-red-100 text-red-700' :
                                        'bg-gray-100 text-gray-700'
                              }`}>
                              {item.process || '-'}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
              </div>

              {/* 카테고리별 요약 */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
                {categorySummary.slice(0, 8).map(cat => (
                  <div key={cat.name} className="p-2 bg-gray-50 rounded-lg text-center">
                    <div className="text-xs text-gray-500">{cat.name}</div>
                    <div className="text-sm font-medium">{cat.amount.toLocaleString()}원</div>
                  </div>
                ))}
              </div>

              {/* 합계 */}
              <div className="flex items-center justify-between p-4 bg-gradient-to-r from-blue-500 to-blue-600 rounded-lg text-white">
                <div>
                  <div className="text-blue-100 text-sm">총 견적 금액</div>
                  <div className="text-xs text-blue-200">부가세 별도</div>
                </div>
                <div className="text-right">
                  <div className="text-2xl font-bold">{calculatedResult.totalAmount.toLocaleString()}원</div>
                  <div className="text-sm text-blue-100">
                    VAT 포함: {Math.round(calculatedResult.totalAmount * 1.1).toLocaleString()}원
                  </div>
                </div>
              </div>

              {/* 액션 버튼 */}
              <div className="flex gap-2">
                <button
                  onClick={() => setShowQuoteModal(true)}
                  className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600"
                >
                  <FileText className="w-4 h-4" />
                  견적서 생성
                </button>
                <button className="flex-1 flex items-center justify-center gap-2 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                  <Download className="w-4 h-4" />
                  산출서 다운로드
                </button>
                <button className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                  <Copy className="w-4 h-4" />
                </button>
              </div>
            </div>
          ) : (
            <div className="border-2 border-dashed rounded-lg p-12 text-center text-gray-400">
              <Calculator className="w-16 h-16 mx-auto mb-4 text-gray-300" />
              <p className="text-lg font-medium mb-2">견적 산출 대기</p>
              <p className="text-sm">왼쪽에서 오픈사이즈와 옵션을 입력하고<br />"견적 산출" 버튼을 클릭하세요.</p>
            </div>
          )}
        </div>
      </div>

      {/* 견적서 생성 모달 */}
      {showQuoteModal && calculatedResult && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-4 border-b sticky top-0 bg-white">
              <h2 className="text-lg font-bold">견적서 미리보기</h2>
              <button onClick={() => setShowQuoteModal(false)} className="p-2 hover:bg-gray-100 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6">
              {/* 견적서 헤더 */}
              <div className="text-center mb-6">
                <h1 className="text-2xl font-bold">견 적 서</h1>
                <p className="text-gray-500">QUOTATION</p>
              </div>

              {/* 기본 정보 */}
              <div className="grid grid-cols-2 gap-4 mb-6 text-sm">
                <div className="space-y-2">
                  <div className="flex"><span className="w-20 text-gray-500">견적번호:</span><span className="font-mono">QT-{Date.now().toString().slice(-8)}</span></div>
                  <div className="flex"><span className="w-20 text-gray-500">견적일자:</span><span>{new Date().toLocaleDateString()}</span></div>
                  <div className="flex"><span className="w-20 text-gray-500">유효기간:</span><span>견적일로부터 30일</span></div>
                </div>
                <div className="space-y-2">
                  <div className="flex"><span className="w-20 text-gray-500">제품유형:</span><span>{calculatedResult.summary.productType}</span></div>
                  <div className="flex"><span className="w-20 text-gray-500">사이즈:</span><span className="font-mono">{calculatedResult.summary.openSize}</span></div>
                  <div className="flex"><span className="w-20 text-gray-500">수량:</span><span>{calculatedResult.summary.qty}SET</span></div>
                </div>
              </div>

              {/* 품목 리스트 */}
              <table className="w-full text-sm mb-6 border">
                <thead className="bg-gray-100">
                  <tr>
                    <th className="px-2 py-2 text-left border-r">품목명</th>
                    <th className="px-2 py-2 text-left border-r">규격</th>
                    <th className="px-2 py-2 text-right border-r">수량</th>
                    <th className="px-2 py-2 text-right border-r">단가</th>
                    <th className="px-2 py-2 text-right">금액</th>
                  </tr>
                </thead>
                <tbody>
                  {calculatedResult.items.map((item, idx) => (
                    <tr key={idx} className="border-t">
                      <td className="px-2 py-1.5 border-r">{item.itemName}</td>
                      <td className="px-2 py-1.5 border-r text-gray-600">{item.spec}</td>
                      <td className="px-2 py-1.5 border-r text-right">{item.qty}</td>
                      <td className="px-2 py-1.5 border-r text-right">{item.unitPrice.toLocaleString()}</td>
                      <td className="px-2 py-1.5 text-right">{item.amount.toLocaleString()}</td>
                    </tr>
                  ))}
                </tbody>
                <tfoot className="bg-gray-50 font-medium">
                  <tr className="border-t">
                    <td colSpan={4} className="px-2 py-2 text-right">공급가액</td>
                    <td className="px-2 py-2 text-right">{calculatedResult.totalAmount.toLocaleString()}원</td>
                  </tr>
                  <tr className="border-t">
                    <td colSpan={4} className="px-2 py-2 text-right">부가세 (10%)</td>
                    <td className="px-2 py-2 text-right">{Math.round(calculatedResult.totalAmount * 0.1).toLocaleString()}원</td>
                  </tr>
                  <tr className="border-t-2 text-blue-600">
                    <td colSpan={4} className="px-2 py-2 text-right font-bold">총 견적금액</td>
                    <td className="px-2 py-2 text-right font-bold">{Math.round(calculatedResult.totalAmount * 1.1).toLocaleString()}원</td>
                  </tr>
                </tfoot>
              </table>

              {/* 버튼 */}
              <div className="flex gap-3">
                <button className="flex-1 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center justify-center gap-2">
                  <Download className="w-4 h-4" />
                  PDF 다운로드
                </button>
                <button className="flex-1 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 flex items-center justify-center gap-2">
                  <Send className="w-4 h-4" />
                  수주 연결
                </button>
                <button
                  onClick={() => setShowQuoteModal(false)}
                  className="px-6 py-2 border rounded-lg hover:bg-gray-50"
                >
                  닫기
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </Card>
  );
};

// ============================================================
// 문서양식관리 (DocumentTemplateManager)
// ============================================================

const OldDocumentTemplateManager = ({ onNavigate }) => {
  // 문서 유형별 상세 템플릿 정의
  const documentTemplates = {
    // 견적서 템플릿
    'QT': {
      title: '견 적 서',
      layout: 'quote',
      showCompanyLogo: true,
      showApprovalBox: false,
      sections: [
        { id: 'header', type: 'titleHeader', fields: ['docTitle'] },
        { id: 'recipient', type: 'recipientBox', label: '수 신', fields: ['customerName', 'contactPerson'] },
        {
          id: 'quoteInfo', type: 'infoTable', rows: [
            [{ label: '현 장 명', field: 'siteName', colSpan: 3 }],
            [{ label: '제 품 명', field: 'itemName', colSpan: 3 }],
            [{ label: '총견적금액', field: 'totalAmount', colSpan: 3, highlight: true }],
          ]
        },
        { id: 'validity', type: 'infoBox', content: '※ 위 견적의 유효기간은 견적일로부터 30일 입니다' },
        { id: 'date', type: 'dateBox', label: '견적일' },
        { id: 'supplier', type: 'companyBox', fields: ['companyName', 'ceoName', 'address', 'phone', 'fax'] },
      ],
      approvalLine: []
    },
    // 견적산출내역서 템플릿
    'QT-DTL': {
      title: '견적산출내역서',
      layout: 'detail',
      showCompanyLogo: true,
      showApprovalBox: false,
      sections: [
        { id: 'header', type: 'titleHeader' },
        {
          id: 'basicInfo', type: 'infoTable', rows: [
            [{ label: '수주번호', field: 'orderNo' }, { label: '수주일자', field: 'orderDate' }],
            [{ label: '거래처', field: 'customerName' }, { label: '현장명', field: 'siteName' }],
            [{ label: '제품명', field: 'itemName' }, { label: '규격', field: 'spec' }],
          ]
        },
        { id: 'itemTable', type: 'productTable', columns: ['순번', '부품명', '규격', '단위', '수량', '단가', '금액', '비고'] },
        {
          id: 'summary', type: 'summaryTable', rows: [
            [{ label: '합계금액', field: 'subtotal' }, { label: '부가세', field: 'tax' }, { label: '총액', field: 'total', highlight: true }]
          ]
        },
      ],
      approvalLine: []
    },
    // 수주확인서 템플릿
    'SO': {
      title: '수 주 확 인 서',
      layout: 'order',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'titleHeader' },
        {
          id: 'orderInfo', type: 'twoColumnTable', left: {
            title: '수요자',
            rows: [
              { label: '상 호', field: 'customerName' },
              { label: '대표자', field: 'customerCeo' },
              { label: '주 소', field: 'customerAddress' },
              { label: '전 화', field: 'customerPhone' },
            ]
          }, right: {
            title: '공급자',
            rows: [
              { label: '상 호', field: 'companyName' },
              { label: '대표자', field: 'ceoName' },
              { label: '주 소', field: 'address' },
              { label: '전 화', field: 'phone' },
            ]
          }
        },
        {
          id: 'productInfo', type: 'infoTable', rows: [
            [{ label: '현장명', field: 'siteName', colSpan: 3 }],
            [{ label: '제품명', field: 'itemName' }, { label: '규격', field: 'spec' }],
            [{ label: '납기일', field: 'dueDate' }, { label: '금액', field: 'totalAmount', highlight: true }],
          ]
        },
        { id: 'remarks', type: 'remarksBox', label: '비고' },
      ],
      approvalLine: [{ role: 'write' }, { role: 'review' }, { role: 'approve' }]
    },
    // 거래명세서 템플릿
    'SL': {
      title: '거 래 명 세 서',
      layout: 'statement',
      showCompanyLogo: true,
      showApprovalBox: false,
      sections: [
        { id: 'header', type: 'titleHeader' },
        {
          id: 'tradeInfo', type: 'twoColumnTable', left: {
            title: '공급받는자',
            rows: [
              { label: '상호', field: 'customerName' },
              { label: '사업자번호', field: 'customerBusinessNo' },
              { label: '주소', field: 'customerAddress' },
            ]
          }, right: {
            title: '공급자',
            rows: [
              { label: '상호', field: 'companyName' },
              { label: '사업자번호', field: 'companyBusinessNo' },
              { label: '주소', field: 'address' },
            ]
          }
        },
        { id: 'itemTable', type: 'productTable', columns: ['일자', '품목', '규격', '수량', '단가', '공급가액', '세액', '비고'] },
        { id: 'summary', type: 'amountSummary' },
      ],
      approvalLine: []
    },
    // 작업지시서 템플릿
    'WO': {
      title: '작 업 지 시 서',
      layout: 'workOrder',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'titleWithNo', label: '지시번호' },
        {
          id: 'orderInfo', type: 'infoTable', rows: [
            [{ label: '수주번호', field: 'orderNo' }, { label: '수주일자', field: 'orderDate' }],
            [{ label: '거래처', field: 'customerName' }, { label: '현장명', field: 'siteName' }],
            [{ label: '제품명', field: 'itemName' }, { label: '규격', field: 'spec' }],
            [{ label: '지시수량', field: 'qty' }, { label: '납기일', field: 'dueDate' }],
          ]
        },
        {
          id: 'sizeInfo', type: 'sizeTable', rows: [
            [{ label: '오픈사이즈', field: 'openSize' }, { label: '제작사이즈', field: 'makeSize' }],
            [{ label: '케이스', field: 'caseSize' }, { label: '특이사항', field: 'specialNote' }],
          ]
        },
        { id: 'processTable', type: 'processTable', columns: ['공정', '작업내용', '담당', '시작일', '완료일', '비고'] },
        { id: 'remarks', type: 'remarksBox', label: '특기사항' },
      ],
      approvalLine: [{ role: 'write', department: '생산관리' }, { role: 'review', department: '품질관리' }, { role: 'approve', position: '공장장' }]
    },
    // 발주서 템플릿
    'PO': {
      title: '발 주 서',
      layout: 'purchase',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'titleHeader' },
        {
          id: 'supplierInfo', type: 'recipientTable', title: '수 신', rows: [
            [{ label: '업체명', field: 'supplierName' }, { label: '담당자', field: 'supplierContact' }],
            [{ label: '연락처', field: 'supplierPhone' }, { label: 'FAX', field: 'supplierFax' }],
          ]
        },
        {
          id: 'deliveryInfo', type: 'infoTable', rows: [
            [{ label: '납품현장', field: 'siteName' }, { label: '납기일', field: 'dueDate' }],
            [{ label: '현장주소', field: 'siteAddress', colSpan: 3 }],
          ]
        },
        { id: 'itemTable', type: 'productTable', columns: ['NO', '품명', '규격', '단위', '수량', '비고'] },
        { id: 'remarks', type: 'remarksBox', label: '특이사항' },
        { id: 'footer', type: 'companySignature' },
      ],
      approvalLine: [{ role: 'write' }, { role: 'review' }, { role: 'approve' }]
    },
    // 수입검사성적서 템플릿
    'IQC': {
      title: '수입검사 성적서',
      layout: 'incomingInspection',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'companyHeader' },
        { id: 'approvalBox', type: 'approvalTable', roles: ['담당', '부서장'], showDate: true },
        {
          id: 'basicInfo', type: 'infoTable', rows: [
            [{ label: '품명', field: 'itemName' }, { label: '납품업체/제조업체', field: 'supplierName' }],
            [{ label: '규격 (두께*너비*길이)', field: 'spec' }, { label: '로트번호', field: 'lotNo' }],
            [{ label: '자재번호', field: 'materialNo' }, { label: '검사일자', field: 'inspectionDate' }],
            [{ label: '로트크기', field: 'lotSize' }, { label: '검사자', field: 'inspector' }],
          ]
        },
        { id: 'inspectionTable', type: 'incomingInspectionTable', columns: ['NO', '검사항목', '검사기준', '검사방식', '검사주기', '측정치 (n1/n2/n3)', '판정'] },
        { id: 'remarks', type: 'remarksSection', title: '특이사항' },
        { id: 'defectContent', type: 'defectSection', title: '부적합 내용' },
        { id: 'judgement', type: 'judgementBox', options: ['합격', '불합격'] },
      ],
      inspectionItems: [
        { no: 1, category: '겉모양', standard: '사용상 해로운 결함이 없을 것', method: '육안검사', period: '', sampleSize: '', measureType: 'okng' },
        {
          no: 2, category: '치수', items: [
            {
              name: '두께', standardOptions: [
                { range: '0.8 이상 ~ 1.0 미만', tolerance: '± 0.07' },
                { range: '1.0 이상 ~ 1.25 미만', tolerance: '± 0.08' },
                { range: '1.25 이상 ~ 1.6 미만', tolerance: '± 0.10' },
                { range: '1.6 이상 ~ 2.0 미만', tolerance: '± 0.12' },
              ], method: '체크검사', period: 'n=3, c=0', measureType: 'value'
            },
            {
              name: '너비', standardOptions: [
                { range: '1250 미만', tolerance: '+7/-0' },
              ], method: '체크검사', period: 'n=3, c=0', measureType: 'value'
            },
            {
              name: '길이', standardOptions: [
                { range: '1250 미만', tolerance: '+10/-0' },
                { range: '2000 이상 ~ 4000 미만', tolerance: '+15/-0' },
                { range: '4000 이상 ~ 6000 미만', tolerance: '+20/-0' },
              ], method: '체크검사', period: 'n=3, c=0', measureType: 'value'
            },
          ]
        },
        { no: 3, category: '인장강도 (N/㎟)', standard: '270 이상', method: '', period: '', measureType: 'value' },
        {
          no: 4, category: '연신율 %', standardOptions: [
            { range: '두께 0.6 이상 ~ 1.0 미만', value: '36 이상' },
            { range: '두께 1.0 이상 ~ 1.6 미만', value: '37 이상' },
            { range: '두께 1.6 이상 ~ 2.3 미만', value: '38 이상' },
          ], method: '공급업체 밀시트', period: '입고시', measureType: 'value'
        },
        { no: 5, category: '아연의 최소 부착량 (g/㎡)', standard: '한면 17 이상', method: '', period: '', measureType: 'value' },
      ],
      remarks: [
        '# 1.55mm의 경우 KS F 4510에 따른 MIN 1.5의 기준에 따름',
        '# 두께의 경우 너비 1000 이상 ~ 1250 미만 기준에 따름',
      ],
      approvalLine: [{ role: 'staff', label: '담당' }, { role: 'manager', label: '부서장' }]
    },
    // 중간검사성적서 템플릿 (스크린/절곡품 호환)
    'PQC': {
      title: '중간 검사성적서',
      layout: 'midInspection',
      showCompanyLogo: true,
      showApprovalBox: true,
      productTypes: ['스크린', '절곡품'],  // 제품유형별 호환
      sections: [
        { id: 'header', type: 'companyHeader' },
        { id: 'approvalBox', type: 'approvalTable', roles: ['작성', '검토', '승인'], departments: ['판매/전진', '생산', '품질'] },
        {
          id: 'basicInfo', type: 'infoTable', rows: [
            [{ label: '품명', field: 'itemName' }, { label: '제품 LOT NO', field: 'lotNo' }],
            [{ label: '규격', field: 'spec' }, { label: '로트크기', field: 'lotSize' }, { label: '개소', field: 'qty' }],
            [{ label: '발주처', field: 'supplierName' }, { label: '검사일자', field: 'inspectionDate' }],
            [{ label: '현장명', field: 'siteName' }, { label: '검사자', field: 'inspector' }],
          ]
        },
        { id: 'inspectionStandard', type: 'inspectionStandardBox', title: '중간검사 기준서' },
        { id: 'inspectionData', type: 'midInspectionTable' },
      ],
      approvalLine: [{ role: 'write', department: '판매/전진' }, { role: 'review', department: '생산' }, { role: 'approve', department: '품질' }]
    },
    // 스크린 중간검사성적서 템플릿
    'PQC-SCR': {
      title: '스크린-중간 검사성적서',
      layout: 'screenMidInspection',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'companyHeader' },
        { id: 'basicInfo', type: 'screenBasicInfo' },
        { id: 'inspectionStandard', type: 'screenInspectionStandard', diagram: 'screenCrossSection' },
        { id: 'inspectionData', type: 'screenInspectionData', columns: ['일련번호', '가공상태', '재봉상태', '조립상태', '길이', '높이', '간격', '판정'] },
      ],
      inspectionItems: {
        appearance: [
          { id: 'processing', name: '가공상태', standard: '사용상 해로운 결함이 없을것', method: '육안검사', regulation: 'KS F 4510 5.1항' },
          { id: 'sewing', name: '재봉상태', standard: '내화실에 의해 견고하게 접합되어야 함', method: '육안검사', regulation: 'KS F 4510 9항' },
          { id: 'assembly', name: '조립상태', standard: '엔드락이 견고하게 조립되어야 함', method: '육안검사', regulation: 'KS F 4510 7항 표9 인용' },
        ],
        dimension: [
          { id: 'length', name: '길이', standard: '도면치수 ± 4', method: '체크검사', unit: 'mm', sampleSize: 'n=1, c=0' },
          { id: 'height', name: '높이', standard: '도면치수 + 제한없음 - 40', method: '체크검사', unit: 'mm' },
          { id: 'interval', name: '간격', standard: '400 이하', method: 'GONO게이지', regulation: '자체규정' },
        ]
      },
      approvalLine: [{ role: 'write', department: '판매/전진' }, { role: 'review', department: '생산' }, { role: 'approve', department: '품질' }]
    },
    // 절곡품 중간검사성적서 템플릿
    'PQC-BND': {
      title: '절곡품-중간 검사성적서',
      layout: 'bendingMidInspection',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'companyHeader' },
        { id: 'basicInfo', type: 'bendingBasicInfo' },
        { id: 'inspectionStandard', type: 'bendingInspectionStandard' },
        { id: 'inspectionData', type: 'bendingInspectionData' },
      ],
      productList: ['가이드레일', '케이스', '하단마감재', '하단 L-BAR', '연기차단재'],
      inspectionItems: {
        appearance: [
          { id: 'bending', name: '절곡상태', standard: '사용상 해로운 결함이 없을것', method: '육안검사', regulation: 'KS F 4510 5.1항' },
        ],
        dimension: [
          { id: 'length', name: '길이', standard: '도면치수 ± 4', method: '체크검사', unit: 'mm', sampleSize: 'n=1, c=0' },
          { id: 'width', name: '너비', standard: 'W50: 50±5 / W80: 80±5', method: '체크검사', unit: 'mm' },
          { id: 'interval', name: '간격', standard: '도면치수 ± 2', method: '체크검사', regulation: '자체규정' },
        ]
      },
      approvalLine: [{ role: 'write', department: '판매/전진' }, { role: 'review', department: '생산' }, { role: 'approve', department: '품질' }]
    },
    // 슬랫 중간검사성적서 템플릿
    'PQC-SLT': {
      title: '슬랫-중간 검사성적서',
      layout: 'slatMidInspection',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'companyHeader' },
        { id: 'basicInfo', type: 'slatBasicInfo' },
        { id: 'inspectionStandard', type: 'slatInspectionStandard' },
        { id: 'inspectionData', type: 'slatInspectionData' },
      ],
      inspectionItems: {
        appearance: [
          { id: 'processing', name: '가공상태', standard: '사용상 해로운 결함이 없을것', method: '육안검사', regulation: 'KS F 4510 5.1항' },
          { id: 'curling', name: '컬링상태', standard: '컬링이 일정하게 성형', method: '육안검사', regulation: 'KS F 4510 9항' },
          { id: 'hooking', name: '후킹상태', standard: '슬랫간 결합이 견고할 것', method: '육안검사', regulation: 'KS F 4510 9항' },
        ],
        dimension: [
          { id: 'length', name: '길이', standard: '도면치수 ± 4', method: '체크검사', unit: 'mm', regulation: 'KS F 4510 7항 표9 인용' },
          { id: 'width', name: '너비', standard: '도면치수 ± 2', method: '체크검사', unit: 'mm', regulation: '자체규정' },
          { id: 'gap', name: '간격', standard: '400 이하', method: 'GONO 게이지', regulation: '자체규정' },
        ]
      },
      approvalLine: [{ role: 'write', department: '판매/전진' }, { role: 'review', department: '생산' }, { role: 'approve', department: '품질' }]
    },
    // 조인트바 중간검사성적서 템플릿
    'PQC-JB': {
      title: '조인트바-중간 검사성적서',
      layout: 'jointBarMidInspection',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'companyHeader' },
        { id: 'basicInfo', type: 'jointBarBasicInfo' },
        { id: 'inspectionStandard', type: 'jointBarInspectionStandard' },
        { id: 'inspectionData', type: 'jointBarInspectionData' },
      ],
      inspectionItems: {
        appearance: [
          { id: 'processing', name: '가공상태', standard: '사용상 해로운 결함이 없을것', method: '육안검사', regulation: 'KS F 4510 5.1항' },
          { id: 'welding', name: '용접상태', standard: '용접부위가 견고할 것', method: '육안검사', regulation: 'KS F 4510 9항' },
          { id: 'assembly', name: '조립상태', standard: '조인트바가 정확히 결합될 것', method: '육안검사', regulation: 'KS F 4510 9항' },
        ],
        dimension: [
          { id: 'length', name: '길이', standard: '도면치수 ± 3', method: '체크검사', unit: 'mm', regulation: 'KS F 4510 7항 표9 인용' },
          { id: 'width', name: '너비', standard: '도면치수 ± 2', method: '체크검사', unit: 'mm', regulation: '자체규정' },
          { id: 'hole', name: '홀위치', standard: '도면치수 ± 1', method: '체크검사', regulation: '자체규정' },
        ]
      },
      approvalLine: [{ role: 'write', department: '판매/전진' }, { role: 'review', department: '생산' }, { role: 'approve', department: '품질' }]
    },
    // 제품검사성적서 템플릿
    'FQC': {
      title: '제품검사성적서',
      layout: 'productInspection',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'companyHeader' },
        { id: 'approvalBox', type: 'approvalTable', roles: ['작성', '승인'], showLine: true },
        {
          id: 'basicInfo', type: 'infoTable', rows: [
            [{ label: '상품명', field: 'productName' }, { label: '제품 LOT NO', field: 'lotNo' }],
            [{ label: '제품명', field: 'itemName' }, { label: '로트크기', field: 'lotSize' }, { label: 'EA', type: 'unit' }],
            [{ label: '발주처', field: 'customerName' }, { label: '검사일자', field: 'inspectionDate' }],
            [{ label: '현장명', field: 'siteName' }, { label: '검사자', field: 'inspector' }],
          ]
        },
        { id: 'productPhoto', type: 'diagramSection', title: '제품사진' },
        { id: 'inspectionTable', type: 'productInspectionTable' },
        { id: 'remarks', type: 'remarksSection', title: '특이사항' },
        { id: 'judgement', type: 'judgementBox', options: ['적합', '부적합'] },
      ],
      inspectionItems: [
        {
          no: 1, category: '겉모양', items: [
            { id: 'processing', name: '가공상태', standard: '사용상 해로운 결함이 없을 것', method: '육안검사', period: '전수검사' },
            { id: 'sewing', name: '재봉상태', standard: '내화실에 의해 견고하게 접합되어야 함', method: '육안검사', period: '전수검사' },
            { id: 'assembly', name: '조립상태', standard: '엔드락이 견고하게 조립되어야 함', method: '육안검사', period: '전수검사' },
            { id: 'smokeBarrier', name: '연기차단재', standard: '연기차단재 설치여부(케이스 W80, 가이드레일 W50(양쪽설치))', method: '육안검사', period: '전수검사' },
            { id: 'bottomFinish', name: '하단마감재', standard: '내부 무게평철 설치 유무', method: '육안검사', period: '전수검사' },
          ]
        },
        {
          no: 2, category: '모터', items: [
            { id: 'motor', name: '', standard: '인정제품과 동일사양', method: '', period: '' },
          ]
        },
        {
          no: 3, category: '재질', items: [
            { id: 'material', name: '', standard: 'WY-SC780 인쇄상태 확인', method: '', period: '' },
          ]
        },
        {
          no: 4, category: '치수\n(오픈사이즈)', items: [
            { id: 'length', name: '길이', standard: '발주치수 ± 30mm', method: '체크검사', period: '전수검사', hasValue: true },
            { id: 'height', name: '높이', standard: '발주치수 ± 30mm', method: '체크검사', period: '전수검사', hasValue: true },
            { id: 'guideRailGap', name: '가이드레일 홈간격', standard: '10 ± 5mm(측정부위: ⓐ 높이 100 이내)', method: '체크검사', period: '전수검사', hasValue: true },
            { id: 'bottomGap', name: '하단마감재간격', standard: '간격 (③+④) 가이드레일과 하단마감재 틈새 25mm 이내', method: '체크검사', period: '전수검사', hasValue: true },
          ]
        },
        {
          no: 5, category: '작동테스트', items: [
            { id: 'operation', name: '개폐성능', standard: '작동 유무 확인(일부 및 완전폐쇄)', method: '', period: '' },
          ]
        },
        {
          no: 6, category: '내화시험', items: [
            { id: 'fire1', name: '비차열성', standard: '6mm 균열게이지 관통 후 150mm 이동 유무', method: '', period: '' },
            { id: 'fire2', name: '', standard: '25mm 균열게이지 관통 유무', method: '', period: '' },
            { id: 'fire3', name: '', standard: '10초 이상 지속되는 화염발생 유무', method: '', period: '' },
          ]
        },
        {
          no: 7, category: '차연시험', items: [
            { id: 'smoke', name: '공기누설량', standard: '25Pa 일때 공기누설량 0.9㎥/min·㎡ 이하', method: '', period: '' },
          ]
        },
        {
          no: 8, category: '개폐시험', items: [
            { id: 'open1', name: '', standard: '개폐의 원활한 작동', method: '', period: '', isCertTest: true },
            { id: 'open2', name: '평균속도', standard: '전도개폐 2.5 ~ 6.5m/min', method: '', period: '', isCertTest: true },
            { id: 'open3', name: '', standard: '자중강하 3 ~ 7m/min', method: '', period: '', isCertTest: true },
            { id: 'open4', name: '', standard: '개폐 시 상부 및 하부 끝부분에서 자동정지', method: '', period: '', isCertTest: true },
            { id: 'open5', name: '', standard: '강하 중 임의의 위치에서 정지', method: '', period: '', isCertTest: true },
          ]
        },
        {
          no: 9, category: '내충격시험', items: [
            { id: 'impact', name: '', standard: '방화상 유해한 파괴, 박리 탈락 유무', method: '', period: '' },
          ]
        },
      ],
      certTestInfo: {
        method: '공인 시험기관\n시험성적서',
        period: '1회 / 5년',
      },
      approvalLine: [{ role: 'write' }, { role: 'approve' }]
    },
    // 세금계산서 템플릿
    'INV': {
      title: '세 금 계 산 서',
      layout: 'taxInvoice',
      showCompanyLogo: false,
      showApprovalBox: false,
      sections: [
        { id: 'header', type: 'taxInvoiceHeader' },
        { id: 'parties', type: 'taxInvoiceParties' },
        { id: 'itemTable', type: 'taxInvoiceTable' },
        { id: 'summary', type: 'taxInvoiceSummary' },
      ],
      approvalLine: []
    },
    // ========== 작업일지 템플릿 ==========
    // 스크린 작업일지
    'WL-SCR': {
      title: '작 업 일 지',
      subtitle: '스크린 생산부서',
      layout: 'workLog',
      showCompanyLogo: true,
      showApprovalBox: true,
      processType: '스크린',
      sections: [
        { id: 'header', type: 'workLogHeader', logo: { text: 'KD', subText: '경동기업' } },
        { id: 'approvalBox', type: 'approvalTable', roles: ['작성', '검토', '승인'], footer: ['판매/전진', '생산', '품질'] },
        { id: 'department', type: 'departmentBox', name: '스크린 생산부서' },
        {
          id: 'orderInfo', type: 'workLogOrderInfo', columns: [
            { section: '신청업체', rows: [['발주일', 'orderDate'], ['업체명', 'company'], ['담당자', 'manager'], ['연락처', 'contact']] },
            { section: '신청내용', rows: [['현장명', 'siteName'], ['작업일자', 'workDate'], ['제품 LOT NO.', 'productLotNo'], ['생산담당자', 'productionManager']] },
          ]
        },
        { id: 'workTable', type: 'screenWorkTable', columns: ['일련번호', '입고 LOT NO.', '제품명', '부호', '가로', '세로', '나머지높이', '1180', '900', '600', '400', '300'] },
        { id: 'materialUsage', type: 'materialUsageTable' },
        { id: 'remarks', type: 'remarksSection' },
      ],
      approvalLine: [{ role: 'write', department: '판매/전진' }, { role: 'review', department: '생산' }, { role: 'approve', department: '품질' }]
    },
    // 슬랫 작업일지
    'WL-SLT': {
      title: '작 업 일 지',
      subtitle: '슬랫 생산부서',
      layout: 'workLog',
      showCompanyLogo: true,
      showApprovalBox: true,
      processType: '슬랫',
      sections: [
        { id: 'header', type: 'workLogHeader', logo: { text: 'KD', subText: '경동기업' } },
        { id: 'approvalBox', type: 'approvalTable', roles: ['작성', '검토', '승인'], footer: ['판매/전진', '생산', '품질'] },
        { id: 'department', type: 'departmentBox', name: '슬랫 생산부서' },
        { id: 'orderInfo', type: 'workLogOrderInfo' },
        { id: 'workTable', type: 'slatWorkTable', columns: ['일련번호', '입고 LOT NO.', '방화유리수량', '가로', '세로', '매수(세로)', '조인트바수량', '코일사용량'] },
        { id: 'summary', type: 'slatSummaryTable' },
        { id: 'remarks', type: 'remarksSection' },
      ],
      approvalLine: [{ role: 'write', department: '판매/전진' }, { role: 'review', department: '생산' }, { role: 'approve', department: '품질' }]
    },
    // 절곡 작업일지
    'WL-FLD': {
      title: '작 업 일 지',
      subtitle: '절곡 생산부서',
      layout: 'workLog',
      showCompanyLogo: true,
      showApprovalBox: true,
      processType: '절곡',
      sections: [
        { id: 'header', type: 'workLogHeader', logo: { text: 'KD', subText: '경동기업' } },
        { id: 'approvalBox', type: 'approvalTable', roles: ['작성', '검토', '승인'], footer: ['판매/전진', '생산', '품질'] },
        { id: 'department', type: 'departmentBox', name: '절곡 생산부서' },
        { id: 'orderInfo', type: 'workLogOrderInfo' },
        { id: 'productInfo', type: 'productInfoTable' },
        { id: 'workTable', type: 'bendingWorkTable', columns: ['세부품명', '재질', '입고 & 생산 LOT NO', '길이/규격', '수량'] },
        { id: 'productionTotal', type: 'productionTotalTable', items: ['SUS', 'EGI'] },
        { id: 'remarks', type: 'remarksSection' },
      ],
      approvalLine: [{ role: 'write', department: '판매/전진' }, { role: 'review', department: '생산' }, { role: 'approve', department: '품질' }]
    },
    // 재고생산 작업일지 (중간검사성적서)
    'WL-STK': {
      title: '절곡품 재고생산 작업일지',
      subtitle: '(중간검사성적서)',
      layout: 'workLog',
      showCompanyLogo: true,
      showApprovalBox: true,
      processType: '재고생산',
      sections: [
        { id: 'header', type: 'workLogHeader', logo: { text: 'KD', subText: '경동기업' }, title: '절곡품 재고생산 작업일지', subtitle: '(중간검사성적서)' },
        { id: 'approvalBox', type: 'approvalTable', roles: ['작성', '검토', '승인'], footer: ['판매/개발자', '생산', '품질'] },
        { id: 'department', type: 'departmentBox', name: '절곡 생산부서' },
        {
          id: 'productInfo', type: 'stockProductInfoTable', rows: [
            [{ label: '품명', field: 'productName' }, { label: '규격', field: 'spec' }, { label: '길이', field: 'length' }],
            [{ label: '입고 LOT NO', field: 'inboundLotNo' }, { label: '생산 LOT NO', field: 'productLotNo' }, { label: '로트크기', field: 'lotSize' }],
          ]
        },
        { id: 'inspectionStandard', type: 'inspectionStandardSection', title: '■ 중간검사 기준서', hasDrawing: true },
        { id: 'inspectionData', type: 'stockInspectionTable', columns: ['검사항목', '겉모양/절곡상태', '길이', '너비', '간격', '판정'] },
        { id: 'finalJudgement', type: 'finalJudgementBox', options: ['합격', '불합격'] },
        { id: 'inspectorInfo', type: 'inspectorInfoTable' },
      ],
      inspectionItems: [
        { id: 'appearance', name: '겉모양/절곡상태', method: '육안검사', standard: '이상무' },
        { id: 'length', name: '길이', method: '버니어캘리퍼스', standard: '2500±3' },
        { id: 'width', name: '너비', method: '버니어캘리퍼스', standard: '120±1' },
        { id: 'interval', name: '간격', method: '버니어캘리퍼스', standard: '14±0.5' },
      ],
      approvalLine: [{ role: 'write', department: '판매/개발자' }, { role: 'review', department: '생산' }, { role: 'approve', department: '품질' }]
    },
    // 출고증 템플릿
    'SHP': {
      title: '출 고 증',
      layout: 'shipment',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'shipmentHeader' },
        { id: 'approvalBox', type: 'approvalTable', roles: ['작성', '검토', '승인'] },
        { id: 'productInfo', type: 'shipmentProductInfo' },
        { id: 'orderInfo', type: 'shipmentOrderInfo' },
        { id: 'deliveryInfo', type: 'shipmentDeliveryInfo' },
        { id: 'itemTable', type: 'shipmentItemTable' },
        { id: 'remarks', type: 'remarksSection' },
      ],
      approvalLine: [{ role: 'write', department: '판매/전진' }, { role: 'review', department: '출하' }, { role: 'approve', department: '생산관리' }]
    },
    // 거래명세서 템플릿 (물류)
    'TXS': {
      title: '거 래 명 세 서',
      layout: 'transactionStatement',
      showCompanyLogo: true,
      showApprovalBox: false,
      sections: [
        { id: 'header', type: 'titleHeader' },
        { id: 'tradeInfo', type: 'twoColumnTable' },
        { id: 'itemTable', type: 'productTable' },
        { id: 'summary', type: 'amountSummary' },
      ],
      approvalLine: []
    },
    // 납품확인서 템플릿
    'DC': {
      title: '납 품 확 인 서',
      layout: 'deliveryConfirmation',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'kdHeader' },
        { id: 'approvalBox', type: 'approvalTable', roles: ['작성', '검토', '승인'] },
        { id: 'orderInfo', type: 'deliveryOrderInfo' },
        { id: 'deliveryInfo', type: 'deliveryDeliveryInfo' },
        { id: 'itemTable', type: 'deliveryItemTable' },
        { id: 'remarks', type: 'remarksSection' },
        { id: 'signature', type: 'deliverySignature' },
      ],
      approvalLine: [{ role: 'write', department: '판매/전진' }, { role: 'review', department: '출하' }, { role: 'approve', department: '품질' }]
    },
    // 출고증 템플릿 (작업일지 스타일)
    'TS': {
      title: '출 고 증',
      layout: 'worklogStyle',
      showCompanyLogo: true,
      showApprovalBox: true,
      sections: [
        { id: 'header', type: 'kdHeader' },
        { id: 'approvalBox', type: 'approvalTable', roles: ['작성', '검토', '승인'] },
        { id: 'headerInfo', type: 'threeColumnHeader', columns: ['신청업체', '신청내용', '납품정보'] },
        { id: 'materialsTable', type: 'tsTable', title: '부자재' },
        { id: 'motorsTable', type: 'tsTable', title: '모터' },
        { id: 'slatTable', type: 'tsTable', title: '슬랫' },
        { id: 'foldingTable', type: 'tsTable', title: '절곡품', hasLotNo: true },
        { id: 'consumablesTable', type: 'tsTable', title: '소모품' },
      ],
      approvalLine: [{ role: 'write', department: '판매/전진' }, { role: 'review', department: '출하' }, { role: 'approve', department: '생산관리' }]
    },
  };

  // 문서 카테고리 정의
  const documentCategories = [
    { id: 'sales', code: 'SALES', name: '판매문서', icon: '📋', description: '견적서, 수주확인서 등', sortOrder: 1 },
    { id: 'production', code: 'PROD', name: '생산문서', icon: '🏭', description: '작업지시서, 발주서 등', sortOrder: 2 },
    { id: 'quality', code: 'QC', name: '품질문서', icon: '✅', description: '검사성적서, 부적합보고서 등', sortOrder: 3 },
    { id: 'logistics', code: 'LOGI', name: '물류문서', icon: '🚚', description: '입출고전표, 배송지시서 등', sortOrder: 4 },
    { id: 'accounting', code: 'ACC', name: '회계문서', icon: '💰', description: '세금계산서, 거래명세서 등', sortOrder: 5 },
  ];

  // 문서 유형 정의 (documentTemplateConfig에서 가져와서 연동)
  // 공정 등록 페이지의 작업일지 양식 드롭다운과 동일한 데이터 소스 사용
  const documentTypes = (documentTemplateConfig.documentTypes || []).map(doc => ({
    ...doc,
    hasTemplate: ['QT', 'QT-DTL', 'SO', 'SL', 'WO', 'WO-SCR', 'WO-SLT', 'WO-FLD', 'IQC', 'PQC', 'PQC-SCR', 'PQC-BND', 'PQC-SLT', 'PQC-JB', 'FQC', 'INV', 'WL-SCR', 'WL-SLT', 'WL-FLD', 'WL-STK', 'WL-PKG', 'DC', 'FQC-REQ', 'TS'].includes(doc.code),
  }));

  // 결재 역할
  const approvalRoles = [
    { id: 'write', name: '작성', sortOrder: 1 },
    { id: 'review', name: '검토', sortOrder: 2 },
    { id: 'approve', name: '승인', sortOrder: 3 },
    { id: 'confirm', name: '확인', sortOrder: 4 },
  ];

  // 회사 기본 정보
  const companyInfo = {
    name: '경동기업',
    nameEn: 'KYUNGDONG COMPANY',
    businessNo: '135-86-12345',
    ceo: '김 대 표',
    address: '경기도 안성시 공업용지 오성길 45-22',
    phone: '031-983-5130',
    fax: '031-983-5131',
    businessType: '제조업',
    businessItem: '방화셔터, 스크린셔터, 방화문',
  };
  const [activeTab, setActiveTab] = useState('template');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [selectedDocType, setSelectedDocType] = useState(null);
  const [showPreviewModal, setShowPreviewModal] = useState(false);
  const [showTemplateEditor, setShowTemplateEditor] = useState(false);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editorMode, setEditorMode] = useState('view'); // 'view', 'edit', 'create'

  // 통합 문서 등록을 위한 섹션 타입 정의
  const sectionTypeOptions = [
    { id: 'header', name: '문서헤더', description: '문서 제목, 번호, 일자', icon: 'FileText' },
    { id: 'partyInfo', name: '당사자정보', description: '수요자/공급자 정보 테이블', icon: 'Users' },
    { id: 'infoTable', name: '정보테이블', description: '라벨-값 형식 테이블', icon: 'Table' },
    { id: 'amountBox', name: '금액박스', description: '총 금액 강조 표시', icon: 'DollarSign' },
    { id: 'productTable', name: '품목테이블', description: '품목/수량/단가/금액', icon: 'Package' },
    { id: 'inspectionTable', name: '검사테이블', description: '검사항목/기준/결과', icon: 'ShieldCheck' },
    { id: 'remarks', name: '비고사항', description: '비고/특이사항 영역', icon: 'Edit' },
    { id: 'signature', name: '서명/인감', description: '날짜, 회사명, 인감', icon: 'CheckCircle' },
    { id: 'approval', name: '결재란', description: '결재선 (작성/검토/승인)', icon: 'Users' },
    { id: 'judgement', name: '판정', description: '합격/불합격 판정', icon: 'CheckSquare' },
    { id: 'diagram', name: '도면/사진', description: '제품 도면 또는 사진', icon: 'Image' },
  ];

  // 템플릿 편집 상태
  const [templateForm, setTemplateForm] = useState({
    title: '',
    code: '',
    category: 'sales',
    description: '',
    paperSize: 'A4',
    orientation: 'portrait',
    showCompanyLogo: true,
    showApprovalBox: false,
    approvalLines: [],
    sections: [],
    inspectionItems: [
      { no: 1, item: '외관검사', standard: '육안검사', method: '목시', value: '', judgement: '' },
      { no: 2, item: '치수검사', standard: '도면 기준', method: '버니어캘리퍼스', value: '', judgement: '' },
      { no: 3, item: '재질검사', standard: '성적서 확인', method: '서류확인', value: '', judgement: '' },
    ],
    productItems: [
      { no: 1, name: '', spec: '', unit: 'EA', qty: '', price: '', amount: '', remark: '' },
    ],
    remarks: '',
    judgementOptions: ['합격', '불합격', '조건부합격'],
  });

  // 섹션 추가
  const handleAddSection = (sectionType) => {
    const newSection = {
      id: `section_${Date.now()}`,
      type: sectionType.id,
      typeName: sectionType.name,
      config: {},
      sortOrder: templateForm.sections.length + 1,
    };
    setTemplateForm(prev => ({
      ...prev,
      sections: [...prev.sections, newSection]
    }));
  };

  // 섹션 삭제
  const handleRemoveSection = (sectionId) => {
    setTemplateForm(prev => ({
      ...prev,
      sections: prev.sections.filter(s => s.id !== sectionId).map((s, i) => ({ ...s, sortOrder: i + 1 }))
    }));
  };

  // 섹션 순서 변경 (위로)
  const handleMoveSectionUp = (index) => {
    if (index === 0) return;
    const newSections = [...templateForm.sections];
    [newSections[index - 1], newSections[index]] = [newSections[index], newSections[index - 1]];
    setTemplateForm(prev => ({
      ...prev,
      sections: newSections.map((s, i) => ({ ...s, sortOrder: i + 1 }))
    }));
  };

  // 섹션 순서 변경 (아래로)
  const handleMoveSectionDown = (index) => {
    if (index === templateForm.sections.length - 1) return;
    const newSections = [...templateForm.sections];
    [newSections[index], newSections[index + 1]] = [newSections[index + 1], newSections[index]];
    setTemplateForm(prev => ({
      ...prev,
      sections: newSections.map((s, i) => ({ ...s, sortOrder: i + 1 }))
    }));
  };

  // 새 문서양식 생성 모달 열기
  const handleOpenCreateModal = () => {
    setTemplateForm({
      title: '',
      code: '',
      category: 'sales',
      description: '',
      paperSize: 'A4',
      orientation: 'portrait',
      showCompanyLogo: true,
      showApprovalBox: false,
      approvalLines: [],
      sections: [],
      inspectionItems: [],
      productItems: [],
      remarks: '',
      judgementOptions: ['합격', '불합격'],
    });
    setEditorMode('create');
    setShowCreateModal(true);
  };

  // 템플릿 저장
  const handleSaveTemplate = () => {
    console.log('저장할 템플릿:', templateForm);
    alert(`문서양식 "${templateForm.title}" 이(가) 저장되었습니다.`);
    setShowCreateModal(false);
    setEditorMode('view');
  };

  // 샘플 데이터 (미리보기용)
  const sampleData = {
    docNo: 'KD-PR-251209-01',
    docDate: '2025.12.09',
    customerName: '삼성물산(주)',
    customerCeo: '홍 길 동',
    customerBusinessNo: '123-45-67890',
    customerAddress: '서울시 강남구 삼성동 123',
    customerPhone: '02-1234-5678',
    siteName: '용신고등학교(4층)',
    siteAddress: '서울시 강남구 삼성동 456',
    itemName: '스크린 방화셔터',
    spec: '와이어 클라스 코팅직물',
    openSize: 'W3000 x H2500',
    makeSize: 'W3100 x H2600',
    caseSize: 'W3100 x D300 x H350',
    qty: '11',
    dueDate: '2025.12.20',
    totalAmount: '12,500,000',
    supplyAmount: '11,363,636',
    taxAmount: '1,136,364',
    lotNo: 'KD-WE-251015-01-(3)',
    lotSize: '11',
    inspectionDate: '2025.',
    orderNo: 'KD-TS-251209-01',
    orderDate: '2025.12.05',
    supplierName: '주일',
    inspector: '',
    // 중간검사 스크린용 샘플 데이터
    screenInspectionData: [
      { no: '01', processing: null, sewing: null, assembly: null, lengthSpec: '7,400', lengthVal: '', heightSpec: '2,950', heightVal: '', intervalStd: '400 이하', intervalOK: null, intervalNG: null, judgement: null },
      { no: '02', processing: null, sewing: null, assembly: null, lengthSpec: '4,700', lengthVal: '', heightSpec: '2,950', heightVal: '', intervalStd: '400 이하', intervalOK: null, intervalNG: null, judgement: null },
      { no: '03', processing: null, sewing: null, assembly: null, lengthSpec: '6,790', lengthVal: '', heightSpec: '2,950', heightVal: '', intervalStd: '400 이하', intervalOK: null, intervalNG: null, judgement: null },
      { no: '04', processing: null, sewing: null, assembly: null, lengthSpec: '3,700', lengthVal: '', heightSpec: '2,950', heightVal: '', intervalStd: '400 이하', intervalOK: null, intervalNG: null, judgement: null },
      { no: '05', processing: null, sewing: null, assembly: null, lengthSpec: '6,000', lengthVal: '', heightSpec: '2,950', heightVal: '', intervalStd: '400 이하', intervalOK: null, intervalNG: null, judgement: null },
      { no: '06', processing: null, sewing: null, assembly: null, lengthSpec: '7,300', lengthVal: '', heightSpec: '2,950', heightVal: '', intervalStd: '400 이하', intervalOK: null, intervalNG: null, judgement: null },
      { no: '07', processing: null, sewing: null, assembly: null, lengthSpec: '3,700', lengthVal: '', heightSpec: '2,950', heightVal: '', intervalStd: '400 이하', intervalOK: null, intervalNG: null, judgement: null },
    ],
    // 중간검사 절곡품용 샘플 데이터
    bendingInspectionData: {
      productName: 'KWE01',
      finishType: 'SUS마감',
      items: [
        { category: 'KWE01', name: '가이드레일', type: '벽면형', bendingOK: null, bendingNG: null, lengthSpec: '3,000', lengthVal: '', widthSpec: 'N/A', widthVal: 'N/A', points: [{ id: 1, spec: 30 }, { id: 2, spec: 80 }, { id: 3, spec: 45 }, { id: 4, spec: 40 }, { id: 5, spec: 34 }] },
        { category: 'KWE01', name: '케이스', type: '500*380', bendingOK: null, bendingNG: null, lengthSpec: '3,000', lengthVal: '', widthSpec: 'N/A', widthVal: 'N/A', points: [{ id: 1, spec: 380 }, { id: 2, spec: 50 }, { id: 3, spec: 240 }, { id: 4, spec: 50 }] },
        { category: 'KWE01', name: '하단마감재', type: '60x40', bendingOK: null, bendingNG: null, lengthSpec: '3,000', lengthVal: '', widthSpec: 'N/A', widthVal: 'N/A', points: [{ id: 1, spec: 60 }, { id: 2, spec: 64 }] },
        { category: 'KWE01', name: '하단 L-BAR', type: '17x60', bendingOK: null, bendingNG: null, lengthSpec: '3,000', lengthVal: '', widthSpec: 'N/A', widthVal: 'N/A', points: [{ id: 1, spec: 17 }] },
        { category: 'KWE01', name: '연기차단재', type: 'W50\n(가이드레일용)', bendingOK: null, bendingNG: null, lengthSpec: '3,000', lengthVal: '', widthSpec: '① 50', widthVal: '', points: [{ id: 2, spec: 12 }] },
        { category: 'KWE01', name: '연기차단재', type: 'W80\n(케이스용)', bendingOK: null, bendingNG: null, lengthSpec: '3,000', lengthVal: '', widthSpec: '① 80', widthVal: '', points: [{ id: 2, spec: 12 }] },
      ]
    },
    // 제품검사 샘플 데이터
    productInspectionData: {
      productName: '스크린 방화셔터',
      itemName: 'KWE01',
      inspectionItems: [
        {
          no: 1, category: '겉모양', items: [
            { name: '가공상태', result: null },
            { name: '재봉상태', result: null },
            { name: '조립상태', result: null },
            { name: '연기차단재', result: null },
            { name: '하단마감재', result: null },
          ]
        },
        { no: 2, category: '모터', items: [{ name: '', result: null }] },
        { no: 3, category: '재질', items: [{ name: '', result: null }] },
        {
          no: 4, category: '치수(오픈사이즈)', items: [
            { name: '길이', result: null, value: '' },
            { name: '높이', result: null, value: '' },
            { name: '가이드레일 홈간격', result: null, value: '' },
            { name: '하단마감재간격', result: null, value: '' },
          ]
        },
        { no: 5, category: '작동테스트', items: [{ name: '개폐성능', result: null }] },
        {
          no: 6, category: '내화시험', items: [
            { name: '비차열성', result: null },
            { name: '', result: null },
            { name: '', result: null },
          ]
        },
        { no: 7, category: '차연시험', items: [{ name: '공기누설량', result: null }] },
        {
          no: 8, category: '개폐시험', items: [
            { name: '', result: null },
            { name: '평균속도', result: null },
            { name: '', result: null },
            { name: '', result: null },
            { name: '', result: null },
          ]
        },
        { no: 9, category: '내충격시험', items: [{ name: '', result: null }] },
      ],
    },
    // 수입검사 샘플 데이터
    incomingInspectionData: {
      itemName: '전기 아연도금 강판\n(KS D 3528, SECC) "EGI 절곡판"',
      supplierName: '지오TNS\n(KG스틸)',
      spec: '1.55 * 1218 * 480',
      specDetail: { thickness: 1.55, width: 1218, length: 480 },
      lotNo: '250715-02',
      materialNo: 'PE02RB',
      lotSize: '200',
      lotUnit: '매',
      inspectionDate: '07/15',
      receiveDate: '2025-07-15',
      inspector: '노완호',
      approver: '노완호',
      approvalDate: '07/15',
      items: [
        { no: 1, category: '겉모양', standard: '사용상 해로운 결함이 없을 것', method: '육안검사', period: '', n1: 'OK', n2: 'OK', n3: 'OK', result: '적' },
        {
          no: 2, category: '치수', subItems: [
            { name: '두께', spec: 1.55, selectedRange: '1.25 이상 ~ 1.6 미만', tolerance: '± 0.10', n1: 1.528, n2: 1.533, n3: 1.521, result: '적' },
            { name: '너비', spec: 1219, selectedRange: '1250 미만', tolerance: '+7/-0', n1: 1222, n2: 1222, n3: 1222, result: '적' },
            { name: '길이', spec: 480, selectedRange: '1250 미만', tolerance: '+10/-0', n1: 480, n2: 480, n3: 480, result: '적' },
          ], method: '체크검사', period: 'n=3\nc=0'
        },
        { no: 3, category: '인장강도 (N/㎟)', standard: '270 이상', method: '', period: '', n1: 313.8, n2: '', n3: '', result: '적' },
        { no: 4, category: '연신율\n%', selectedRange: '두께 1.0 이상 ~ 1.6 미만', standard: '37 이상', method: '공급업체\n밀시트', period: '입고시', n1: 46.5, n2: '', n3: '', result: '적' },
        { no: 5, category: '아연의 최소\n부착량 (g/㎡)', standard: '한면 17 이상', method: '', period: '', n1: '17.21 / 17.17', n2: '', n3: '', result: '적' },
      ],
      remarks: [
        '# 1.55mm의 경우 KS F 4510에 따른 MIN 1.5의 기준에 따름',
        '# 두께의 경우 너비 1000 이상 ~ 1250 미만 기준에 따름',
      ],
      overallJudgement: '합격',
    },
  };

  // 필터링된 문서 유형
  const filteredDocTypes = selectedCategory === 'all'
    ? documentTypes
    : documentTypes.filter(dt => dt.category === selectedCategory);

  // 문서 유형 선택
  const handleSelectDocType = (docType) => {
    setSelectedDocType(docType);
    const template = documentTemplates[docType.code];
    if (template) {
      setTemplateForm({
        title: template.title,
        approvalLines: template.approvalLine || [],
        inspectionItems: [
          { no: 1, item: '외관검사', standard: '육안검사', method: '목시', value: '', judgement: '' },
          { no: 2, item: '치수검사', standard: '도면 기준', method: '버니어캘리퍼스', value: '', judgement: '' },
          { no: 3, item: '재질검사', standard: '성적서 확인', method: '서류확인', value: '', judgement: '' },
        ],
        productItems: [
          { no: 1, name: '', spec: '', unit: 'EA', qty: '', price: '', amount: '', remark: '' },
        ],
        remarks: '',
        judgementOptions: ['합격', '불합격', '조건부합격'],
      });
    }
    setShowPreviewModal(true);
  };

  // 결재자 추가
  const handleAddApprovalLine = () => {
    setTemplateForm(prev => ({
      ...prev,
      approvalLines: [...prev.approvalLines, { role: 'review', department: '', name: '' }]
    }));
  };

  // 결재자 삭제
  const handleRemoveApprovalLine = (index) => {
    setTemplateForm(prev => ({
      ...prev,
      approvalLines: prev.approvalLines.filter((_, i) => i !== index)
    }));
  };

  // 검사항목 추가
  const handleAddInspectionItem = () => {
    setTemplateForm(prev => ({
      ...prev,
      inspectionItems: [...prev.inspectionItems, {
        no: prev.inspectionItems.length + 1,
        item: '', standard: '', method: '', value: '', judgement: ''
      }]
    }));
  };

  // 검사항목 삭제
  const handleRemoveInspectionItem = (index) => {
    setTemplateForm(prev => ({
      ...prev,
      inspectionItems: prev.inspectionItems.filter((_, i) => i !== index).map((item, i) => ({ ...item, no: i + 1 }))
    }));
  };

  // 품목 추가
  const handleAddProductItem = () => {
    setTemplateForm(prev => ({
      ...prev,
      productItems: [...prev.productItems, {
        no: prev.productItems.length + 1,
        name: '', spec: '', unit: 'EA', qty: '', price: '', amount: '', remark: ''
      }]
    }));
  };

  // 품목 삭제
  const handleRemoveProductItem = (index) => {
    setTemplateForm(prev => ({
      ...prev,
      productItems: prev.productItems.filter((_, i) => i !== index).map((item, i) => ({ ...item, no: i + 1 }))
    }));
  };

  // 탭 정의
  const tabs = [
    { id: 'template', label: '문서유형', icon: 'FileText' },
    { id: 'preview', label: '미리보기', icon: 'Eye' },
  ];

  // 문서별 미리보기 렌더러
  const renderDocumentPreview = (docCode) => {
    const template = documentTemplates[docCode];
    if (!template) return <div className="text-center text-gray-500 py-8">템플릿이 정의되지 않았습니다.</div>;

    // ========== 공통 렌더링 함수들 ==========

    // 1. KD 로고 헤더 공통 렌더러
    const renderKDHeader = (title, departmentName, approvalData = {}, options = {}) => (
      <table className="w-full border-collapse mb-2" style={{ border: '2px solid black' }}>
        <tbody>
          <tr>
            {/* KD 로고 - 100% 공통 */}
            <td rowSpan="4" className="text-center align-middle p-2" style={{ width: '100px', borderRight: '1px solid black' }}>
              <div className={`text-2xl font-black ${options.logoColor || ''}`}>KD</div>
              <div className="text-xs font-bold">경동기업</div>
              <div style={{ fontSize: '8px' }} className="text-gray-500">{options.subTitle || 'KYUNGDONG COMPANY'}</div>
            </td>
            {/* 제목 - 부서명 없으면 4행 병합, 있으면 2행 병합 */}
            <td rowSpan={departmentName ? 2 : 4} className="text-center align-middle" style={{ width: '45%', borderRight: '1px solid black', borderBottom: departmentName ? '1px solid black' : 'none' }}>
              <div className="text-2xl font-black tracking-widest">{title}</div>
              {options.subtitle && <div className="text-base text-gray-600 mt-1">{options.subtitle}</div>}
            </td>
            {/* 결재 라벨 */}
            <td rowSpan="4" className="text-center align-middle" style={{ width: '30px', borderRight: '1px solid black' }}>
              <div className="text-xs font-bold">결</div>
              <div className="text-xs font-bold mt-4">재</div>
            </td>
            {/* 결재란 헤더 */}
            <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>작성</td>
            <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검토</td>
            <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderBottom: '1px solid black' }}>승인</td>
          </tr>
          <tr>
            {/* 결재란 서명 영역 - 이름만 표시 */}
            <td className="text-center py-1" style={{ height: '50px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
              <div className="text-base font-bold">{approvalData.writer || ''}</div>
            </td>
            <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
              <div className="text-base font-bold">{approvalData.reviewer || ''}</div>
            </td>
            <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}>
              <div className="text-base font-bold">{approvalData.approver || ''}</div>
            </td>
          </tr>
          <tr>
            {/* 부서명 - 값이 있을 때만 렌더링 */}
            {departmentName && (
              <td rowSpan="2" className="text-center py-2 font-bold align-middle bg-gray-200" style={{ borderRight: '1px solid black' }}>
                {departmentName}
              </td>
            )}
            <td className="text-center py-1 text-xs" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{approvalData.writerDept || '판매/전진'}</td>
            <td className="text-center py-1 text-xs" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{approvalData.reviewerDept || '생산'}</td>
            <td className="text-center py-1 text-xs font-semibold" style={{ borderBottom: '1px solid black' }}>{approvalData.approverDept || '품질'}</td>
          </tr>
        </tbody>
      </table>
    );

    // 2. 신청업체/신청내용 테이블 공통 렌더러
    const renderRequestInfoTable = (data, options = {}) => (
      <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
        <tbody>
          <tr>
            <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '50%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>신 청 업 체</td>
            <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '50%', borderBottom: '1px solid black' }}>신 청 내 용</td>
          </tr>
          <tr>
            <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 일</td>
            <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{data.orderDate}</td>
            <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '80px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>현 장 명</td>
            <td className={`px-2 py-1.5 font-bold ${options.siteNameColor || ''}`} style={{ borderBottom: '1px solid black' }}>{data.siteName}</td>
          </tr>
          <tr>
            <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>업 체 명</td>
            <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{data.customerName}</td>
            <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>작업일자</td>
            <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}>{data.workDate}</td>
          </tr>
          <tr>
            <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>담 당 자</td>
            <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{data.managerName}</td>
            <td className="text-center bg-yellow-300 py-1.5 font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>제품 LOT NO.</td>
            <td className="px-2 py-1.5 font-bold" style={{ borderBottom: '1px solid black' }}>{data.lotNo}</td>
          </tr>
          <tr>
            <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black' }}>연 락 처</td>
            <td className="px-2 py-1.5" style={{ borderRight: '1px solid black' }}>{data.phone || ''}</td>
            <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black' }}>생산담당자</td>
            <td className="px-2 py-1.5">{data.productionManager || ''}</td>
          </tr>
          {/* 제품명/마감유형 추가 행 (옵션) */}
          {options.showProductInfo && (
            <tr>
              <td className="text-center bg-gray-200 py-1.5 font-bold" style={{ borderRight: '1px solid black', borderTop: '1px solid black' }}>제품명</td>
              <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderTop: '1px solid black' }}>
                <span className="font-bold">{data.productCode}</span>
                <span className="ml-4 font-bold">{data.productName}</span>
              </td>
              <td className="text-center bg-gray-200 py-1.5 font-bold" style={{ borderRight: '1px solid black', borderTop: '1px solid black' }}>마감유형</td>
              <td className="px-2 py-1.5" style={{ borderTop: '1px solid black' }}>
                <span className="font-bold text-red-600">{data.finishType}</span>
                <span className="ml-4 font-bold text-red-600">{data.finishSpec}</span>
              </td>
            </tr>
          )}
        </tbody>
      </table>
    );

    // 3. 출고증 헤더 렌더러 (로트번호 포함)
    const renderShipmentHeader = (title, departmentName, data, approvalData = {}) => (
      <table className="w-full border-collapse mb-2" style={{ border: '2px solid black' }}>
        <tbody>
          <tr>
            <td rowSpan="4" className="text-center align-middle p-2" style={{ width: '100px', borderRight: '1px solid black' }}>
              <div className="text-2xl font-black text-blue-700">KD</div>
              <div className="text-xs font-bold">경동기업</div>
              <div style={{ fontSize: '8px' }} className="text-gray-500">KYUNGDONG COMPANY</div>
            </td>
            <td rowSpan="2" className="text-center align-middle" style={{ width: '45%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
              <div className="text-2xl font-black tracking-widest">{title}</div>
            </td>
            <td className="text-center text-xs py-1 bg-gray-50" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>로트번호</td>
            <td className="px-2 py-1 font-bold" style={{ borderBottom: '1px solid black' }}>{data.lotNo}</td>
          </tr>
          <tr>
            <td rowSpan="3" className="text-center align-middle" style={{ borderRight: '1px solid black' }}>
              <div className="text-xs font-bold">결</div>
              <div className="text-xs font-bold mt-4">재</div>
            </td>
            <td style={{ padding: 0 }}>
              <table className="w-full border-collapse">
                <tbody>
                  <tr>
                    <td className="text-center text-xs font-semibold py-1" style={{ width: '33%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>작성</td>
                    <td className="text-center text-xs font-semibold py-1" style={{ width: '33%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검토</td>
                    <td className="text-center text-xs font-semibold py-1" style={{ borderBottom: '1px solid black' }}>승인</td>
                  </tr>
                  <tr>
                    <td className="text-center py-3 text-base font-bold text-blue-600" style={{ height: '40px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>{approvalData.writer || ''}</td>
                    <td className="text-center py-3" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{approvalData.reviewer || ''}</td>
                    <td className="text-center py-3" style={{ borderBottom: '1px solid black' }}>{approvalData.approver || ''}</td>
                  </tr>
                  <tr>
                    <td className="text-center py-1 text-xs" style={{ borderRight: '1px solid black' }}>{approvalData.writerDept || '판매/전진'}</td>
                    <td className="text-center py-1 text-xs" style={{ borderRight: '1px solid black' }}>{approvalData.reviewerDept || '출하'}</td>
                    <td className="text-center py-1 text-xs bg-yellow-100">{approvalData.approverDept || '생산관리'}</td>
                  </tr>
                </tbody>
              </table>
            </td>
          </tr>
          <tr>
            <td className="text-center py-2 bg-gray-200 font-bold align-middle" style={{ borderRight: '1px solid black' }}>
              {departmentName}
            </td>
          </tr>
        </tbody>
      </table>
    );

    // ========== 문서별 미리보기 렌더링 ==========

    // 견적서 미리보기 (새로운 디자인 - 2025.02 업데이트)
    if (docCode === 'QT') {
      const qtSampleData = {
        docNo: 'KD-PR-250215-01',
        docDate: '2025년 02월 15일',
        customerName: '현대개발(주)',
        siteName: '연수 오피스텔',
        productName: 'ST-001',
        contactPerson: '홍길동',
        contactPhone: '010-1234-5678',
        totalAmount: 35000000,
        supplyAmount: 51600000,
        remarks: '오피스텔 신축 공사',
        items: [
          { no: 1, name: '가이드레일 상판', spec: '본관1층', qty: 100.00, unit: 'M', unitPrice: 85000, amount: 8500000 },
          { no: 2, name: '가이드레일 하판', spec: '본관1층', qty: 100.00, unit: 'M', unitPrice: 85000, amount: 8500000 },
          { no: 3, name: '셔터 세트', spec: '별관', qty: 30, unit: 'SET', unitPrice: 450000, amount: 13500000 },
          { no: 4, name: '알루미늄 프레임', spec: '지하주차장', qty: 80.00, unit: 'M', unitPrice: 120000, amount: 9600000 },
          { no: 5, name: 'DC 모터', spec: '전동식', qty: 50, unit: 'EA', unitPrice: 230000, amount: 11500000 },
        ]
      };
      return (
        <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '15mm' }}>
          {/* 제목 */}
          <div className="text-center mb-6">
            <h1 className="text-3xl font-bold tracking-[0.8em] mb-4">견 적 서</h1>
            <div className="text-sm text-gray-600">
              문서번호: {qtSampleData.docNo} | 작성일자: {qtSampleData.docDate}
            </div>
          </div>

          <hr className="border-t-2 border-gray-300 mb-8" />

          {/* 수요자 정보 */}
          <div className="mb-6">
            <table className="w-full border-collapse border border-black text-sm">
              <thead>
                <tr>
                  <th colSpan={4} className="border border-black bg-white py-2 text-center font-bold tracking-widest">수 요 자</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 w-24 text-center font-medium">업체명</th>
                  <td className="border border-black px-3 py-2" colSpan={3}>{qtSampleData.customerName}</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">현장명</th>
                  <td className="border border-black px-3 py-2">{qtSampleData.siteName}</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 w-20 text-center font-medium">담당자</th>
                  <td className="border border-black px-3 py-2 w-32">{qtSampleData.contactPerson}</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">제품명</th>
                  <td className="border border-black px-3 py-2">{qtSampleData.productName}</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">연락처</th>
                  <td className="border border-black px-3 py-2">{qtSampleData.contactPhone}</td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 공급자 정보 */}
          <div className="mb-8">
            <table className="w-full border-collapse border border-black text-sm">
              <thead>
                <tr>
                  <th colSpan={4} className="border border-black bg-white py-2 text-center font-bold tracking-widest">공 급 자</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 w-28 text-center font-medium">상호</th>
                  <td className="border border-black px-3 py-2">(주)염진건설</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 w-28 text-center font-medium">사업자등록번호</th>
                  <td className="border border-black px-3 py-2">139-87-00353</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">대표자</th>
                  <td className="border border-black px-3 py-2">김 용 진</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">업태</th>
                  <td className="border border-black px-3 py-2">제조</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">종목</th>
                  <td className="border border-black px-3 py-2" colSpan={3}>방창, 셔터, 금속창호</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">사업장주소</th>
                  <td className="border border-black px-3 py-2" colSpan={3}>경기도 안성시 공업용지 오성길 45-22</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">전화</th>
                  <td className="border border-black px-3 py-2">031-983-5130</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">팩스</th>
                  <td className="border border-black px-3 py-2">02-6911-6315</td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 총 견적금액 박스 */}
          <div className="border-2 border-black p-6 mb-8 text-center">
            <div className="text-lg font-medium mb-3">총 견적금액</div>
            <div className="text-4xl font-bold mb-3">₩ {qtSampleData.totalAmount.toLocaleString()}</div>
            <div className="text-sm text-gray-600">※ 부가가치세 별도</div>
          </div>

          {/* 세부산출내역 */}
          <div className="mb-8">
            <div className="bg-black text-white px-4 py-2 text-center font-bold tracking-[0.5em]">
              세 부 산 출 내 역
            </div>
            <table className="w-full border-collapse border-2 border-t-0 border-black text-sm">
              <thead>
                <tr className="bg-gray-50">
                  <th className="border border-black px-2 py-2 w-12 text-center">No.</th>
                  <th className="border border-black px-3 py-2 text-center">품목명</th>
                  <th className="border border-black px-3 py-2 w-28 text-center">규격</th>
                  <th className="border border-black px-2 py-2 w-20 text-center">수량</th>
                  <th className="border border-black px-2 py-2 w-14 text-center">단위</th>
                  <th className="border border-black px-2 py-2 w-24 text-center">단가</th>
                  <th className="border border-black px-2 py-2 w-28 text-center">금액</th>
                </tr>
              </thead>
              <tbody>
                {qtSampleData.items.map((item) => (
                  <tr key={item.no}>
                    <td className="border border-black px-2 py-2 text-center">{item.no}</td>
                    <td className="border border-black px-3 py-2">{item.name}</td>
                    <td className="border border-black px-3 py-2 text-center">{item.spec}</td>
                    <td className="border border-black px-2 py-2 text-right">{item.qty.toLocaleString()}</td>
                    <td className="border border-black px-2 py-2 text-center">{item.unit}</td>
                    <td className="border border-black px-2 py-2 text-right">{item.unitPrice.toLocaleString()}</td>
                    <td className="border border-black px-2 py-2 text-right">{item.amount.toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
              <tfoot>
                <tr className="bg-gray-100 font-bold">
                  <td colSpan={6} className="border border-black px-3 py-2 text-right">공급가액 합계</td>
                  <td className="border border-black px-2 py-2 text-right">{qtSampleData.supplyAmount.toLocaleString()}</td>
                </tr>
              </tfoot>
            </table>
          </div>

          {/* 비고사항 */}
          <div className="mb-8">
            <div className="bg-black text-white px-4 py-2 text-center font-bold tracking-[0.5em]">
              비 고 사 항
            </div>
            <div className="border-2 border-t-0 border-black p-4 min-h-[80px]">
              <p className="text-sm">{qtSampleData.remarks}</p>
            </div>
          </div>

          {/* 하단 서명 영역 */}
          <div className="flex justify-end items-end mt-8 mb-8">
            <div className="text-right mr-6">
              <p className="text-sm mb-4">상기와 같이 견적합니다.</p>
              <p className="text-sm mb-2 font-bold">{qtSampleData.docDate}</p>
              <p className="text-sm">공급자: (주)염진건설 (인)</p>
            </div>
            <div className="border border-black w-16 h-16 flex items-center justify-center text-xs text-gray-400">
              (인감<br />날인)
            </div>
          </div>

          {/* 유의사항 */}
          <div className="mb-6 text-xs text-gray-700">
            <p className="font-bold mb-2">【 유의사항 】</p>
            <p className="mb-1">1. 본 견적서는 {qtSampleData.docDate} 기준으로 작성되었으며, 자재 가격 변동 시 조정될 수 있습니다.</p>
            <p className="mb-1">2. 견적 유효기간은 발행일로부터 30일이며, 기간 경과 시 재견적이 필요합니다.</p>
            <p className="mb-1">3. 제작 사양 및 수량 변경 시 견적 금액이 변동될 수 있습니다.</p>
            <p className="mb-1">4. 현장 여건에 따라 추가 비용이 발생할 수 있습니다.</p>
          </div>

          {/* 문의 */}
          <div className="text-center text-sm text-gray-600 border-t border-gray-300 pt-4">
            문의: {qtSampleData.contactPerson} | {qtSampleData.contactPhone}
          </div>
        </div>
      );
    }

    // 견적산출내역서 미리보기 (QT-DTL) - 2025.02 업데이트
    if (docCode === 'QT-DTL') {
      const qtDtlSampleData = {
        docNo: 'KD-PR-250215-01',
        docDate: '2025년 02월 15일',
        customerName: '현대개발(주)',
        siteName: '연수 오피스텔',
        productName: 'ST-001',
        contactPerson: '홍길동',
        contactPhone: '010-1234-5678',
        totalAmount: 35000000,
        supplyAmount: 51600000,
        remarks: '오피스텔 신축 공사',
        // 세부산출내역
        items: [
          { no: 1, name: '가이드레일 상판', spec: '본관1층', qty: 100.00, unit: 'M', unitPrice: 85000, amount: 8500000 },
          { no: 2, name: '가이드레일 하판', spec: '본관1층', qty: 100.00, unit: 'M', unitPrice: 85000, amount: 8500000 },
          { no: 3, name: '셔터 세트', spec: '별관', qty: 30, unit: 'SET', unitPrice: 450000, amount: 13500000 },
          { no: 4, name: '알루미늄 프레임', spec: '지하주차장', qty: 80.00, unit: 'M', unitPrice: 120000, amount: 9600000 },
          { no: 5, name: 'DC 모터', spec: '전동식', qty: 50, unit: 'EA', unitPrice: 230000, amount: 11500000 },
        ],
        // 소요자재내역 정보
        productType: '철재',
        productCode: '-',
        openSize: 'W - × H - (mm)',
        makeSize: 'W - × H - (mm)',
        qty: '80 SET',
        caseSize: '1219 × 550 (mm)',
        // 자재 목록
        materials: [
          { no: 1, name: '가이드레일', spec: '2438mm (EGI 1.6T, SUS 1.2T)', qty: 2, unit: '개' },
          { no: 2, name: '케이스', spec: '1219mm (EGI 1.6T)', qty: 1, unit: '개' },
          { no: 3, name: '모터', spec: '150KG', qty: 1, unit: '개' },
          { no: 4, name: '연동제어기', spec: '매입형', qty: 1, unit: '개' },
          { no: 5, name: '브라켓', spec: '백박스', qty: 1, unit: '개' },
          { no: 6, name: '엥클', spec: '-', qty: 4, unit: '개' },
          { no: 7, name: '연기차단재 (해당몰)', spec: '2438mm', qty: 2, unit: '개' },
          { no: 8, name: '연기차단재 (케이스용)', spec: '3000mm', qty: 4, unit: '개' },
          { no: 9, name: '참가시트', spec: '4500mm (5인치)', qty: 1, unit: '개' },
          { no: 10, name: '조인트바', spec: '300mm', qty: 5, unit: '개' },
          { no: 11, name: '엥클 (추가)', spec: '6000mm', qty: 4, unit: '개' },
        ]
      };
      return (
        <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '15mm' }}>
          {/* 제목 */}
          <div className="text-center mb-6">
            <h1 className="text-3xl font-bold tracking-[0.5em] mb-4">견 적 산 출 내 역 서</h1>
            <div className="text-sm text-gray-600">
              문서번호: {qtDtlSampleData.docNo} | 작성일자: {qtDtlSampleData.docDate}
            </div>
          </div>

          <hr className="border-t-2 border-gray-300 mb-8" />

          {/* 수요자 정보 */}
          <div className="mb-6">
            <table className="w-full border-collapse border border-black text-sm">
              <thead>
                <tr>
                  <th colSpan={4} className="border border-black bg-white py-2 text-center font-bold tracking-widest">수 요 자</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 w-24 text-center font-medium">업체명</th>
                  <td className="border border-black px-3 py-2" colSpan={3}>{qtDtlSampleData.customerName}</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">현장명</th>
                  <td className="border border-black px-3 py-2">{qtDtlSampleData.siteName}</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 w-20 text-center font-medium">담당자</th>
                  <td className="border border-black px-3 py-2 w-32">{qtDtlSampleData.contactPerson}</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">제품명</th>
                  <td className="border border-black px-3 py-2">{qtDtlSampleData.productName}</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">연락처</th>
                  <td className="border border-black px-3 py-2">{qtDtlSampleData.contactPhone}</td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 공급자 정보 */}
          <div className="mb-8">
            <table className="w-full border-collapse border border-black text-sm">
              <thead>
                <tr>
                  <th colSpan={4} className="border border-black bg-white py-2 text-center font-bold tracking-widest">공 급 자</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 w-28 text-center font-medium">상호</th>
                  <td className="border border-black px-3 py-2">(주)염진건설</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 w-28 text-center font-medium">사업자등록번호</th>
                  <td className="border border-black px-3 py-2">139-87-00353</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">대표자</th>
                  <td className="border border-black px-3 py-2">김 용 진</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">업태</th>
                  <td className="border border-black px-3 py-2">제조</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">종목</th>
                  <td className="border border-black px-3 py-2" colSpan={3}>방창, 셔터, 금속창호</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">사업장주소</th>
                  <td className="border border-black px-3 py-2" colSpan={3}>경기도 안성시 공업용지 오성길 45-22</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">전화</th>
                  <td className="border border-black px-3 py-2">031-983-5130</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">팩스</th>
                  <td className="border border-black px-3 py-2">02-6911-6315</td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 총 견적금액 박스 */}
          <div className="border-2 border-black p-6 mb-8 text-center">
            <div className="text-lg font-medium mb-3">총 견적금액</div>
            <div className="text-4xl font-bold mb-3">₩ {qtDtlSampleData.totalAmount.toLocaleString()}</div>
            <div className="text-sm text-gray-600">※ 부가가치세 별도</div>
          </div>

          {/* 세부산출내역 */}
          <div className="mb-8">
            <div className="bg-black text-white px-4 py-2 text-center font-bold tracking-[0.5em]">
              세 부 산 출 내 역
            </div>
            <table className="w-full border-collapse border-2 border-t-0 border-black text-sm">
              <thead>
                <tr className="bg-gray-50">
                  <th className="border border-black px-2 py-2 w-12 text-center">No.</th>
                  <th className="border border-black px-3 py-2 text-center">품목명</th>
                  <th className="border border-black px-3 py-2 w-28 text-center">규격</th>
                  <th className="border border-black px-2 py-2 w-20 text-center">수량</th>
                  <th className="border border-black px-2 py-2 w-14 text-center">단위</th>
                  <th className="border border-black px-2 py-2 w-24 text-center">단가</th>
                  <th className="border border-black px-2 py-2 w-28 text-center">금액</th>
                </tr>
              </thead>
              <tbody>
                {qtDtlSampleData.items.map((item) => (
                  <tr key={item.no}>
                    <td className="border border-black px-2 py-2 text-center">{item.no}</td>
                    <td className="border border-black px-3 py-2">{item.name}</td>
                    <td className="border border-black px-3 py-2 text-center">{item.spec}</td>
                    <td className="border border-black px-2 py-2 text-right">{item.qty.toLocaleString()}</td>
                    <td className="border border-black px-2 py-2 text-center">{item.unit}</td>
                    <td className="border border-black px-2 py-2 text-right">{item.unitPrice.toLocaleString()}</td>
                    <td className="border border-black px-2 py-2 text-right">{item.amount.toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
              <tfoot>
                <tr className="bg-gray-100 font-bold">
                  <td colSpan={6} className="border border-black px-3 py-2 text-right">공급가액 합계</td>
                  <td className="border border-black px-2 py-2 text-right">{qtDtlSampleData.supplyAmount.toLocaleString()}</td>
                </tr>
              </tfoot>
            </table>
          </div>

          {/* 소요자재내역 */}
          <div className="mb-8">
            <div className="bg-black text-white px-4 py-2 text-center font-bold tracking-[0.5em]">
              소 요 자 재 내 역
            </div>
            <table className="w-full border-collapse border-2 border-t-0 border-black text-sm mb-4">
              <tbody>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 w-24 text-center font-medium">제품구분</th>
                  <td className="border border-black px-3 py-2">{qtDtlSampleData.productType}</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 w-20 text-center font-medium">부호</th>
                  <td className="border border-black px-3 py-2">{qtDtlSampleData.productCode}</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">오픈사이즈</th>
                  <td className="border border-black px-3 py-2">{qtDtlSampleData.openSize}</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">제작사이즈</th>
                  <td className="border border-black px-3 py-2">{qtDtlSampleData.makeSize}</td>
                </tr>
                <tr>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">수량</th>
                  <td className="border border-black px-3 py-2">{qtDtlSampleData.qty}</td>
                  <th className="border border-black bg-gray-50 px-3 py-2 text-center font-medium">케이스</th>
                  <td className="border border-black px-3 py-2">{qtDtlSampleData.caseSize}</td>
                </tr>
              </tbody>
            </table>

            {/* 자재 목록 테이블 */}
            <table className="w-full border-collapse border-2 border-black text-sm">
              <thead>
                <tr className="bg-gray-50">
                  <th className="border border-black px-2 py-2 w-12 text-center">No.</th>
                  <th className="border border-black px-3 py-2 text-center">자재명</th>
                  <th className="border border-black px-3 py-2 text-center">규격</th>
                  <th className="border border-black px-2 py-2 w-20 text-center">수량</th>
                  <th className="border border-black px-2 py-2 w-14 text-center">단위</th>
                </tr>
              </thead>
              <tbody>
                {qtDtlSampleData.materials.map((mat) => (
                  <tr key={mat.no}>
                    <td className="border border-black px-2 py-2 text-center">{mat.no}</td>
                    <td className="border border-black px-3 py-2">{mat.name}</td>
                    <td className="border border-black px-3 py-2 text-center">{mat.spec}</td>
                    <td className="border border-black px-2 py-2 text-center">{mat.qty}</td>
                    <td className="border border-black px-2 py-2 text-center">{mat.unit}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* 비고사항 */}
          <div className="mb-8">
            <div className="bg-black text-white px-4 py-2 text-center font-bold tracking-[0.5em]">
              비 고 사 항
            </div>
            <div className="border-2 border-t-0 border-black p-4 min-h-[80px]">
              <p className="text-sm">{qtDtlSampleData.remarks}</p>
            </div>
          </div>

          {/* 하단 서명 영역 */}
          <div className="flex justify-end items-end mt-8 mb-8">
            <div className="text-right mr-6">
              <p className="text-sm mb-4">상기와 같이 견적합니다.</p>
              <p className="text-sm mb-2 font-bold">{qtDtlSampleData.docDate}</p>
              <p className="text-sm">공급자: (주)염진건설 (인)</p>
            </div>
            <div className="border border-black w-16 h-16 flex items-center justify-center text-xs text-gray-400">
              (인감<br />날인)
            </div>
          </div>

          {/* 유의사항 */}
          <div className="mb-6 text-xs text-gray-700">
            <p className="font-bold mb-2">【 유의사항 】</p>
            <p className="mb-1">1. 본 견적서는 {qtDtlSampleData.docDate} 기준으로 작성되었으며, 자재 가격 변동 시 조정될 수 있습니다.</p>
            <p className="mb-1">2. 견적 유효기간은 발행일로부터 30일이며, 기간 경과 시 재견적이 필요합니다.</p>
            <p className="mb-1">3. 제작 사양 및 수량 변경 시 견적 금액이 변동될 수 있습니다.</p>
            <p className="mb-1">4. 현장 여건에 따라 추가 비용이 발생할 수 있습니다.</p>
          </div>

          {/* 문의 */}
          <div className="text-center text-sm text-gray-600 border-t border-gray-300 pt-4">
            문의: {qtDtlSampleData.contactPerson} | {qtDtlSampleData.contactPhone}
          </div>
        </div>
      );
    }

    // 수주확인서 미리보기
    if (docCode === 'SO') {
      return (
        <div className="bg-white p-8 shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm' }}>
          <div className="flex justify-end mb-4">
            <table className="border-collapse border text-sm">
              <thead><tr>{templateForm.approvalLines.map((line, i) => <th key={i} className="border px-4 py-1 bg-gray-100">{approvalRoles.find(r => r.id === line.role)?.name}</th>)}</tr></thead>
              <tbody><tr>{templateForm.approvalLines.map((_, i) => <td key={i} className="border px-4 py-6 text-center min-w-[60px]"></td>)}</tr></tbody>
            </table>
          </div>
          <div className="text-center mb-6"><h1 className="text-2xl font-bold tracking-[0.5em]">{template.title}</h1></div>
          <div className="grid grid-cols-2 gap-4 mb-6">
            <div className="border-2 border-black">
              <div className="bg-gray-800 text-white text-center py-1 font-bold">수 요 자</div>
              <table className="w-full text-sm"><tbody>
                <tr><th className="border-b px-3 py-2 bg-gray-100 w-20">상 호</th><td className="border-b px-3 py-2">{sampleData.customerName}</td></tr>
                <tr><th className="border-b px-3 py-2 bg-gray-100">대표자</th><td className="border-b px-3 py-2">{sampleData.customerCeo}</td></tr>
                <tr><th className="border-b px-3 py-2 bg-gray-100">주 소</th><td className="border-b px-3 py-2">{sampleData.customerAddress}</td></tr>
                <tr><th className="px-3 py-2 bg-gray-100">전 화</th><td className="px-3 py-2">{sampleData.customerPhone}</td></tr>
              </tbody></table>
            </div>
            <div className="border-2 border-black">
              <div className="bg-gray-800 text-white text-center py-1 font-bold">공 급 자</div>
              <table className="w-full text-sm"><tbody>
                <tr><th className="border-b px-3 py-2 bg-gray-100 w-20">상 호</th><td className="border-b px-3 py-2">{companyInfo.name}</td></tr>
                <tr><th className="border-b px-3 py-2 bg-gray-100">대표자</th><td className="border-b px-3 py-2">{companyInfo.ceo}</td></tr>
                <tr><th className="border-b px-3 py-2 bg-gray-100">주 소</th><td className="border-b px-3 py-2">{companyInfo.address}</td></tr>
                <tr><th className="px-3 py-2 bg-gray-100">전 화</th><td className="px-3 py-2">{companyInfo.phone}</td></tr>
              </tbody></table>
            </div>
          </div>
          <table className="w-full border-collapse border-2 border-black mb-6 text-sm">
            <tbody>
              <tr><th className="border border-black bg-gray-100 px-3 py-2 w-24">현 장 명</th><td className="border border-black px-3 py-2" colSpan={3}>{sampleData.siteName}</td></tr>
              <tr><th className="border border-black bg-gray-100 px-3 py-2">제 품 명</th><td className="border border-black px-3 py-2">{sampleData.itemName}</td><th className="border border-black bg-gray-100 px-3 py-2 w-20">규 격</th><td className="border border-black px-3 py-2">{sampleData.spec}</td></tr>
              <tr><th className="border border-black bg-gray-100 px-3 py-2">납 기 일</th><td className="border border-black px-3 py-2">{sampleData.dueDate}</td><th className="border border-black bg-gray-100 px-3 py-2">금 액</th><td className="border border-black px-3 py-2 font-bold text-right">￦ {sampleData.totalAmount}</td></tr>
            </tbody>
          </table>
          <div className="mb-6">
            <div className="bg-gray-800 text-white px-3 py-1 text-sm font-medium">비 고</div>
            <div className="border-2 border-t-0 border-black p-4 min-h-[80px]"></div>
          </div>
        </div>
      );
    }

    // 작업지시서 미리보기
    if (docCode === 'WO') {
      return (
        <div className="bg-white p-8 shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm' }}>
          <div className="flex justify-between items-start mb-4">
            <div className="text-sm"><span className="font-bold">지시번호:</span> {sampleData.orderNo}</div>
            <table className="border-collapse border text-sm">
              <thead><tr>{templateForm.approvalLines.map((line, i) => <th key={i} className="border px-4 py-1 bg-gray-100">{approvalRoles.find(r => r.id === line.role)?.name}</th>)}</tr></thead>
              <tbody><tr>{templateForm.approvalLines.map((_, i) => <td key={i} className="border px-4 py-6 text-center min-w-[60px]"></td>)}</tr></tbody>
            </table>
          </div>
          <div className="text-center mb-6"><h1 className="text-2xl font-bold tracking-[0.3em]">{template.title}</h1></div>
          <table className="w-full border-collapse border-2 border-black mb-4 text-sm">
            <tbody>
              <tr><th className="border border-black bg-gray-100 px-3 py-2 w-24">수주번호</th><td className="border border-black px-3 py-2">{sampleData.orderNo}</td><th className="border border-black bg-gray-100 px-3 py-2 w-24">수주일자</th><td className="border border-black px-3 py-2">{sampleData.orderDate}</td></tr>
              <tr><th className="border border-black bg-gray-100 px-3 py-2">거래처</th><td className="border border-black px-3 py-2">{sampleData.customerName}</td><th className="border border-black bg-gray-100 px-3 py-2">현장명</th><td className="border border-black px-3 py-2">{sampleData.siteName}</td></tr>
              <tr><th className="border border-black bg-gray-100 px-3 py-2">제품명</th><td className="border border-black px-3 py-2">{sampleData.itemName}</td><th className="border border-black bg-gray-100 px-3 py-2">규격</th><td className="border border-black px-3 py-2">{sampleData.spec}</td></tr>
              <tr><th className="border border-black bg-gray-100 px-3 py-2">지시수량</th><td className="border border-black px-3 py-2">{sampleData.qty} SET</td><th className="border border-black bg-gray-100 px-3 py-2">납기일</th><td className="border border-black px-3 py-2">{sampleData.dueDate}</td></tr>
            </tbody>
          </table>
          <table className="w-full border-collapse border-2 border-black mb-4 text-sm">
            <tbody>
              <tr><th className="border border-black bg-blue-100 px-3 py-2 w-28">오픈사이즈</th><td className="border border-black px-3 py-2">{sampleData.openSize}</td><th className="border border-black bg-blue-100 px-3 py-2 w-28">제작사이즈</th><td className="border border-black px-3 py-2">{sampleData.makeSize}</td></tr>
              <tr><th className="border border-black bg-blue-100 px-3 py-2">케이스</th><td className="border border-black px-3 py-2">{sampleData.caseSize}</td><th className="border border-black bg-blue-100 px-3 py-2">특이사항</th><td className="border border-black px-3 py-2"></td></tr>
            </tbody>
          </table>
          <div className="bg-gray-800 text-white px-3 py-1 text-sm font-medium">공정별 작업내용</div>
          <table className="w-full border-collapse border-2 border-t-0 border-black mb-4 text-sm">
            <thead className="bg-gray-100"><tr><th className="border px-3 py-2">공정</th><th className="border px-3 py-2">작업내용</th><th className="border px-3 py-2">담당</th><th className="border px-3 py-2">시작일</th><th className="border px-3 py-2">완료일</th></tr></thead>
            <tbody>
              {['커튼조립', '케이스조립', '모터장착', '포장'].map((process, i) => (
                <tr key={i}><td className="border px-3 py-2">{process}</td><td className="border px-3 py-2"></td><td className="border px-3 py-2"></td><td className="border px-3 py-2"></td><td className="border px-3 py-2"></td></tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }

    // 발주서 미리보기
    if (docCode === 'PO') {
      return (
        <div className="bg-white p-8 shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm' }}>
          <div className="flex justify-end mb-4">
            <table className="border-collapse border text-sm">
              <thead><tr>{templateForm.approvalLines.map((line, i) => <th key={i} className="border px-4 py-1 bg-gray-100">{approvalRoles.find(r => r.id === line.role)?.name}</th>)}</tr></thead>
              <tbody><tr>{templateForm.approvalLines.map((_, i) => <td key={i} className="border px-4 py-6 text-center min-w-[60px]"></td>)}</tr></tbody>
            </table>
          </div>
          <div className="text-center mb-6"><h1 className="text-2xl font-bold tracking-[0.5em]">{template.title}</h1></div>
          <div className="border-2 border-black mb-4">
            <div className="bg-gray-800 text-white text-center py-1 font-bold">수 신</div>
            <table className="w-full text-sm"><tbody>
              <tr><th className="border-b px-3 py-2 bg-gray-100 w-24">업 체 명</th><td className="border-b px-3 py-2"></td><th className="border-b px-3 py-2 bg-gray-100 w-24">담 당 자</th><td className="border-b px-3 py-2"></td></tr>
              <tr><th className="px-3 py-2 bg-gray-100">연 락 처</th><td className="px-3 py-2"></td><th className="px-3 py-2 bg-gray-100">F A X</th><td className="px-3 py-2"></td></tr>
            </tbody></table>
          </div>
          <table className="w-full border-collapse border-2 border-black mb-4 text-sm">
            <tbody>
              <tr><th className="border border-black bg-gray-100 px-3 py-2 w-24">납품현장</th><td className="border border-black px-3 py-2">{sampleData.siteName}</td><th className="border border-black bg-gray-100 px-3 py-2 w-24">납 기 일</th><td className="border border-black px-3 py-2">{sampleData.dueDate}</td></tr>
              <tr><th className="border border-black bg-gray-100 px-3 py-2">현장주소</th><td className="border border-black px-3 py-2" colSpan={3}>{sampleData.siteAddress}</td></tr>
            </tbody>
          </table>
          <div className="bg-gray-800 text-white px-3 py-1 text-sm font-medium">발주 내역</div>
          <table className="w-full border-collapse border-2 border-t-0 border-black mb-4 text-sm">
            <thead className="bg-gray-100"><tr><th className="border px-3 py-2 w-12">NO</th><th className="border px-3 py-2">품 명</th><th className="border px-3 py-2">규 격</th><th className="border px-3 py-2 w-16">단위</th><th className="border px-3 py-2 w-16">수량</th><th className="border px-3 py-2">비고</th></tr></thead>
            <tbody>
              {[1, 2, 3, 4, 5].map(no => (
                <tr key={no}><td className="border px-3 py-2 text-center">{no}</td><td className="border px-3 py-2"></td><td className="border px-3 py-2"></td><td className="border px-3 py-2"></td><td className="border px-3 py-2"></td><td className="border px-3 py-2"></td></tr>
              ))}
            </tbody>
          </table>
          <div className="mb-6"><div className="bg-gray-800 text-white px-3 py-1 text-sm font-medium">특이사항</div><div className="border-2 border-t-0 border-black p-4 min-h-[60px]"></div></div>
          <div className="border-2 border-black p-4 text-center">
            <p className="text-lg mb-2">{sampleData.docDate}</p>
            <p className="font-bold text-xl">{companyInfo.name}</p>
            <div className="flex justify-center mt-2"><div className="w-16 h-16 border-2 border-red-500 rounded-full flex items-center justify-center text-red-500 text-sm">인</div></div>
          </div>
        </div>
      );
    }

    // 스크린 중간검사 성적서 미리보기 (PQC-SCR) - KD 헤더 스타일 적용
    if (docCode === 'PQC-SCR' || docCode === 'PQC') {
      return (
        <div className="bg-white shadow-lg mx-auto text-xs" style={{ width: '210mm', minHeight: '297mm', padding: '15mm' }}>
          {/* KD 로고 헤더 + 결재란 - 작업일지 스타일 */}
          {renderKDHeader(<>스크린<br />중간검사 성적서</>, '', {
            writer: '전진',
            writerDate: sampleData.inspectionDate,
            writerDept: '판매/전진',
            reviewerDept: '생산',
            approverDept: '품질'
          })}

          {/* 기본정보 테이블 */}
          <table className="w-full border-collapse text-[10px]" style={{ border: '2px solid black' }}>
            <tbody>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ width: '15%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>품  명</th>
                <td className="px-2 py-1.5" style={{ width: '35%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>스크린</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ width: '15%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>제품 LOT NO</th>
                <td className="px-2 py-1.5 font-bold" style={{ borderBottom: '1px solid black' }}>{sampleData.lotNo}</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>규  격</th>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.spec}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>로 트 크 기</th>
                <td className="px-2 py-1.5 text-center" style={{ borderBottom: '1px solid black' }}>{sampleData.lotSize} 개소</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 처</th>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.supplierName}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>검 사 일 자</th>
                <td className="px-2 py-1.5 text-center" style={{ borderBottom: '1px solid black' }}>{sampleData.inspectionDate}</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black' }}>현 장 명</th>
                <td className="px-2 py-1.5 font-bold text-blue-600" style={{ borderRight: '1px solid black' }}>{sampleData.siteName}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black' }}>검 사 자</th>
                <td className="px-2 py-1.5 text-center"></td>
              </tr>
            </tbody>
          </table>

          {/* 중간검사 기준서 - 슬랫/조인트바와 동일한 구조 */}
          <table className="w-full border-collapse text-[9px] border-2 border-t-0 border-black">
            <tbody>
              {/* 헤더 행 */}
              <tr>
                <td className="bg-yellow-100 text-center font-bold border-b border-r border-black px-1 py-1.5" rowSpan={7} style={{ width: '45px' }}>
                  중간검사<br />기준서
                </td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '100px' }}>도해</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '50px' }}>검사항목</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" colSpan={3}>검사기준</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '55px' }}>검사방법</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '65px' }}>검사주기</td>
                <td className="bg-gray-50 text-center border-b border-black px-1 py-1 font-semibold" style={{ width: '85px' }}>관련규정</td>
              </tr>
              {/* 겉모양 - 가공상태 */}
              <tr>
                <td className="border-b border-r border-black p-1 align-middle" rowSpan={6}>
                  {/* 도해 다이어그램 - 스크린 이미지 */}
                  <div className="w-full h-32 bg-gray-100 border border-gray-300 relative mx-auto flex flex-col items-center justify-center">
                    {/* ① 앤드락 표시 - 상단 */}
                    <div className="flex items-center gap-2 mb-1">
                      <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-black text-[8px] font-bold">1</span>
                    </div>
                    {/* 메인 스크린 본체 */}
                    <div className="relative w-20 h-20 border border-gray-400 bg-gray-200 mb-1">
                      {/* 앤드락 라벨 */}
                      <div className="absolute -top-1 left-0 text-[7px] text-red-600 font-bold">앤드락</div>
                      {/* 내화실 폐쇄선 (점선) */}
                      <div className="absolute top-3 left-1 right-1 border-t-2 border-dashed border-yellow-500"></div>
                      <div className="absolute top-5 left-1/2 -translate-x-1/2 text-[7px] text-blue-600">내화실</div>
                      <div className="absolute top-8 left-1/2 -translate-x-1/2 text-[7px] text-blue-600">방화선</div>
                      {/* ② 스크린원단 표시 */}
                      <div className="absolute bottom-2 left-1/2 -translate-x-1/2 flex items-center gap-1">
                        <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-black text-[8px] font-bold">2</span>
                        <span className="text-[7px] text-yellow-600 font-bold">스크린원단</span>
                      </div>
                    </div>
                    {/* ③ 간격 표시 */}
                    <div className="flex items-center gap-1">
                      <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-black text-[8px] font-bold">3</span>
                    </div>
                  </div>
                </td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle font-semibold" rowSpan={3}>겉모양</td>
                <td className="border-b border-r border-black px-1 py-2 text-center" colSpan={2}>가공상태</td>
                <td className="border-b border-r border-black px-1 py-2 text-center">사용상 해로운 결함이 없을것</td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" rowSpan={3}>육안검사</td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" rowSpan={6}>n = 1, c = 0</td>
                <td className="border-b border-black px-1 py-2 text-center">KS F 4510 5.1항</td>
              </tr>
              {/* 겉모양 - 재봉상태 */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center" colSpan={2}>재봉상태</td>
                <td className="border-b border-r border-black px-1 py-2 text-center leading-relaxed text-[8px]">내화실에 의해 견고하게<br />접합되어야 함</td>
                <td className="border-b border-black px-1 py-2 text-center">KS F 4510 9항</td>
              </tr>
              {/* 겉모양 - 조립상태 */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center" colSpan={2}>조립상태</td>
                <td className="border-b border-r border-black px-1 py-2 text-center leading-relaxed text-[8px]">앤드락이 견고하게 조립되어야 함</td>
                <td className="border-b border-black px-1 py-2 text-center" rowSpan={2}>KS F 4510 7항<br />표9 인용</td>
              </tr>
              {/* 치수 - 길이① */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle font-semibold" rowSpan={3}>치수<br />(mm)</td>
                <td className="border-b border-r border-black px-1 py-2 text-center">길이</td>
                <td className="border-b border-r border-black px-1 py-2 text-center" style={{ width: '25px' }}>
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">①</span>
                </td>
                <td className="border-b border-r border-black px-1 py-2 text-center">도면치수 &nbsp;± 4</td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" rowSpan={2}>체크검사</td>
              </tr>
              {/* 치수 - 높이② */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center">높이</td>
                <td className="border-b border-r border-black px-1 py-2 text-center">
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">②</span>
                </td>
                <td className="border-b border-r border-black px-1 py-2 text-center leading-relaxed text-[8px]">도면치수 + 제한없음<br />- 40</td>
                <td className="border-b border-black px-1 py-2 text-center" rowSpan={2}>자체규정</td>
              </tr>
              {/* 치수 - 간격③ */}
              <tr>
                <td className="border-r border-black px-1 py-2 text-center">간격</td>
                <td className="border-r border-black px-1 py-2 text-center">
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">③</span>
                </td>
                <td className="border-r border-black px-1 py-2 text-center">400 이하</td>
                <td className="border-r border-black px-1 py-2 text-center">GONO<br />게이지</td>
              </tr>
            </tbody>
          </table>

          {/* 중간검사 DATA */}
          <div className="border-2 border-t-0 border-black">
            <div className="bg-gray-100 px-2 py-1 font-bold border-b border-black text-center">중간검사 DATA</div>
            <table className="w-full border-collapse text-[9px]">
              <thead>
                <tr className="bg-gray-50">
                  <th className="border-b border-r border-black px-1 py-1" rowSpan={3}>일련<br />번호</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={3}>겉모양</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={6}>치수 [mm]</th>
                  <th className="border-b border-black px-1 py-1" rowSpan={3}>판정</th>
                </tr>
                <tr className="bg-gray-50">
                  <th className="border-b border-r border-black px-1 py-1" rowSpan={2}>가공상태</th>
                  <th className="border-b border-r border-black px-1 py-1" rowSpan={2}>재봉상태</th>
                  <th className="border-b border-r border-black px-1 py-1" rowSpan={2}>조립상태</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={2}>① 길이</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={2}>② 높이</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={2}>③ 간격</th>
                </tr>
                <tr className="bg-gray-50">
                  <th className="border-b border-r border-black px-1 py-1">도면치수</th>
                  <th className="border-b border-r border-black px-1 py-1">측정값</th>
                  <th className="border-b border-r border-black px-1 py-1">도면치수</th>
                  <th className="border-b border-r border-black px-1 py-1">측정값</th>
                  <th className="border-b border-r border-black px-1 py-1">기준치</th>
                  <th className="border-b border-r border-black px-1 py-1">측정값</th>
                </tr>
              </thead>
              <tbody>
                {sampleData.screenInspectionData.map((row, i) => (
                  <tr key={i}>
                    <td className="border-b border-r border-black px-1 py-1 text-center font-bold">{row.no}</td>
                    <td className="border-b border-r border-black px-1 py-1 text-center">
                      <span className="mr-1">□ 양호</span><span>□ 불량</span>
                    </td>
                    <td className="border-b border-r border-black px-1 py-1 text-center">
                      <span className="mr-1">□ 양호</span><span>□ 불량</span>
                    </td>
                    <td className="border-b border-r border-black px-1 py-1 text-center">
                      <span className="mr-1">□ 양호</span><span>□ 불량</span>
                    </td>
                    <td className="border-b border-r border-black px-1 py-1 text-center text-lg font-bold text-red-600">{row.lengthSpec}</td>
                    <td className="border-b border-r border-black px-1 py-1 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-1 text-center text-lg font-bold text-red-600">{row.heightSpec}</td>
                    <td className="border-b border-r border-black px-1 py-1 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-1 text-center">{row.intervalStd}</td>
                    <td className="border-b border-r border-black px-1 py-1 text-center">
                      <span className="mr-1">□ OK</span><span>□ NG</span>
                    </td>
                    <td className="border-b border-black px-1 py-1 text-center">
                      <span className="mr-1">□ 적합</span><span>□ 부적합</span>
                    </td>
                  </tr>
                ))}
                {/* 부적합 내용 + 종합판정 행 */}
                <tr>
                  <td colSpan={10} className="border-r border-black p-0 align-top">
                    <div className="px-2 py-1 font-bold border-b border-black bg-gray-50">[부적합 내용]</div>
                    <div className="h-24"></div>
                  </td>
                  <td className="p-0 align-top">
                    <div className="bg-yellow-300 text-center font-bold px-2 py-1 border-b border-black">종합판정</div>
                    <div className="h-24 flex items-center justify-center">
                      <span className="text-lg font-bold"></span>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 문서번호 푸터 */}
          <div className="flex justify-between items-center mt-4 text-[10px] font-bold">
            <span>KDQP-01-006</span>
            <span>KDPS-03-01</span>
          </div>
        </div>
      );
    }

    // 절곡품 중간검사 성적서 미리보기 (PQC-BND) - KD 헤더 스타일 적용
    if (docCode === 'PQC-BND') {
      return (
        <div className="bg-white shadow-lg mx-auto text-xs" style={{ width: '210mm', minHeight: '297mm', padding: '15mm' }}>
          {/* KD 로고 헤더 + 결재란 - 작업일지 스타일 */}
          {renderKDHeader(<>절곡품<br />중간검사 성적서</>, '', {
            writer: '전진',
            writerDate: sampleData.inspectionDate,
            writerDept: '판매/전진',
            reviewerDept: '생산',
            approverDept: '품질'
          })}

          {/* 기본정보 테이블 */}
          <table className="w-full border-collapse text-[10px]" style={{ border: '2px solid black' }}>
            <tbody>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ width: '15%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>품  명</th>
                <td className="px-2 py-1.5" style={{ width: '35%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>절곡품</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ width: '15%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>제품 LOT NO</th>
                <td className="px-2 py-1.5 font-bold" style={{ borderBottom: '1px solid black' }}>{sampleData.lotNo}</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>규  격</th>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="mr-2">□ 철재</span><span>☑ 스크린</span>
                </td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>로 트 크 기</th>
                <td className="px-2 py-1.5 text-center" style={{ borderBottom: '1px solid black' }}>{sampleData.lotSize} 개소</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 처</th>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{companyInfo.name}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>검 사 일 자</th>
                <td className="px-2 py-1.5 text-center" style={{ borderBottom: '1px solid black' }}>{sampleData.inspectionDate}</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>현 장 명</th>
                <td className="px-2 py-1.5 font-bold text-blue-600" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.siteName}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>검 사 자</th>
                <td className="px-2 py-1.5 text-center" style={{ borderBottom: '1px solid black' }}></td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black' }}>제 품 명</th>
                <td className="px-2 py-1.5 font-bold" style={{ borderRight: '1px solid black' }}>{sampleData.bendingInspectionData.productName}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black' }}>마감유형</th>
                <td className="px-2 py-1.5 text-center font-bold text-blue-600">{sampleData.bendingInspectionData.finishType}</td>
              </tr>
            </tbody>
          </table>

          {/* 중간검사 기준서 */}
          <table className="w-full border-collapse text-[8px] border-2 border-t-0 border-black">
            <tbody>
              {/* 가이드레일/케이스/하단마감재 섹션 */}
              <tr>
                <td className="bg-yellow-100 text-center font-bold border-b border-r border-black px-2 py-1" rowSpan={9}>
                  중간검사<br />기준서
                </td>
                <td className="border-b border-r border-black px-2 py-1 text-center font-bold align-middle" rowSpan={4}>
                  가이드레일<br />케이스<br />하단마감재
                </td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold">도해</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold">검사항목</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" colSpan={3}>검사기준</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold">검사방법</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold">검사주기</td>
                <td className="bg-gray-50 text-center border-b border-black px-1 py-1 font-semibold">관련규정</td>
              </tr>
              <tr>
                <td className="border-b border-r border-black p-1 align-middle text-center text-[7px] text-gray-500" rowSpan={3}>
                  절곡품 제품검사<br />상세도면 참조
                </td>
                <td className="border-b border-r border-black px-1 py-1 text-center">겉모양</td>
                <td className="border-b border-r border-black px-1 py-1 text-center" colSpan={2}>절곡상태</td>
                <td className="border-b border-r border-black px-1 py-1 text-center">사용상 해로운 결함이 없을것</td>
                <td className="border-b border-r border-black px-1 py-1 text-center">육안검사</td>
                <td className="border-b border-r border-black px-1 py-1 text-center align-middle" rowSpan={3}>n = 1, c = 0</td>
                <td className="border-b border-black px-1 py-1 text-center">KS F 4510 5.1항</td>
              </tr>
              <tr>
                <td className="border-b border-r border-black px-1 py-1 text-center align-middle" rowSpan={2}>치수<br />(mm)</td>
                <td className="border-b border-r border-black px-1 py-1 text-center" colSpan={2}>길이</td>
                <td className="border-b border-r border-black px-1 py-1 text-center">도면치수 ± 4</td>
                <td className="border-b border-r border-black px-1 py-1 text-center align-middle" rowSpan={2}>체크검사</td>
                <td className="border-b border-black px-1 py-1 text-center">KS F 4510 7항<br />표9</td>
              </tr>
              <tr>
                <td className="border-b border-r border-black px-1 py-1 text-center" colSpan={2}>간격</td>
                <td className="border-b border-r border-black px-1 py-1 text-center">도면치수 ± 2</td>
                <td className="border-b border-black px-1 py-1 text-center">KS F 4510 7항<br />표9 / 자체규정</td>
              </tr>
              {/* 연기차단재 섹션 */}
              <tr>
                <td className="border-b border-r border-black px-2 py-1 text-center font-bold align-middle" rowSpan={5}>
                  연기차단재
                </td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold">도해</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold">검사항목</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" colSpan={3}>검사기준</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold">검사방법</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold">검사주기</td>
                <td className="bg-gray-50 text-center border-b border-black px-1 py-1 font-semibold">관련규정</td>
              </tr>
              <tr>
                <td className="border-b border-r border-black p-1 align-middle" rowSpan={4}>
                  {/* 연기차단재 도해 */}
                  <div className="w-28 h-20 bg-gray-100 border border-gray-300 relative mx-auto flex flex-col items-center justify-center">
                    <div className="text-[6px] text-gray-500 mb-1">화이바 글라스 코팅직물</div>
                    <div className="flex items-center gap-2">
                      <div className="w-16 h-6 bg-yellow-200 border border-yellow-400 rounded relative">
                        <span className="absolute -top-2 -left-1 inline-flex items-center justify-center w-3 h-3 rounded-full border border-blue-600 text-blue-600 text-[6px] font-bold bg-white">1</span>
                      </div>
                    </div>
                    <div className="text-[5px] text-gray-500 mt-1">(연기차단재 프레임)</div>
                    <div className="text-[5px] text-gray-500">(EGI 0.8T)</div>
                    <div className="text-[5px] text-purple-600">글라스 코팅직물 (너비 50/80)</div>
                    <span className="absolute bottom-0 right-1 inline-flex items-center justify-center w-3 h-3 rounded-full border border-blue-600 text-blue-600 text-[6px] font-bold bg-white">2</span>
                  </div>
                </td>
                <td className="border-b border-r border-black px-1 py-1 text-center">겉모양</td>
                <td className="border-b border-r border-black px-1 py-1 text-center" colSpan={2}>절곡상태</td>
                <td className="border-b border-r border-black px-1 py-1 text-center">원단이 프레임에서 빠지지 않을것</td>
                <td className="border-b border-r border-black px-1 py-1 text-center">육안검사</td>
                <td className="border-b border-r border-black px-1 py-1 text-center align-middle" rowSpan={4}>n = 1, c = 0</td>
                <td className="border-b border-black px-1 py-1 text-center">KS F 4510 5.1항</td>
              </tr>
              <tr>
                <td className="border-b border-r border-black px-1 py-1 text-center align-middle" rowSpan={3}>치수<br />(mm)</td>
                <td className="border-b border-r border-black px-1 py-1 text-center" colSpan={2}>길이</td>
                <td className="border-b border-r border-black px-1 py-1 text-center">도면치수 ± 4</td>
                <td className="border-b border-r border-black px-1 py-1 text-center align-middle" rowSpan={3}>체크검사</td>
                <td className="border-b border-black px-1 py-1 text-center">KS F 4510 7항<br />표9 인용</td>
              </tr>
              <tr>
                <td className="border-b border-r border-black px-1 py-1 text-center">너비</td>
                <td className="border-b border-r border-black px-1 py-1 text-center">
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">①</span>
                </td>
                <td className="border-b border-r border-black px-1 py-1 text-center">W50 : 50 ± 5<br />W80 : 80 ± 5</td>
                <td className="border-b border-black px-1 py-1 text-center align-middle" rowSpan={2}>자체규정</td>
              </tr>
              <tr>
                <td className="border-r border-black px-1 py-1 text-center">간격</td>
                <td className="border-r border-black px-1 py-1 text-center">
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">②</span>
                </td>
                <td className="border-r border-black px-1 py-1 text-center">도면치수 ± 2</td>
              </tr>
            </tbody>
          </table>

          {/* 중간검사 DATA */}
          <div className="border-2 border-t-0 border-black">
            <div className="bg-gray-100 px-2 py-1 font-bold border-b border-black text-center">중간검사 DATA</div>
            <table className="w-full border-collapse text-[8px]">
              <thead>
                <tr className="bg-gray-50">
                  <th className="border-b border-r border-black px-1 py-1" rowSpan={3}>분류</th>
                  <th className="border-b border-r border-black px-1 py-1" rowSpan={3}>제품명</th>
                  <th className="border-b border-r border-black px-1 py-1" rowSpan={3}>타입</th>
                  <th className="border-b border-r border-black px-1 py-1" rowSpan={2}>겉모양</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={7}>치수 [mm]</th>
                  <th className="border-b border-black px-1 py-1" rowSpan={3}>판정</th>
                </tr>
                <tr className="bg-gray-50">
                  <th className="border-b border-r border-black px-1 py-1" colSpan={2}>길이</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={2}>너비</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={3}>간격</th>
                </tr>
                <tr className="bg-gray-50">
                  <th className="border-b border-r border-black px-1 py-1">절곡상태</th>
                  <th className="border-b border-r border-black px-1 py-1">도면치수</th>
                  <th className="border-b border-r border-black px-1 py-1">측정값</th>
                  <th className="border-b border-r border-black px-1 py-1">도면치수</th>
                  <th className="border-b border-r border-black px-1 py-1">측정값</th>
                  <th className="border-b border-r border-black px-1 py-1">POINT</th>
                  <th className="border-b border-r border-black px-1 py-1">도면치수</th>
                  <th className="border-b border-r border-black px-1 py-1">측정값</th>
                </tr>
              </thead>
              <tbody>
                {/* 샘플 데이터 - 철재 가이드레일 */}
                <tr>
                  <td className="border-b border-r border-black px-1 py-1 text-center bg-orange-50" rowSpan={4}>
                    <span className="font-bold">철재</span><br />
                    <span className="text-[7px]">(KQTS01)</span>
                  </td>
                  <td className="border-b border-r border-black px-1 py-1 font-bold" rowSpan={4}>가이드레일</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center" rowSpan={4}>벽면형</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center" rowSpan={4}>
                    <span className="mr-1">□ 양호</span><span>□ 불량</span>
                  </td>
                  <td className="border-b border-r border-black px-1 py-1 text-center font-bold" rowSpan={4}>4,300</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center" rowSpan={4}></td>
                  <td className="border-b border-r border-black px-1 py-1 text-center" rowSpan={4}>N/A</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center" rowSpan={4}>N/A</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center">①</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center font-bold text-blue-600">30</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center"></td>
                  <td className="border-b border-black px-1 py-1 text-center" rowSpan={4}>
                    <span className="mr-1">□ 적합</span><span>□ 부적합</span>
                  </td>
                </tr>
                <tr>
                  <td className="border-b border-r border-black px-1 py-1 text-center">②</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center font-bold text-blue-600">78</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center"></td>
                </tr>
                <tr>
                  <td className="border-b border-r border-black px-1 py-1 text-center">③</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center font-bold text-blue-600">25</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center"></td>
                </tr>
                <tr>
                  <td className="border-b border-r border-black px-1 py-1 text-center">④</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center font-bold text-blue-600">45</td>
                  <td className="border-b border-r border-black px-1 py-1 text-center"></td>
                </tr>
                {/* 빈 행 추가 */}
                {[1, 2].map(i => (
                  <tr key={i}>
                    <td className="border-b border-r border-black px-1 py-2 text-center bg-orange-50"></td>
                    <td className="border-b border-r border-black px-1 py-2"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center">
                      <span className="mr-1">□ 양호</span><span>□ 불량</span>
                    </td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-black px-1 py-2 text-center">
                      <span className="mr-1">□ 적합</span><span>□ 부적합</span>
                    </td>
                  </tr>
                ))}
                {/* 부적합 내용 + 종합판정 행 */}
                <tr>
                  <td colSpan={11} className="border-r border-black p-0 align-top">
                    <div className="px-2 py-1 font-bold border-b border-black bg-gray-50">[부적합 내용]</div>
                    <div className="h-24"></div>
                  </td>
                  <td className="p-0 align-top">
                    <div className="bg-yellow-300 text-center font-bold px-2 py-1 border-b border-black">종합판정</div>
                    <div className="h-24 flex items-center justify-center">
                      <span className="text-lg font-bold"></span>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 문서번호 푸터 */}
          <div className="flex justify-between items-center mt-4 text-[10px] font-bold">
            <span>KDQP-01-007</span>
            <span>KDPS-10-01</span>
          </div>
        </div>
      );
    }

    // 슬랫 중간검사성적서 미리보기 (PQC-SLT) - KD 헤더 스타일 적용
    if (docCode === 'PQC-SLT') {
      return (
        <div className="bg-white shadow-lg mx-auto text-xs" style={{ width: '210mm', minHeight: '297mm', padding: '15mm' }}>
          {/* KD 로고 헤더 + 결재란 - 작업일지 스타일 */}
          {renderKDHeader(<>슬랫<br />중간검사 성적서</>, '', {
            writer: '전진',
            writerDate: sampleData.inspectionDate,
            writerDept: '판매/전진',
            reviewerDept: '생산',
            approverDept: '품질'
          })}

          {/* 기본정보 테이블 */}
          <table className="w-full border-collapse text-[10px] border-2 border-black">
            <tbody>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold border-r border-b border-black" style={{ width: '15%' }}>품  명</th>
                <td className="px-2 py-1.5 border-r border-b border-black" style={{ width: '35%' }}>슬랫</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold border-r border-b border-black" style={{ width: '15%' }}>제품 LOT NO</th>
                <td className="px-2 py-1.5 font-bold border-b border-black">{sampleData.lotNo}</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold border-r border-b border-black">규  격</th>
                <td className="px-2 py-1.5 border-r border-b border-black">{sampleData.spec}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold border-r border-b border-black">로 트 크 기</th>
                <td className="px-2 py-1.5 text-center border-b border-black">{sampleData.lotSize} 개소</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold border-r border-b border-black">발 주 처</th>
                <td className="px-2 py-1.5 border-r border-b border-black">{sampleData.supplierName}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold border-r border-b border-black">검 사 일 자</th>
                <td className="px-2 py-1.5 text-center border-b border-black">{sampleData.inspectionDate}</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold border-r border-black">현 장 명</th>
                <td className="px-2 py-1.5 font-bold text-blue-600 border-r border-black">{sampleData.siteName}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold border-r border-black">검 사 자</th>
                <td className="px-2 py-1.5 text-center"></td>
              </tr>
            </tbody>
          </table>

          {/* 중간검사 기준서 - 첨부파일 양식 기준 */}
          <table className="w-full border-collapse text-[9px] border-2 border-t-0 border-black">
            <tbody>
              {/* 헤더 행 */}
              <tr>
                <td className="bg-yellow-100 text-center font-bold border-b border-r border-black px-1 py-1.5" rowSpan={7} style={{ width: '45px' }}>
                  중간검사<br />기준서
                </td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '75px' }}>도해</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '50px' }}>검사항목</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" colSpan={3}>검사기준</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '55px' }}>검사방법</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '65px' }}>검사주기</td>
                <td className="bg-gray-50 text-center border-b border-black px-1 py-1 font-semibold" style={{ width: '85px' }}>관련규정</td>
              </tr>
              {/* 겉모양 - 가공상태 */}
              <tr>
                <td className="border-b border-r border-black p-1 align-middle" rowSpan={6}>
                  {/* 도해 다이어그램 - 슬랫 이미지 */}
                  <div className="w-full h-28 bg-gray-100 border border-gray-300 relative mx-auto flex flex-col items-center justify-center">
                    {/* ① ② 표시 - 상단 */}
                    <div className="flex items-center gap-4 mb-1">
                      <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-red-600 text-red-600 text-[8px] font-bold">1</span>
                      <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-red-600 text-red-600 text-[8px] font-bold">2</span>
                    </div>
                    {/* 슬랫 단면도 */}
                    <div className="text-[7px] text-gray-500 mb-1">조립상태</div>
                    <div className="w-16 h-6 bg-gray-300 rounded-sm relative">
                      <div className="absolute -bottom-1 left-1/2 transform -translate-x-1/2 w-12 h-1.5 bg-yellow-600 rounded-sm"></div>
                    </div>
                    {/* ③ 표시 - 하단 */}
                    <div className="flex items-center gap-1 mt-2">
                      <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-blue-600 text-blue-600 text-[8px] font-bold">3</span>
                    </div>
                  </div>
                </td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle font-semibold" rowSpan={3}>겉모양</td>
                <td className="border-b border-r border-black px-1 py-2 text-center" colSpan={2}>가공상태</td>
                <td className="border-b border-r border-black px-1 py-2 text-center">사용상 해로운 결함이 없을것</td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" rowSpan={3}>육안검사</td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" rowSpan={6}>n = 1, c = 0</td>
                <td className="border-b border-black px-1 py-2 text-center">KS F 4510 5.1항</td>
              </tr>
              {/* 겉모양 - 조립상태 (위) */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" colSpan={2} rowSpan={2}>조립상태</td>
                <td className="border-b border-r border-black px-1 py-2 text-center leading-relaxed text-[8px]">앤드락이 용접에 의해<br />견고하게 조립되어야 함</td>
                <td className="border-b border-black px-1 py-1 text-center">KS F 4510 9항</td>
              </tr>
              {/* 겉모양 - 조립상태 (아래) */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center leading-relaxed text-[8px]">용접부위에 락카도색이<br />되어야 함</td>
                <td className="border-b border-black px-1 py-1 text-center">자체규정</td>
              </tr>
              {/* 치수 - 높이① */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle font-semibold" rowSpan={3}>치수<br />(mm)</td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" rowSpan={2}>높이</td>
                <td className="border-b border-r border-black px-1 py-2 text-center" style={{ width: '25px' }}>
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">①</span>
                </td>
                <td className="border-b border-r border-black px-1 py-2 text-center">16.5 &nbsp;± 1</td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" rowSpan={3}>체크검사</td>
                <td className="border-b border-black px-1 py-2 text-center" rowSpan={3}>KS F 4510 7항<br />표9</td>
              </tr>
              {/* 치수 - 높이② */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center">
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">②</span>
                </td>
                <td className="border-b border-r border-black px-1 py-2 text-center">14.5 &nbsp;± 1</td>
              </tr>
              {/* 치수 - 길이③ */}
              <tr>
                <td className="border-r border-black px-1 py-2 text-center">길이</td>
                <td className="border-r border-black px-1 py-2 text-center">
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">③</span>
                </td>
                <td className="border-r border-black px-1 py-2 text-center">도면치수(앤드락제외) &nbsp;± 4</td>
              </tr>
            </tbody>
          </table>

          {/* 중간검사 DATA */}
          <div className="border-2 border-t-0 border-black">
            <div className="bg-gray-100 px-2 py-1 font-bold border-b border-black text-center">중간검사 DATA</div>
            <table className="w-full border-collapse text-[9px]">
              <thead>
                <tr className="bg-gray-50">
                  <th className="border-b border-r border-black px-1 py-1" rowSpan={3}>일련<br />번호</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={2}>겉모양</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={6}>치수 [mm]</th>
                  <th className="border-b border-black px-1 py-1" rowSpan={3}>판정</th>
                </tr>
                <tr className="bg-gray-50">
                  <th className="border-b border-r border-black px-1 py-1" rowSpan={2}>가공상태</th>
                  <th className="border-b border-r border-black px-1 py-1" rowSpan={2}>조립상태</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={2}>① 높이</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={2}>② 높이</th>
                  <th className="border-b border-r border-black px-1 py-1" colSpan={2}>③ 길이 (앤드락제외)</th>
                </tr>
                <tr className="bg-gray-50">
                  <th className="border-b border-r border-black px-1 py-1">기준치</th>
                  <th className="border-b border-r border-black px-1 py-1">측정값</th>
                  <th className="border-b border-r border-black px-1 py-1">기준치</th>
                  <th className="border-b border-r border-black px-1 py-1">측정값</th>
                  <th className="border-b border-r border-black px-1 py-1">도면치수</th>
                  <th className="border-b border-r border-black px-1 py-1">측정값</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td className="border-b border-r border-black px-1 py-2 text-center font-bold">01</td>
                  <td className="border-b border-r border-black px-1 py-2 text-center">
                    <span className="mr-1">□ 양호</span><span>□ 불량</span>
                  </td>
                  <td className="border-b border-r border-black px-1 py-2 text-center">
                    <span className="mr-1">□ 양호</span><span>□ 불량</span>
                  </td>
                  <td className="border-b border-r border-black px-1 py-2 text-center text-blue-600 font-bold">16.5 ± 1</td>
                  <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                  <td className="border-b border-r border-black px-1 py-2 text-center text-blue-600 font-bold">14.5 ± 1</td>
                  <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                  <td className="border-b border-r border-black px-1 py-2 text-center text-red-600 font-bold text-lg">4,510</td>
                  <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                  <td className="border-b border-black px-1 py-2 text-center">
                    <span className="mr-1">□ 적합</span><span>□ 부적합</span>
                  </td>
                </tr>
                {[2, 3, 4, 5].map(i => (
                  <tr key={i}>
                    <td className="border-b border-r border-black px-1 py-2 text-center font-bold">{String(i).padStart(2, '0')}</td>
                    <td className="border-b border-r border-black px-1 py-2 text-center">
                      <span className="mr-1">□ 양호</span><span>□ 불량</span>
                    </td>
                    <td className="border-b border-r border-black px-1 py-2 text-center">
                      <span className="mr-1">□ 양호</span><span>□ 불량</span>
                    </td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-r border-black px-1 py-2 text-center"></td>
                    <td className="border-b border-black px-1 py-2 text-center">
                      <span className="mr-1">□ 적합</span><span>□ 부적합</span>
                    </td>
                  </tr>
                ))}
                {/* 부적합 내용 + 종합판정 행 */}
                <tr>
                  <td colSpan={9} className="border-r border-black p-0 align-top">
                    <div className="px-2 py-1 font-bold border-b border-black bg-gray-50">[부적합 내용]</div>
                    <div className="h-24"></div>
                  </td>
                  <td className="p-0 align-top">
                    <div className="bg-yellow-300 text-center font-bold px-2 py-1 border-b border-black">종합판정</div>
                    <div className="h-24 flex items-center justify-center">
                      <span className="text-lg font-bold"></span>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 문서번호 푸터 */}
          <div className="flex justify-between items-center mt-4 text-[10px] font-bold">
            <span>KDQP-01-008</span>
            <span>KDPS-10-02</span>
          </div>
        </div>
      );
    }

    // 조인트바 중간검사성적서 미리보기 (PQC-JB) - KD 헤더 스타일 적용
    if (docCode === 'PQC-JB') {
      return (
        <div className="bg-white shadow-lg mx-auto text-xs" style={{ width: '210mm', minHeight: '297mm', padding: '15mm' }}>
          {/* KD 로고 헤더 + 결재란 - 작업일지 스타일 */}
          {renderKDHeader(<>조인트바<br />중간검사 성적서</>, '', {
            writer: '전진',
            writerDate: sampleData.inspectionDate,
            writerDept: '판매/전진',
            reviewerDept: '생산',
            approverDept: '품질'
          })}

          {/* 기본정보 테이블 */}
          <table className="w-full border-collapse text-[10px]" style={{ border: '2px solid black' }}>
            <tbody>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ width: '15%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>품  명</th>
                <td className="px-2 py-1.5" style={{ width: '35%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>조인트바</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ width: '15%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>제품 LOT NO</th>
                <td className="px-2 py-1.5 font-bold" style={{ borderBottom: '1px solid black' }}>{sampleData.lotNo}</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>규  격</th>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.spec}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>로 트 크 기</th>
                <td className="px-2 py-1.5 text-center" style={{ borderBottom: '1px solid black' }}>{sampleData.lotSize} 개소</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 처</th>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.supplierName}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>검 사 일 자</th>
                <td className="px-2 py-1.5 text-center" style={{ borderBottom: '1px solid black' }}>{sampleData.inspectionDate}</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black' }}>현 장 명</th>
                <td className="px-2 py-1.5 font-bold text-blue-600" style={{ borderRight: '1px solid black' }}>{sampleData.siteName}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black' }}>검 사 자</th>
                <td className="px-2 py-1.5 text-center"></td>
              </tr>
            </tbody>
          </table>

          {/* 중간검사 기준서 - 슬랫 양식과 동일한 구조 */}
          <table className="w-full border-collapse text-[9px] border-2 border-t-0 border-black">
            <tbody>
              {/* 헤더 행 */}
              <tr>
                <td className="bg-yellow-100 text-center font-bold border-b border-r border-black px-1 py-1.5" rowSpan={8} style={{ width: '45px' }}>
                  중간검사<br />기준서
                </td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '75px' }}>도해</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '50px' }}>검사항목</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" colSpan={3}>검사기준</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '55px' }}>검사방법</td>
                <td className="bg-gray-50 text-center border-b border-r border-black px-1 py-1 font-semibold" style={{ width: '65px' }}>검사주기</td>
                <td className="bg-gray-50 text-center border-b border-black px-1 py-1 font-semibold" style={{ width: '85px' }}>관련규정</td>
              </tr>
              {/* 겉모양 - 가공상태 */}
              <tr>
                <td className="border-b border-r border-black p-1 align-middle" rowSpan={7}>
                  {/* 도해 다이어그램 - 조인트바 이미지 */}
                  <div className="w-full h-36 bg-gray-100 border border-gray-300 relative mx-auto flex flex-col items-center justify-center">
                    {/* 상단 슬랫 이미지 */}
                    <div className="flex items-center gap-2 mb-2">
                      <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-black text-[8px] font-bold">1</span>
                      <div className="w-12 h-3 bg-gray-400 rounded-sm"></div>
                      <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-black text-[8px] font-bold">2</span>
                    </div>
                    {/* 메인 슬랫 본체 */}
                    <div className="relative w-16 h-16 border border-gray-400 bg-gray-200 mb-1">
                      <div className="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-2">
                        <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-black text-[8px] font-bold">4</span>
                      </div>
                      <div className="absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2 text-[7px] text-gray-500 border border-dashed border-yellow-500 rounded-full px-1">조립상태</div>
                    </div>
                    {/* 하단 ③ 표시 */}
                    <div className="flex items-center gap-1">
                      <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-black text-[8px] font-bold">3</span>
                    </div>
                  </div>
                </td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle font-semibold" rowSpan={3}>겉모양</td>
                <td className="border-b border-r border-black px-1 py-2 text-center" colSpan={2}>가공상태</td>
                <td className="border-b border-r border-black px-1 py-2 text-center">사용상 해로운 결함이 없을것</td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" rowSpan={3}>육안검사</td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" rowSpan={7}>n = 1, c = 0</td>
                <td className="border-b border-black px-1 py-2 text-center">KS F 4510 5.1항</td>
              </tr>
              {/* 겉모양 - 조립상태 (위) */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" colSpan={2} rowSpan={2}>조립상태</td>
                <td className="border-b border-r border-black px-1 py-2 text-center leading-relaxed text-[8px]">앤드락이 용접에 의해<br />견고하게 조립되어야 함</td>
                <td className="border-b border-black px-1 py-1 text-center">KS F 4510 9항</td>
              </tr>
              {/* 겉모양 - 조립상태 (아래) */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center leading-relaxed text-[8px]">용접부위에 락카도색이<br />되어야 함</td>
                <td className="border-b border-black px-1 py-1 text-center">자체규정</td>
              </tr>
              {/* 치수 - 높이① */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle font-semibold" rowSpan={4}>치수<br />(mm)</td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" rowSpan={2}>높이</td>
                <td className="border-b border-r border-black px-1 py-2 text-center" style={{ width: '25px' }}>
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">①</span>
                </td>
                <td className="border-b border-r border-black px-1 py-2 text-center">16.5 &nbsp;± 1</td>
                <td className="border-b border-r border-black px-1 py-2 text-center align-middle" rowSpan={4}>체크검사</td>
                <td className="border-b border-black px-1 py-2 text-center" rowSpan={3}>KS F 4510 7항<br />표9</td>
              </tr>
              {/* 치수 - 높이② */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center">
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">②</span>
                </td>
                <td className="border-b border-r border-black px-1 py-2 text-center">14.5 &nbsp;± 1</td>
              </tr>
              {/* 치수 - 길이③ */}
              <tr>
                <td className="border-b border-r border-black px-1 py-2 text-center">길이</td>
                <td className="border-b border-r border-black px-1 py-2 text-center">
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">③</span>
                </td>
                <td className="border-b border-r border-black px-1 py-2 text-center">300(앤드락제외) &nbsp;± 4</td>
              </tr>
              {/* 치수 - 간격④ */}
              <tr>
                <td className="border-r border-black px-1 py-2 text-center">간격</td>
                <td className="border-r border-black px-1 py-2 text-center">
                  <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-gray-500 text-[8px]">④</span>
                </td>
                <td className="border-r border-black px-1 py-2 text-center">150 &nbsp;± 4</td>
                <td className="border-black px-1 py-2 text-center">자체규정</td>
              </tr>
            </tbody>
          </table>

          {/* 중간검사 DATA */}
          <div className="border-2 border-t-0 border-black">
            <div className="bg-gray-100 px-2 py-1 font-bold border-b border-black text-center">중간검사 DATA</div>

            {/* 중간검사 DATA 테이블 */}
            <table className="w-full border-collapse text-[9px]">
              <thead>
                {/* 1행: 일련번호 / 겉모양 / 치수 (mm) / 판정 */}
                <tr className="bg-gray-50">
                  <th className="px-1 py-1" rowSpan={3} style={{ borderBottom: '1px solid black', borderRight: '1px solid black', width: '40px' }}>일련<br />번호</th>
                  <th className="px-1 py-1" colSpan={2} style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>겉모양</th>
                  <th className="px-1 py-1" colSpan={8} style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>치수 (mm)</th>
                  <th className="px-1 py-1" rowSpan={3} style={{ borderBottom: '1px solid black', width: '60px' }}>판정</th>
                </tr>
                {/* 2행: 가공상태/조립상태 + ①높이/②높이/③길이/④간격 */}
                <tr className="bg-gray-50">
                  <th className="px-1 py-1" rowSpan={2} style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>가공상태</th>
                  <th className="px-1 py-1" rowSpan={2} style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>조립상태</th>
                  <th className="px-1 py-1" colSpan={2} style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>① 높이</th>
                  <th className="px-1 py-1" colSpan={2} style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>② 높이</th>
                  <th className="px-1 py-1" colSpan={2} style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>③ 길이 (미미제외)</th>
                  <th className="px-1 py-1" colSpan={2} style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>④ 간격</th>
                </tr>
                {/* 3행: 기준치/측정값 */}
                <tr className="bg-gray-50">
                  <th className="px-1 py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>기준치</th>
                  <th className="px-1 py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>측정값</th>
                  <th className="px-1 py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>기준치</th>
                  <th className="px-1 py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>측정값</th>
                  <th className="px-1 py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>기준치</th>
                  <th className="px-1 py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>측정값</th>
                  <th className="px-1 py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>기준치</th>
                  <th className="px-1 py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>측정값</th>
                </tr>
              </thead>
              <tbody>
                {[1, 2, 3, 4, 5].map(i => (
                  <tr key={i}>
                    <td className="px-1 py-1 text-center font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{i}</td>
                    <td className="px-1 py-1 text-center" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>□ 양호 □ 불량</td>
                    <td className="px-1 py-1 text-center" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>□ 양호 □ 불량</td>
                    <td className="px-1 py-1 text-center font-bold text-blue-600" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>16.5 ± 1</td>
                    <td className="px-1 py-1 text-center" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                    <td className="px-1 py-1 text-center font-bold text-blue-600" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>14.5 ± 1</td>
                    <td className="px-1 py-1 text-center" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                    <td className="px-1 py-1 text-center font-bold text-blue-600" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>300 ± 4</td>
                    <td className="px-1 py-1 text-center" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                    <td className="px-1 py-1 text-center font-bold text-blue-600" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>150 ± 4</td>
                    <td className="px-1 py-1 text-center" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                    <td className="px-1 py-1 text-center" style={{ borderBottom: '1px solid black' }}>□ 적합 □ 부적합</td>
                  </tr>
                ))}
                {/* 부적합 내용 + 종합판정 행 */}
                <tr>
                  <td colSpan={11} style={{ borderRight: '1px solid black', padding: 0, verticalAlign: 'top' }}>
                    <div className="px-2 py-1 font-bold border-b border-black bg-gray-50">[부적합 내용]</div>
                    <div className="h-24"></div>
                  </td>
                  <td style={{ padding: 0, verticalAlign: 'top' }}>
                    <div className="bg-yellow-300 text-center font-bold px-2 py-1 border-b border-black">종합판정</div>
                    <div className="h-24 flex items-center justify-center">
                      <span className="text-lg font-bold"></span>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 문서번호 푸터 */}
          <div className="flex justify-between items-center mt-4 text-[10px] font-bold">
            <span>KDQP-01-009</span>
            <span>KDPS-10-03</span>
          </div>
        </div>
      );
    }

    // 제품검사성적서 미리보기 (FQC) - 작업일지 스타일 적용
    if (docCode === 'FQC') {
      return (
        <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '10mm', fontSize: '10px' }}>
          {/* 헤더 - KD 스타일 (작업일지 스타일) */}
          {renderKDHeader(<>제품검사성적서</>, '', {
            writer: '김검사',
            reviewer: '',
            approver: '박승인',
            writerDept: '품질',
            reviewerDept: '',
            approverDept: '품질'
          })}

          {/* 기본정보 테이블 */}
          <table className="w-full border-collapse text-[10px]" style={{ border: '2px solid black' }}>
            <tbody>
              <tr>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>상 품 명</td>
                <td className="px-2 py-1.5" style={{ width: '38%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.itemName || '자동방화셔터(인정)'}</td>
                <td className="text-center bg-yellow-200 py-1.5 font-bold" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>제품 LOT NO</td>
                <td className="px-2 py-1.5 font-bold" style={{ borderBottom: '1px solid black' }}>KD-SA-251218-01</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>제 품 명</td>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>WY-SC780 방화셔터</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>로 트 크 기</td>
                <td className="px-2 py-1.5 text-right" style={{ borderBottom: '1px solid black' }}>EA</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 처</td>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.customerName || '(주)OO건설'}</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>검 사 일 자</td>
                <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}>2023. &nbsp; &nbsp; .</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black' }}>현 장 명</td>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black' }}>{sampleData.siteName || 'OO아파트 신축공사'}</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black' }}>검 사 자</td>
                <td className="px-2 py-1.5"></td>
              </tr>
            </tbody>
          </table>

          {/* 제품사진 영역 */}
          <table className="w-full border-collapse text-[9px] border-2 border-t-0 border-black">
            <tbody>
              <tr>
                <td className="text-center bg-yellow-100 py-2 font-bold align-middle" style={{ width: '10%', borderRight: '1px solid black' }}>제품사진</td>
                <td className="p-3" style={{ minHeight: '180px' }}>
                  {/* 제품 도해 영역 - 첨부파일 기준 */}
                  <div className="flex justify-between items-start gap-4">
                    {/* 왼쪽: 방화셔터 전체 도해 */}
                    <div className="relative w-56 h-44 border border-gray-400 bg-gray-50 flex-shrink-0">
                      {/* 셔터박스 */}
                      <div className="absolute top-1 left-1/2 -translate-x-1/2 w-40 h-6 border border-gray-500 bg-gray-200 flex items-center justify-center">
                        <div className="w-full border-b border-gray-400"></div>
                      </div>
                      {/* ① 번호 */}
                      <div className="absolute top-4 left-8">
                        <span className="inline-flex items-center justify-center w-5 h-5 rounded-full border-2 border-black text-[10px] font-bold bg-white">①</span>
                      </div>
                      {/* 스크린 원단 영역 */}
                      <div className="absolute top-8 left-1/2 -translate-x-1/2 w-36 h-28 border border-gray-400 bg-gray-100">
                        {/* 가로줄 패턴 */}
                        {[...Array(12)].map((_, i) => (
                          <div key={i} className="border-b border-gray-300" style={{ height: '8%' }}></div>
                        ))}
                      </div>
                      {/* ③ 번호 */}
                      <div className="absolute bottom-6 left-6">
                        <span className="inline-flex items-center justify-center w-5 h-5 rounded-full border-2 border-black text-[10px] font-bold bg-white">③</span>
                      </div>
                      {/* ④ 번호 */}
                      <div className="absolute bottom-6 right-6">
                        <span className="inline-flex items-center justify-center w-5 h-5 rounded-full border-2 border-black text-[10px] font-bold bg-white">④</span>
                      </div>
                      {/* 하단 가이드레일 홈 간격 설명 */}
                      <div className="absolute bottom-0 left-1/2 -translate-x-1/2 text-[8px] text-gray-600 text-center">
                        <div>가이드레일 홈 간격 측정</div>
                        <div className="flex items-center justify-center gap-1">
                          <span className="inline-flex items-center justify-center w-3 h-3 rounded-full border border-black text-[7px]">ⓐ</span>
                          <span>높이 100 이내</span>
                        </div>
                      </div>
                    </div>
                    {/* 오른쪽: 가이드레일 상세 도해 */}
                    <div className="flex flex-col gap-3 flex-shrink-0">
                      {/* 가이드레일 벽면형 */}
                      <div className="relative w-28 h-16 border border-gray-400 bg-gray-50">
                        <div className="absolute top-1 right-1">
                          <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-black text-[8px] font-bold">②</span>
                        </div>
                        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-[8px] text-gray-500">
                          [단면도]
                        </div>
                        <div className="absolute bottom-1 left-1/2 -translate-x-1/2 text-[7px] font-semibold">가이드레일 벽면형</div>
                      </div>
                      {/* 가이드레일 측면형 */}
                      <div className="relative w-28 h-16 border border-gray-400 bg-gray-50">
                        <div className="absolute top-1 right-1">
                          <span className="inline-flex items-center justify-center w-4 h-4 rounded-full border border-black text-[8px] font-bold">②</span>
                        </div>
                        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-[8px] text-gray-500">
                          [단면도]
                        </div>
                        <div className="absolute bottom-1 left-1/2 -translate-x-1/2 text-[7px] font-semibold">가이드레일 측면형</div>
                      </div>
                    </div>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>

          {/* 검사항목 테이블 - 검사항목(단일)/검사기준(colSpan=3) 구조로 재구성 */}
          <table className="w-full border-collapse text-[9px] border-2 border-t-0 border-black">
            <thead>
              <tr className="bg-gray-100">
                <th className="py-1.5 font-bold text-center" style={{ width: '4%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>No</th>
                <th className="py-1.5 font-bold text-center" style={{ width: '8%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사항목</th>
                <th className="py-1.5 font-bold text-center" colSpan={3} style={{ width: '38%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사기준</th>
                <th className="py-1.5 font-bold text-center" style={{ width: '10%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사방법</th>
                <th className="py-1.5 font-bold text-center" style={{ width: '10%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사주기</th>
                <th className="py-1.5 font-bold text-center" style={{ width: '14%', borderBottom: '1px solid black' }}>판정</th>
              </tr>
            </thead>
            <tbody>
              {/* 1. 겉모양 - 검사기준: 가공상태/재봉상태/조립상태/연기차단재/하단마감재 */}
              <tr>
                <td className="text-center py-1" rowSpan={5} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>1</td>
                <td className="text-center py-1" rowSpan={5} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>겉모양</td>
                <td className="py-1 px-1 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>가공상태</td>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>사용상 해로운 결함이 없을 것</td>
                <td className="text-center py-1" rowSpan={5} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>육안검사</td>
                <td className="text-center py-1" rowSpan={5} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>전수검사</td>
                <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}>□ 적합 &nbsp; □ 부적합</td>
              </tr>
              <tr>
                <td className="py-1 px-1 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>재봉상태</td>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>내화실에 의해 견고하게 접합되어야 함</td>
                <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}>□ 적합 &nbsp; □ 부적합</td>
              </tr>
              <tr>
                <td className="py-1 px-1 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>조립상태</td>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>앤드락이 견고하게 조립되어야 함</td>
                <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}>□ 적합 &nbsp; □ 부적합</td>
              </tr>
              <tr>
                <td className="py-1 px-1 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>연기차단재</td>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>연기차단재 설치여부(케이스 W80, 가이드레일 W50(양쪽설치))</td>
                <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}>□ 적합 &nbsp; □ 부적합</td>
              </tr>
              <tr>
                <td className="py-1 px-1 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>하단마감재</td>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>내부 무게평철 설치 유무</td>
                <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}>□ 적합 &nbsp; □ 부적합</td>
              </tr>

              {/* 2. 모터 */}
              <tr>
                <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>2</td>
                <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>모터</td>
                <td className="py-1 px-1 text-center" colSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>인정제품과 동일사양</td>
                <td className="text-center py-1" rowSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                <td className="text-center py-1" rowSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}>□ 적합 &nbsp; □ 부적합</td>
              </tr>

              {/* 3. 재질 */}
              <tr>
                <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>3</td>
                <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>재질</td>
                <td className="py-1 px-1 text-center" colSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>WY-SC780 인쇄상태 확인</td>
                <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}>□ 적합 &nbsp; □ 부적합</td>
              </tr>

              {/* 4. 치수(오픈사이즈) - 검사기준: 길이/높이/가이드레일홈간격/하단마감재간격 */}
              <tr>
                <td className="text-center py-1" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>4</td>
                <td className="text-center py-1 whitespace-nowrap" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>치수<br />(오픈사이즈)</td>
                <td className="py-1 px-1 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>길이</td>
                <td className="py-1 px-1 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발주치수 ± 30mm</td>
                <td className="text-center py-1" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>체크검사</td>
                <td className="text-center py-1" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>전수검사</td>
                <td className="py-1 px-1 text-[8px]" style={{ borderBottom: '1px solid black' }}>측정값( &nbsp; &nbsp; &nbsp; )<br />□ 적합 &nbsp; □ 부적합</td>
              </tr>
              <tr>
                <td className="py-1 px-1 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>높이</td>
                <td className="py-1 px-1 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발주치수 ± 30mm</td>
                <td className="py-1 px-1 text-[8px]" style={{ borderBottom: '1px solid black' }}>측정값( &nbsp; &nbsp; &nbsp; )<br />□ 적합 &nbsp; □ 부적합</td>
              </tr>
              <tr>
                <td className="py-1 px-1 text-center whitespace-nowrap" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>가이드레일<br />홈간격</td>
                <td className="py-1 px-1 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>10 ± 5mm(측정부위 : ⓐ 높이 100 이내)</td>
                <td className="py-1 px-1 text-[8px]" style={{ borderBottom: '1px solid black' }}>측정값( &nbsp; &nbsp; &nbsp; )<br />□ 적합 &nbsp; □ 부적합</td>
              </tr>
              <tr>
                <td className="py-1 px-1 text-center whitespace-nowrap" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>하단마감재간격</td>
                <td className="py-1 px-1 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>간격 (③+④)</td>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>가이드레일과 하단마감재 틈새 25mm 이내</td>
                <td className="py-1 px-1 text-[8px]" style={{ borderBottom: '1px solid black' }}>측정값( &nbsp; &nbsp; &nbsp; )<br />□ 적합 &nbsp; □ 부적합</td>
              </tr>

              {/* 5. 작동테스트 - 검사기준: 개폐성능 */}
              <tr>
                <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>5</td>
                <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>작동테스트</td>
                <td className="py-1 px-1 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>개폐성능</td>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>작동 유무 확인(일부 및 완전폐쇄)</td>
                <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}>□ 적합 &nbsp; □ 부적합</td>
              </tr>

              {/* 6. 내화시험 - 검사기준: 비차열 | 차염성 (별도 컬럼) */}
              <tr>
                <td className="text-center py-1" rowSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>6</td>
                <td className="text-center py-1" rowSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>내화시험</td>
                <td className="text-center py-1" rowSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>비<br />차<br />열</td>
                <td className="text-center py-1" rowSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>차<br />염<br />성</td>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>6mm 균열게이지 관통 후 150mm 이동 유무</td>
                <td className="text-center py-1 whitespace-nowrap" rowSpan={9} style={{ borderRight: '1px solid black', borderBottom: '1px solid black', fontSize: '8px' }}>공인 시험기관<br />시험성적서</td>
                <td className="text-center py-1" rowSpan={9} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>1회 / 5년</td>
                <td className="text-center py-1" rowSpan={9} style={{ borderBottom: '1px solid black' }}>□ 적합 &nbsp; □ 부적합</td>
              </tr>
              <tr>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>25mm 균열게이지 관통 유무</td>
              </tr>
              <tr>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>10초 이상 지속되는 화염발생 유무</td>
              </tr>

              {/* 7. 차연시험 - 검사기준: 공기누설량 */}
              <tr>
                <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>7</td>
                <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>차연시험</td>
                <td className="py-1 px-1 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>공기누설량</td>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>25Pa 일때 공기누설량 0.9㎥/min·㎡ 이하</td>
              </tr>

              {/* 8. 개폐시험 - 검사기준: 평균속도 등 */}
              <tr>
                <td className="text-center py-1" rowSpan={5} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>8</td>
                <td className="text-center py-1" rowSpan={5} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>개폐시험</td>
                <td className="py-1 px-1 text-center" colSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>개폐의 원활한 작동</td>
              </tr>
              <tr>
                <td className="text-center py-1" colSpan={2} rowSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>평균속도</td>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>전동개폐 2.5 ~ 6.5m/min</td>
              </tr>
              <tr>
                <td className="py-1 px-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>자중강하 3 ~ 7m/min</td>
              </tr>
              <tr>
                <td className="py-1 px-1 text-center" colSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>개폐 시 상부 및 하부 끝부분에서 자동정지</td>
              </tr>
              <tr>
                <td className="py-1 px-1 text-center" colSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>강하 중 임의의 위치에서 정지</td>
              </tr>

              {/* 9. 내충격시험 */}
              <tr>
                <td className="text-center py-1" style={{ borderRight: '1px solid black' }}>9</td>
                <td className="text-center py-1" style={{ borderRight: '1px solid black' }}>내충격시험</td>
                <td className="py-1 px-1 text-center" colSpan={3} style={{ borderRight: '1px solid black' }}>방화상 유해한 파괴, 박리 탈락 유무</td>
                <td className="text-center py-1" style={{ borderRight: '1px solid black' }}></td>
                <td className="text-center py-1" style={{ borderRight: '1px solid black' }}></td>
                <td className="text-center py-1">□ 적합 &nbsp; □ 부적합</td>
              </tr>
            </tbody>
          </table>

          {/* 특이사항 및 종합판정 */}
          <table className="w-full border-collapse text-[9px] border-2 border-t-0 border-black">
            <tbody>
              <tr>
                <td className="bg-gray-100 font-bold py-1.5 px-2 align-top" style={{ width: '10%', borderRight: '1px solid black' }}>[특이사항]</td>
                <td className="px-2 py-1.5 align-top" style={{ borderRight: '1px solid black', minHeight: '40px' }}>
                  <p className="text-[9px]">1. 내화시험, 차연시험, 개폐시험, 내충격시험의 경우 공인시험기관에서 시험을 진행하며, 그 시험성적서로 갈음한다.</p>
                </td>
                <td className="bg-yellow-200 text-center font-bold py-2 align-middle" style={{ width: '12%' }}>
                  <div className="text-base">종합판정</div>
                </td>
              </tr>
            </tbody>
          </table>

          {/* 문서번호 푸터 */}
          <div className="flex justify-between mt-3 text-[9px] text-gray-600">
            <div>KDQP-01-005</div>
            <div className="font-semibold">㈜경동기업</div>
          </div>
        </div>
      );
    }

    // 수입검사성적서 미리보기 (IQC) - KD 헤더 스타일 적용
    if (docCode === 'IQC') {
      const iqcData = sampleData.incomingInspectionData;
      return (
        <div className="bg-white shadow-lg mx-auto text-xs" style={{ width: '210mm', minHeight: '297mm', padding: '15mm' }}>
          {/* KD 로고 헤더 + 결재란 - 작업일지 스타일 */}
          {renderKDHeader('수 입 검 사 성 적 서', '품질관리부서', {
            writer: iqcData.inspector || '품질담당',
            writerDate: iqcData.inspectionDate,
            writerDept: '자재/입고',
            reviewerDept: '품질',
            approverDept: '품질팀장'
          })}

          {/* 입고일자 표시 */}
          <div className="text-right text-[10px] mb-1 -mt-1">
            <span className="font-semibold">입고일자:</span> {iqcData.receiveDate}
          </div>

          {/* 기본정보 테이블 */}
          <table className="w-full border-collapse text-[10px]" style={{ border: '2px solid black' }}>
            <tbody>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ width: '15%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>품  명</th>
                <td className="px-2 py-1.5" style={{ width: '35%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>{iqcData.itemName}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ width: '15%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>납품/제조업체</th>
                <td className="px-2 py-1.5 font-bold text-blue-600" style={{ borderBottom: '1px solid black' }}>{iqcData.supplierName}</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>규  격</th>
                <td className="px-2 py-1.5 font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{iqcData.spec}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>로트번호</th>
                <td className="px-2 py-1.5 font-bold text-blue-600" style={{ borderBottom: '1px solid black' }}>{iqcData.lotNo}</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>자재번호</th>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{iqcData.materialNo}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사일자</th>
                <td className="px-2 py-1.5 font-bold text-blue-600" style={{ borderBottom: '1px solid black' }}>{iqcData.inspectionDate}</td>
              </tr>
              <tr>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black' }}>로트크기</th>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black' }}>{iqcData.lotSize} {iqcData.lotUnit}</td>
                <th className="bg-gray-100 px-2 py-1.5 text-center font-semibold" style={{ borderRight: '1px solid black' }}>검사자</th>
                <td className="px-2 py-1.5">{iqcData.inspector}</td>
              </tr>
            </tbody>
          </table>

          {/* 검사항목 테이블 - 첨부파일 기준 완전 구현 */}
          <table className="w-full border-collapse text-[10px] mt-2" style={{ border: '2px solid black' }}>
            <thead>
              <tr>
                <th className="bg-gray-100 px-1 py-2 text-center font-bold" rowSpan={2} style={{ width: '4%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>NO</th>
                <th className="bg-gray-100 px-1 py-2 text-center font-bold" rowSpan={2} style={{ width: '10%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사항목</th>
                <th className="bg-gray-100 px-1 py-2 text-center font-bold" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사기준</th>
                <th className="bg-gray-100 px-1 py-2 text-center font-bold" rowSpan={2} style={{ width: '8%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사방식</th>
                <th className="bg-gray-100 px-1 py-2 text-center font-bold" rowSpan={2} style={{ width: '7%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사주기</th>
                <th className="bg-gray-100 px-1 py-2 text-center font-bold" colSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>측정치</th>
                <th className="bg-gray-100 px-1 py-2 text-center font-bold" rowSpan={2} style={{ width: '6%', borderBottom: '1px solid black' }}>판정<br />(적/부)</th>
              </tr>
              <tr>
                <th className="bg-gray-100 px-1 py-1 text-center font-bold" style={{ width: '8%', borderRight: '1px solid black', borderBottom: '1px solid black' }}></th>
                <th className="bg-gray-100 px-1 py-1 text-center font-bold" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}></th>
                <th className="bg-gray-100 px-1 py-1 text-center font-bold" style={{ width: '9%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>n1<br />양호/불량</th>
                <th className="bg-gray-100 px-1 py-1 text-center font-bold" style={{ width: '9%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>n2<br />양호/불량</th>
                <th className="bg-gray-100 px-1 py-1 text-center font-bold" style={{ width: '9%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>n3<br />양호/불량</th>
              </tr>
            </thead>
            <tbody>
              {/* 1. 겉모양 */}
              <tr>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>1</td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>겉모양</td>
                <td className="px-2 py-2 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>사용상 해로운<br />결함이 없을 것</td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>육안검사</td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-flex items-center text-[9px]">
                    <span className="text-green-600 font-bold">✓</span>OK<span className="mx-0.5 inline-block w-3 h-3 rounded-full bg-gray-300"></span>NG
                  </span>
                </td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-flex items-center text-[9px]">
                    <span className="text-green-600 font-bold">✓</span>OK<span className="mx-0.5 inline-block w-3 h-3 rounded-full bg-gray-300"></span>NG
                  </span>
                </td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-flex items-center text-[9px]">
                    <span className="text-green-600 font-bold">✓</span>OK<span className="mx-0.5 inline-block w-3 h-3 rounded-full bg-gray-300"></span>NG
                  </span>
                </td>
                <td className="px-1 py-2 text-center font-bold" style={{ borderBottom: '1px solid black' }}>적</td>
              </tr>

              {/* 2. 치수 - 두께 */}
              <tr>
                <td className="px-1 py-1 text-center" rowSpan={12} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>2</td>
                <td className="px-1 py-1 text-center" rowSpan={12} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>치수</td>
                <td className="px-1 py-1 text-center" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>두께<br />1.55</td>
                <td className="px-1 py-1 text-[9px]" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-block w-3 h-3 border border-black mr-1"></span>0.8 이상<br />
                  <span className="ml-4">~ 1.0 미만</span>
                  <span className="float-right">± 0.07</span>
                </td>
                <td className="px-1 py-1 text-center" rowSpan={12} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>체크검사</td>
                <td className="px-1 py-1 text-center" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>n = 3<br />c = 0</td>
                <td className="px-1 py-1 text-center" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>1.528</td>
                <td className="px-1 py-1 text-center" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>1.533</td>
                <td className="px-1 py-1 text-center" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>1.521</td>
                <td className="px-1 py-1 text-center font-bold" rowSpan={4} style={{ borderBottom: '1px solid black' }}>적</td>
              </tr>
              <tr>
                <td className="px-1 py-1 text-[9px]" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-block w-3 h-3 border border-black mr-1"></span>1.0 이상<br />
                  <span className="ml-4">~ 1.25 미만</span>
                  <span className="float-right">± 0.08</span>
                </td>
              </tr>
              <tr>
                <td className="px-1 py-1 text-[9px] bg-gray-100" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-block w-3 h-3 border border-black mr-1 bg-green-500 text-white text-center leading-3">✓</span>1.25 이상<br />
                  <span className="ml-4">~ 1.6 미만</span>
                  <span className="float-right font-bold">± 0.10</span>
                </td>
              </tr>
              <tr>
                <td className="px-1 py-1 text-[9px] bg-gray-200" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-block w-3 h-3 border border-black mr-1"></span><strong>1.6 이상</strong><br />
                  <span className="ml-4"><strong>~ 2.0 미만</strong></span>
                  <span className="float-right font-bold">± 0.12</span>
                </td>
              </tr>

              {/* 치수 - 너비 */}
              <tr>
                <td className="px-1 py-1 text-center" rowSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>너비<br />1219</td>
                <td className="px-1 py-1 text-[9px] bg-gray-100" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-block w-3 h-3 border border-black mr-1 bg-green-500 text-white text-center leading-3">✓</span>1250 미만
                  <span className="float-right">+ 7<br />- 0</span>
                </td>
                <td className="px-1 py-1 text-center" rowSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                <td className="px-1 py-1 text-center" rowSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>1222</td>
                <td className="px-1 py-1 text-center" rowSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>1222</td>
                <td className="px-1 py-1 text-center" rowSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>1222</td>
                <td className="px-1 py-1 text-center font-bold" rowSpan={2} style={{ borderBottom: '1px solid black' }}>적</td>
              </tr>
              <tr>
                <td className="px-1 py-1 text-[9px]" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
              </tr>

              {/* 치수 - 길이 */}
              <tr>
                <td className="px-1 py-1 text-center" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>길이<br />480</td>
                <td className="px-1 py-1 text-[9px] bg-gray-100" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-block w-3 h-3 border border-black mr-1 bg-green-500 text-white text-center leading-3">✓</span>1250 미만
                  <span className="float-right">+ 10<br />- 0</span>
                </td>
                <td className="px-1 py-1 text-center" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                <td className="px-1 py-1 text-center" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>480</td>
                <td className="px-1 py-1 text-center" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>480</td>
                <td className="px-1 py-1 text-center" rowSpan={4} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>480</td>
                <td className="px-1 py-1 text-center font-bold" rowSpan={4} style={{ borderBottom: '1px solid black' }}>적</td>
              </tr>
              <tr>
                <td className="px-1 py-1 text-[9px]" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-block w-3 h-3 border border-black mr-1"></span>2000 이상<br />
                  <span className="ml-4">~ 4000 미만</span>
                  <span className="float-right">+ 15<br />- 0</span>
                </td>
              </tr>
              <tr>
                <td className="px-1 py-1 text-[9px]" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-block w-3 h-3 border border-black mr-1"></span>4000 이상<br />
                  <span className="ml-4">~ 6000 미만</span>
                  <span className="float-right">+ 20<br />- 0</span>
                </td>
              </tr>
              <tr>
                <td className="px-1 py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
              </tr>

              {/* 3. 인장강도 */}
              <tr>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>3</td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>인장강도 (N/㎟)</td>
                <td className="px-2 py-2 text-center" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>270 이상</td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                <td className="px-1 py-2 text-center" colSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>313.8</td>
                <td className="px-1 py-2 text-center font-bold" style={{ borderBottom: '1px solid black' }}>적</td>
              </tr>

              {/* 4. 연신율 */}
              <tr>
                <td className="px-1 py-1 text-center" rowSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>4</td>
                <td className="px-1 py-1 text-center" rowSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>연신율<br />%</td>
                <td className="px-1 py-1 text-[9px]" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-block w-3 h-3 border border-black mr-1"></span>두께 0.6 이상<br />
                  <span className="ml-4">~ 1.0 미만</span>
                </td>
                <td className="px-1 py-1 text-center text-[9px]" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>36 이상</td>
                <td className="px-1 py-1 text-center" rowSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>공급업체<br />밀시트</td>
                <td className="px-1 py-1 text-center" rowSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>입고시</td>
                <td className="px-1 py-1 text-center" colSpan={3} rowSpan={3} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>46.5</td>
                <td className="px-1 py-1 text-center font-bold" rowSpan={3} style={{ borderBottom: '1px solid black' }}>적</td>
              </tr>
              <tr>
                <td className="px-1 py-1 text-[9px] bg-gray-100" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-block w-3 h-3 border border-black mr-1 bg-green-500 text-white text-center leading-3">✓</span>두께 1.0 이상<br />
                  <span className="ml-4">~ 1.6 미만</span>
                </td>
                <td className="px-1 py-1 text-center text-[9px]" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>37 이상</td>
              </tr>
              <tr>
                <td className="px-1 py-1 text-[9px] bg-gray-200" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="inline-block w-3 h-3 border border-black mr-1"></span><strong>두께 1.6 이상</strong><br />
                  <span className="ml-4"><strong>~ 2.3 미만</strong></span>
                </td>
                <td className="px-1 py-1 text-center text-[9px] font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>38 이상</td>
              </tr>

              {/* 5. 아연의 최소 부착량 */}
              <tr>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black' }}>5</td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black' }}>아연의 최소<br />부착량 (g/㎡)</td>
                <td className="px-2 py-2 text-center" colSpan={2} style={{ borderRight: '1px solid black' }}>한면 17 이상</td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black' }}></td>
                <td className="px-1 py-2 text-center" style={{ borderRight: '1px solid black' }}></td>
                <td className="px-1 py-2 text-center" colSpan={3} style={{ borderRight: '1px solid black' }}>17.21 / 17.17</td>
                <td className="px-1 py-2 text-center font-bold">적</td>
              </tr>
            </tbody>
          </table>

          {/* 비고 영역 */}
          <div className="border border-black border-t-0 p-2 min-h-[40px] text-[9px]">
            {iqcData.remarks.map((remark, i) => (
              <p key={i}>{remark}</p>
            ))}
          </div>

          {/* 종합판정 */}
          <div className="border border-black border-t-0 text-right px-4 py-1 bg-gray-100 text-[10px] font-bold">
            종합판정
          </div>

          {/* 부적합 내용 및 판정 */}
          <div className="border-2 border-black mt-4">
            <div className="flex">
              <div className="flex-1 p-2 min-h-[60px]">
                <div className="text-[9px] text-gray-500">[부적합 내용]</div>
              </div>
              <div className="w-32 border-l border-black flex items-center justify-center bg-yellow-50">
                <span className="text-2xl font-bold">{iqcData.overallJudgement}</span>
              </div>
            </div>
          </div>
        </div>
      );
    }

    // 거래명세서 미리보기 (심플 스타일 - 결재란 없음)
    if (docCode === 'SL') {
      return (
        <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '20mm' }}>
          {/* 제목 */}
          <h1 className="text-2xl font-bold tracking-[0.5em] text-center mb-4">거 래 명 세 서</h1>

          {/* 문서번호/발행일 */}
          <div className="text-center text-sm mb-8">
            <span>수주번호: </span>
            <span className="font-mono">{sampleData.orderNo || 'KD-SO-250215-01'}</span>
            <span className="mx-2">|</span>
            <span>발행일: </span>
            <span>{sampleData.issueDate || '2025-02-15'}</span>
          </div>

          {/* 공급자/공급받는자 - 2열 테이블 */}
          <div className="grid grid-cols-2 gap-6 mb-8">
            {/* 공급자 */}
            <div className="border-2 border-black">
              <div className="bg-gray-100 text-center py-2 font-bold border-b-2 border-black">공급자</div>
              <table className="w-full text-sm">
                <tbody>
                  <tr className="border-b border-gray-300">
                    <th className="px-4 py-2.5 bg-gray-50 w-24 text-left">상 호</th>
                    <td className="px-4 py-2.5">{sampleData.supplierName || '한국방화문(주)'}</td>
                  </tr>
                  <tr className="border-b border-gray-300">
                    <th className="px-4 py-2.5 bg-gray-50 text-left">대표자</th>
                    <td className="px-4 py-2.5">{sampleData.supplierCeo || '홍길동'}</td>
                  </tr>
                  <tr className="border-b border-gray-300">
                    <th className="px-4 py-2.5 bg-gray-50 text-left">사업자번호</th>
                    <td className="px-4 py-2.5">{sampleData.supplierBusinessNo || '123-45-67890'}</td>
                  </tr>
                  <tr>
                    <th className="px-4 py-2.5 bg-gray-50 text-left">주 소</th>
                    <td className="px-4 py-2.5">{sampleData.supplierAddress || '서울 강남구 테헤란로 123'}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            {/* 공급받는자 */}
            <div className="border-2 border-black">
              <div className="bg-gray-100 text-center py-2 font-bold border-b-2 border-black">공급받는자</div>
              <table className="w-full text-sm">
                <tbody>
                  <tr className="border-b border-gray-300">
                    <th className="px-4 py-2.5 bg-gray-50 w-24 text-left">상 호</th>
                    <td className="px-4 py-2.5">{sampleData.customerName || '삼성건설(주)'}</td>
                  </tr>
                  <tr className="border-b border-gray-300">
                    <th className="px-4 py-2.5 bg-gray-50 text-left">담당자</th>
                    <td className="px-4 py-2.5">{sampleData.customerManager || '이영희'}</td>
                  </tr>
                  <tr className="border-b border-gray-300">
                    <th className="px-4 py-2.5 bg-gray-50 text-left">연락처</th>
                    <td className="px-4 py-2.5">{sampleData.customerPhone || '010-2345-6789'}</td>
                  </tr>
                  <tr>
                    <th className="px-4 py-2.5 bg-gray-50 text-left">현장명</th>
                    <td className="px-4 py-2.5">{sampleData.siteName || '강남 타워 신축현장 (B동)'}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* 품목내역 제목 */}
          <div className="bg-black text-white text-center py-2.5 font-bold rounded-t-lg">
            품 목 내 역
          </div>

          {/* 품목내역 테이블 */}
          <table className="w-full border-collapse border-2 border-black border-t-0 mb-6 text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="border border-black px-2 py-2.5" style={{ width: '50px' }}>순번</th>
                <th className="border border-black px-2 py-2.5" style={{ width: '80px' }}>품목코드</th>
                <th className="border border-black px-2 py-2.5">품명</th>
                <th className="border border-black px-2 py-2.5">규격</th>
                <th className="border border-black px-2 py-2.5" style={{ width: '60px' }}>수량</th>
                <th className="border border-black px-2 py-2.5" style={{ width: '50px' }}>단위</th>
                <th className="border border-black px-2 py-2.5" style={{ width: '90px' }}>단가</th>
                <th className="border border-black px-2 py-2.5" style={{ width: '100px' }}>공급가액</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td className="border border-black px-2 py-2.5 text-center">1</td>
                <td className="border border-black px-2 py-2.5 text-center font-mono">FD-002</td>
                <td className="border border-black px-2 py-2.5">방화셔터</td>
                <td className="border border-black px-2 py-2.5 text-center">1200×2400</td>
                <td className="border border-black px-2 py-2.5 text-center">120</td>
                <td className="border border-black px-2 py-2.5 text-center">SET</td>
                <td className="border border-black px-2 py-2.5 text-right">400,000</td>
                <td className="border border-black px-2 py-2.5 text-right">48,000,000</td>
              </tr>
              {[2, 3].map(no => (
                <tr key={no}>
                  <td className="border border-black px-2 py-2.5 text-center"></td>
                  <td className="border border-black px-2 py-2.5"></td>
                  <td className="border border-black px-2 py-2.5"></td>
                  <td className="border border-black px-2 py-2.5"></td>
                  <td className="border border-black px-2 py-2.5"></td>
                  <td className="border border-black px-2 py-2.5"></td>
                  <td className="border border-black px-2 py-2.5"></td>
                  <td className="border border-black px-2 py-2.5"></td>
                </tr>
              ))}
            </tbody>
          </table>

          {/* 금액 요약 박스 */}
          <div className="border-2 border-black p-5 mb-8">
            <div className="space-y-3 text-sm">
              <div className="flex justify-between">
                <span className="font-semibold">공급가액</span>
                <span>48,000,000원</span>
              </div>
              <div className="flex justify-between text-red-600">
                <span className="font-semibold">할인율</span>
                <span>0%</span>
              </div>
              <div className="flex justify-between text-red-600">
                <span className="font-semibold">할인액</span>
                <span>-0원</span>
              </div>
              <div className="flex justify-between">
                <span className="font-semibold">할인 후 공급가액</span>
                <span>48,000,000원</span>
              </div>
              <div className="flex justify-between">
                <span className="font-semibold">부가세 (10%)</span>
                <span>4,800,000원</span>
              </div>
              <div className="border-t-2 border-black pt-3 mt-3 flex justify-between items-center">
                <span className="text-lg font-bold">합계 금액</span>
                <span className="text-2xl font-black">￦ 52,800,000</span>
              </div>
            </div>
          </div>

          {/* 하단 증명 문구 */}
          <div className="text-right mt-12">
            <p className="mb-6">위 금액을 거래하였음을 증명합니다.</p>
            <p className="font-semibold mb-6">{sampleData.issueDate || '2025-02-15'}</p>
            <div className="flex justify-end">
              <div className="border border-black w-16 h-16 flex items-center justify-center text-gray-400">
                인
              </div>
            </div>
          </div>
        </div>
      );
    }

    // ========== 제품검사신청서(FQC-REQ) 미리보기 ==========
    // 작업일지 스타일 적용 - 발주처에서 경동기업으로 신청하는 문서
    if (docCode === 'FQC-REQ') {
      return (
        <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '8mm', fontSize: '10px' }}>
          {/* 헤더 - KD 로고 + 제품검사요청서 제목 + 접수일 (작업일지 스타일) */}
          <table className="w-full border-collapse mb-2" style={{ border: '2px solid black' }}>
            <tbody>
              <tr>
                <td rowSpan="2" className="text-center align-middle p-2" style={{ width: '100px', borderRight: '1px solid black' }}>
                  <div className="text-2xl font-black">KD</div>
                  <div className="text-xs font-bold">경동기업</div>
                  <div style={{ fontSize: '8px' }} className="text-gray-500">KYUNGDONG COMPANY</div>
                </td>
                <td className="text-center align-middle py-3" style={{ borderRight: '1px solid black' }}>
                  <div className="text-xl font-black tracking-widest">자동방화셔터(인정제품) 제품검사요청서</div>
                </td>
                <td className="text-center align-middle p-2" style={{ width: '150px' }}>
                  <div className="text-xs mb-1">접수일</div>
                  <div className="border-b border-black pb-1">2024년    월    일</div>
                </td>
              </tr>
            </tbody>
          </table>

          {/* 기본정보 테이블 */}
          <table className="w-full border-collapse mb-2" style={{ border: '2px solid black' }}>
            <tbody>
              <tr>
                <td className="bg-blue-100 text-center font-bold py-1 px-2" style={{ width: '100px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발신처</td>
                <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{sampleData.customerName || '(주)OO건설'}</td>
                <td className="bg-blue-100 text-center font-bold py-1 px-2" style={{ width: '100px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발주번호</td>
                <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}>KD-PO-2024-001</td>
              </tr>
              <tr>
                <td className="bg-blue-100 text-center font-bold py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>현장명</td>
                <td className="py-1 px-2" colSpan="3" style={{ borderBottom: '1px solid black' }}>{sampleData.siteName || 'OO아파트 신축공사'}</td>
              </tr>
              <tr>
                <td className="bg-blue-100 text-center font-bold py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사대상</td>
                <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>자동방화셔터</td>
                <td className="bg-blue-100 text-center font-bold py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>수량</td>
                <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}>20 SET</td>
              </tr>
              <tr>
                <td className="bg-blue-100 text-center font-bold py-1 px-2" style={{ borderRight: '1px solid black' }}>담당자</td>
                <td className="py-1 px-2" style={{ borderRight: '1px solid black' }}>홍길동</td>
                <td className="bg-blue-100 text-center font-bold py-1 px-2" style={{ borderRight: '1px solid black' }}>연락처</td>
                <td className="py-1 px-2">010-0000-0000</td>
              </tr>
            </tbody>
          </table>

          {/* 검사방문요청일 */}
          <div className="mb-3 p-2 border-2 border-blue-300 bg-blue-50 rounded">
            <div className="flex items-center">
              <span className="font-bold text-blue-700 mr-2">검사방문요청일(전화예정):</span>
              <span className="border-b-2 border-blue-500 px-4 py-1 min-w-[200px]">2024년    월    일</span>
            </div>
          </div>

          {/* 입력사항 섹션 */}
          <div className="mb-3 border-2 border-black">
            <div className="bg-gray-200 text-center font-bold py-2 border-b border-black" style={{ fontSize: '12px' }}>
              입력사항 (품질관리서 동일정보)
            </div>
            <table className="w-full border-collapse">
              <tbody>
                {/* 1. 건축공사장 */}
                <tr>
                  <td className="bg-gray-100 text-center font-bold py-2" style={{ width: '30px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>1</td>
                  <td className="bg-gray-100 font-bold py-2 px-2" style={{ width: '120px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>건축공사장</td>
                  <td style={{ borderBottom: '1px solid black' }}>
                    <table className="w-full border-collapse">
                      <tbody>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black', width: '80px' }}>현장명</td>
                          <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}></td>
                        </tr>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>대지위치</td>
                          <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}></td>
                        </tr>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black' }}>건축주</td>
                          <td className="py-1 px-2"></td>
                        </tr>
                      </tbody>
                    </table>
                  </td>
                </tr>
                {/* 2. 자재유통업자 */}
                <tr>
                  <td className="bg-gray-100 text-center font-bold py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>2</td>
                  <td className="bg-gray-100 font-bold py-2 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>자재유통업자</td>
                  <td style={{ borderBottom: '1px solid black' }}>
                    <table className="w-full border-collapse">
                      <tbody>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black', width: '80px' }}>상호</td>
                          <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}></td>
                        </tr>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>대표자명</td>
                          <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}></td>
                        </tr>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>주소</td>
                          <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}></td>
                        </tr>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black' }}>연락처</td>
                          <td className="py-1 px-2"></td>
                        </tr>
                      </tbody>
                    </table>
                  </td>
                </tr>
                {/* 3. 공사시공자 */}
                <tr>
                  <td className="bg-gray-100 text-center font-bold py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>3</td>
                  <td className="bg-gray-100 font-bold py-2 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>공사시공자</td>
                  <td style={{ borderBottom: '1px solid black' }}>
                    <table className="w-full border-collapse">
                      <tbody>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black', width: '80px' }}>상호</td>
                          <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}></td>
                        </tr>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>대표자명</td>
                          <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}></td>
                        </tr>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>주소</td>
                          <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}></td>
                        </tr>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black' }}>연락처</td>
                          <td className="py-1 px-2"></td>
                        </tr>
                      </tbody>
                    </table>
                  </td>
                </tr>
                {/* 4. 공사감리자 */}
                <tr>
                  <td className="bg-gray-100 text-center font-bold py-2" style={{ borderRight: '1px solid black' }}>4</td>
                  <td className="bg-gray-100 font-bold py-2 px-2" style={{ borderRight: '1px solid black' }}>공사감리자</td>
                  <td>
                    <table className="w-full border-collapse">
                      <tbody>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black', width: '80px' }}>상호</td>
                          <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}></td>
                        </tr>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>대표자명</td>
                          <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}></td>
                        </tr>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>주소</td>
                          <td className="py-1 px-2" style={{ borderBottom: '1px solid black' }}></td>
                        </tr>
                        <tr>
                          <td className="py-1 px-2" style={{ borderRight: '1px solid black' }}>연락처</td>
                          <td className="py-1 px-2"></td>
                        </tr>
                      </tbody>
                    </table>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 검사요청시 필독 */}
          <div className="mb-3 p-3 border-2 border-red-400 bg-red-50 rounded">
            <div className="font-bold text-red-700 mb-2" style={{ fontSize: '11px' }}>※ 검사요청시 필독</div>
            <ul className="text-xs space-y-1 pl-4 list-disc text-gray-700">
              <li>제품검사요청서 접수 후 3일 이내 방문검사 실시</li>
              <li>검사 불합격 시 재검사 비용은 신청자 부담</li>
              <li>현장 접근성 및 검사환경 사전 확보 필요</li>
              <li>검사 당일 담당자 현장 입회 필수</li>
            </ul>
          </div>

          {/* 검사대상 사전 고지 정보 테이블 */}
          <div className="border-2 border-black">
            <div className="bg-gray-200 text-center font-bold py-2 border-b border-black" style={{ fontSize: '12px' }}>
              검사대상 사전 고지 정보
            </div>
            <table className="w-full border-collapse text-xs">
              <thead>
                <tr className="bg-gray-100">
                  <th className="py-2 px-2 text-center border-r border-b border-black" style={{ width: '40px' }}>No</th>
                  <th className="py-2 px-2 text-center border-r border-b border-black">제품명</th>
                  <th className="py-2 px-2 text-center border-r border-b border-black" style={{ width: '80px' }}>규격(W×H)</th>
                  <th className="py-2 px-2 text-center border-r border-b border-black" style={{ width: '50px' }}>수량</th>
                  <th className="py-2 px-2 text-center border-r border-b border-black" style={{ width: '80px' }}>설치위치</th>
                  <th className="py-2 px-2 text-center border-b border-black" style={{ width: '100px' }}>비고</th>
                </tr>
              </thead>
              <tbody>
                {[1, 2, 3, 4, 5, 6, 7, 8].map((no) => (
                  <tr key={no}>
                    <td className="py-2 px-2 text-center border-r border-b border-black">{no}</td>
                    <td className="py-2 px-2 border-r border-b border-black"></td>
                    <td className="py-2 px-2 text-center border-r border-b border-black"></td>
                    <td className="py-2 px-2 text-center border-r border-b border-black"></td>
                    <td className="py-2 px-2 border-r border-b border-black"></td>
                    <td className="py-2 px-2 border-b border-black"></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* 신청인/접수인 서명란 */}
          <div className="mt-4 flex justify-end gap-8">
            <div className="text-center">
              <div className="text-xs mb-1">신청인</div>
              <div className="border-b border-black w-24 h-8"></div>
              <div className="text-xs text-gray-500 mt-1">(인)</div>
            </div>
            <div className="text-center">
              <div className="text-xs mb-1">접수인</div>
              <div className="border-b border-black w-24 h-8"></div>
              <div className="text-xs text-gray-500 mt-1">(인)</div>
            </div>
          </div>

          {/* 문서번호 */}
          <div className="mt-4 text-right text-[9px] text-gray-400">
            문서번호: KD-SA-YYMMDD-##
          </div>
        </div>
      );
    }

    // ========== 작업일지 미리보기 ==========
    // 스크린 작업일지
    if (docCode === 'WL-SCR') {
      // 스크린 작업일지 샘플 데이터
      const scrSampleData = {
        orderDate: '2025년 10월 15일 수요일',
        siteName: '용신고등학교(4층)',
        customerName: '주일',
        workDate: '2025.    .',
        managerName: '김영민과장',
        lotNo: 'KD-WE-251015-01-(3)',
        phone: '',
        productionManager: ''
      };

      return (
        <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '8mm', fontSize: '10px' }}>
          {/* 헤더 - 공통 함수 사용 */}
          {renderKDHeader('작 업 일 지', '스크린 생산부서', {
            writer: '전진',
            writerDate: '10/15',
            writerDept: '판매/전진'
          })}

          {/* 신청업체 / 신청내용 - 공통 함수 사용 */}
          {renderRequestInfoTable(scrSampleData)}

          {/* 작업 내역 */}
          <div className="text-sm font-bold mb-1">■ 작업 내역</div>
          <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
            <thead>
              <tr>
                <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '5%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>일련<br />번호</th>
                <th rowSpan="2" className="bg-yellow-300 py-1 font-bold" style={{ width: '12%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>입고 LOT NO.</th>
                <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '8%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>제품명</th>
                <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '10%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>부호</th>
                <th colSpan="2" className="bg-gray-200 py-1 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>제작사이즈(mm)</th>
                <th rowSpan="2" className="bg-gray-100 py-1 font-bold" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>나머지<br />높이</th>
                <th colSpan="5" className="bg-gray-200 py-1 font-bold" style={{ borderBottom: '1px solid black', fontSize: '8px' }}>규격(매수)</th>
              </tr>
              <tr>
                <th className="bg-gray-100 py-0.5 font-bold" style={{ width: '8%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>가로</th>
                <th className="bg-gray-100 py-0.5 font-bold" style={{ width: '8%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>세로</th>
                <th className="bg-gray-100 py-0.5 font-bold" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>1180</th>
                <th className="bg-gray-100 py-0.5 font-bold" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>900</th>
                <th className="bg-gray-100 py-0.5 font-bold" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>600</th>
                <th className="bg-gray-100 py-0.5 font-bold" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>400</th>
                <th className="bg-gray-100 py-0.5 font-bold" style={{ width: '7%', borderBottom: '1px solid black', fontSize: '8px' }}>300</th>
              </tr>
            </thead>
            <tbody style={{ fontSize: '9px' }}>
              {[
                { no: '01', lot: '', name: '와이어', code: '4층 FSS17', w: '7400', h: '2950', rest: '810', s1180: '2', s900: '1', s600: '', s400: '', s300: '' },
                { no: '02', lot: '', name: '와이어', code: '4층 FSS5', w: '4700', h: '2950', rest: '810', s1180: '2', s900: '1', s600: '', s400: '', s300: '' },
                { no: '03', lot: '', name: '와이어', code: '4층 FSS17A', w: '6790', h: '2950', rest: '810', s1180: '2', s900: '1', s600: '', s400: '', s300: '' },
                { no: '04', lot: '', name: '와이어', code: '4층 FSS3-1', w: '3700', h: '2950', rest: '810', s1180: '2', s900: '1', s600: '', s400: '', s300: '' },
                { no: '05', lot: '', name: '와이어', code: '4층 FSS7', w: '6000', h: '2950', rest: '810', s1180: '2', s900: '1', s600: '', s400: '', s300: '' },
                { no: '06', lot: '', name: '와이어', code: '4층 FSS16', w: '7300', h: '2950', rest: '810', s1180: '2', s900: '1', s600: '', s400: '', s300: '' },
                { no: '07', lot: '', name: '와이어', code: '4층 FSS3-2', w: '3700', h: '2950', rest: '810', s1180: '2', s900: '1', s600: '', s400: '', s300: '' },
                { no: '08', lot: '', name: '와이어', code: '4층 FSS6', w: '5900', h: '2950', rest: '810', s1180: '2', s900: '1', s600: '', s400: '', s300: '' },
                { no: '09', lot: '', name: '와이어', code: '4층 FSS3-3', w: '3910', h: '2950', rest: '810', s1180: '2', s900: '1', s600: '', s400: '', s300: '' },
                { no: '10', lot: '', name: '와이어', code: '4층 FSS17', w: '7400', h: '2950', rest: '810', s1180: '2', s900: '1', s600: '', s400: '', s300: '' },
                { no: '11', lot: '', name: '와이어', code: '4층 FSS15', w: '7000', h: '2950', rest: '810', s1180: '2', s900: '1', s600: '', s400: '', s300: '' },
              ].map((row, idx) => (
                <tr key={idx}>
                  <td className="text-center py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.no}</td>
                  <td className="text-center py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.lot}</td>
                  <td className="text-center py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.name}</td>
                  <td className="text-center py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.code}</td>
                  <td className="text-center py-1 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.w}</td>
                  <td className="text-center py-1 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.h}</td>
                  <td className="text-center py-1 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.rest}</td>
                  <td className="text-center py-1 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.s1180}</td>
                  <td className="text-center py-1 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.s900}</td>
                  <td className="text-center py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.s600}</td>
                  <td className="text-center py-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.s400}</td>
                  <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}>{row.s300}</td>
                </tr>
              ))}
              {/* 합계 행 */}
              <tr className="bg-gray-100 font-bold">
                <td colSpan="7" className="text-center py-1.5" style={{ borderRight: '1px solid black' }}>합 계</td>
                <td className="text-center py-1.5" style={{ borderRight: '1px solid black' }}>22</td>
                <td className="text-center py-1.5" style={{ borderRight: '1px solid black' }}>11</td>
                <td className="text-center py-1.5" style={{ borderRight: '1px solid black' }}></td>
                <td className="text-center py-1.5" style={{ borderRight: '1px solid black' }}></td>
                <td className="text-center py-1.5"></td>
              </tr>
            </tbody>
          </table>

          {/* 내화실 입고 LOT.NO */}
          <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td className="bg-gray-200 font-bold py-1.5 px-3" style={{ width: '20%' }}>내화실 입고 LOT.NO</td>
                <td className="py-1.5 px-3" style={{ width: '80%' }}></td>
              </tr>
            </tbody>
          </table>

          {/* 사용량 테이블 */}
          <table className="w-full border-collapse" style={{ fontSize: '9px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td rowSpan="3" className="text-center font-bold bg-gray-200 align-middle" style={{ width: '8%', borderRight: '1px solid black' }}>
                  <div>사용량</div>
                  <div>(M)</div>
                </td>
                <td className="text-center py-1.5 font-bold bg-gray-100" style={{ width: '8%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>1220</td>
                <td className="text-center py-1.5" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>127.60</td>
                <td className="text-center py-1.5 font-bold bg-gray-100" style={{ width: '8%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>400</td>
                <td className="text-center py-1.5" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                <td rowSpan="3" className="text-center font-bold bg-gray-200 align-middle" style={{ width: '12%', borderRight: '1px solid black' }}>
                  <div>사용량</div>
                  <div>[ ㎡ ]</div>
                </td>
                <td rowSpan="3" className="text-center font-bold text-xl align-middle" style={{ width: '30%' }}>213.09</td>
              </tr>
              <tr>
                <td className="text-center py-1.5 font-bold bg-gray-100" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>900</td>
                <td className="text-center py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>63.8</td>
                <td className="text-center py-1.5 font-bold bg-gray-100" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>300</td>
                <td className="text-center py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
              </tr>
              <tr>
                <td className="text-center py-1.5 font-bold bg-gray-100" style={{ borderRight: '1px solid black' }}>600</td>
                <td className="text-center py-1.5" style={{ borderRight: '1px solid black' }}></td>
                <td className="text-center py-1.5" colSpan="2" style={{ borderRight: '1px solid black' }}></td>
              </tr>
            </tbody>
          </table>
        </div>
      );
    }

    // 슬랫 작업일지
    if (docCode === 'WL-SLT') {
      // 슬랫 작업일지 샘플 데이터
      const sltSampleData = {
        orderDate: '2025년 6월 30일 월요일',
        siteName: '철재 스라트 전체표시(모터포함)',
        customerName: '경동기업',
        workDate: '06/30',
        managerName: '개발자',
        lotNo: 'KD-비인정',
        phone: '010-5123-8210',
        productionManager: '개발자'
      };

      return (
        <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '8mm', fontSize: '10px' }}>
          {/* 헤더 - 공통 함수 사용 */}
          {renderKDHeader('작 업 일 지', '슬랫 생산부서', {
            writer: '개발자',
            writerDate: '06/30',
            reviewer: '개발자',
            reviewerDate: '07/02',
            approver: '개발자',
            approverDate: '07/02',
            writerDept: '판매/개발자'
          })}

          {/* 신청업체 / 신청내용 - 공통 함수 사용 */}
          {renderRequestInfoTable(sltSampleData)}

          {/* 작업내역 */}
          <div className="text-sm font-bold mb-1">■ 작업내역</div>
          <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
            <thead>
              <tr>
                <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '5%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>일련<br />번호</th>
                <th rowSpan="2" className="bg-yellow-300 py-1 font-bold" style={{ width: '12%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>입고 LOT NO.</th>
                <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '8%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>방화유리<br />수량</th>
                <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '10%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>품명</th>
                <th colSpan="3" className="bg-gray-200 py-1 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>제작사이즈(mm) - 미미제외</th>
                <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '8%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>조인트바<br />수량</th>
                <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '8%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>코일<br />사용량</th>
                <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '10%', borderBottom: '1px solid black', fontSize: '8px' }}>설치층/부호</th>
              </tr>
              <tr>
                <th className="bg-gray-100 py-0.5 font-bold" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>가로</th>
                <th className="bg-gray-100 py-0.5 font-bold" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>세로</th>
                <th className="bg-gray-100 py-0.5 font-bold" style={{ width: '8%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>매수(세로)</th>
              </tr>
            </thead>
            <tbody style={{ fontSize: '9px' }}>
              {[
                { no: '1', lot: '250508-01', name: '', product: '슬랫\n[EGI1.55T]', w: '3610', h: '4350', count: '61', joint: '5', coil: '225', floor: '/' },
                { no: '2', lot: '250425-01', name: '', product: '슬랫\n[EGI1.55T]', w: '3610', h: '4350', count: '61', joint: '5', coil: '225', floor: '/' },
              ].map((row, idx) => (
                <tr key={idx}>
                  <td className="text-center py-2" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.no}</td>
                  <td className="text-center py-2" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.lot}<span className="inline-block w-4 h-4 bg-gray-800 text-white rounded-full text-xs ml-1">i</span></td>
                  <td className="text-center py-2" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.name}</td>
                  <td className="text-center py-2" style={{ borderBottom: '1px solid black', borderRight: '1px solid black', whiteSpace: 'pre-line' }}>{row.product}</td>
                  <td className="text-center py-2 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.w}</td>
                  <td className="text-center py-2 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.h}</td>
                  <td className="text-center py-2 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.count}</td>
                  <td className="text-center py-2 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.joint}</td>
                  <td className="text-center py-2 font-bold" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{row.coil}</td>
                  <td className="text-center py-2" style={{ borderBottom: '1px solid black' }}>{row.floor}</td>
                </tr>
              ))}
            </tbody>
          </table>

          {/* 합계 */}
          <table className="w-full border-collapse" style={{ fontSize: '9px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td className="text-center font-bold py-2 bg-gray-100" style={{ width: '20%', borderRight: '1px solid black' }}>생산량 합계 (㎡)</td>
                <td className="text-center py-2 font-bold" style={{ width: '30%', borderRight: '1px solid black' }}>450</td>
                <td className="text-center font-bold py-2 bg-gray-100" style={{ width: '20%', borderRight: '1px solid black' }}>조인트바 합계</td>
                <td className="text-center py-2 font-bold" style={{ width: '30%' }}>10</td>
              </tr>
            </tbody>
          </table>
        </div>
      );
    }

    // 절곡 작업일지 - 첨부파일 기준 완전 구현
    if (docCode === 'WL-FLD') {
      // 절곡 작업일지 샘플 데이터
      const fldSampleData = {
        orderDate: '2025년 10월 15일 수요일',
        siteName: '용신고등학교(4층)',
        customerName: '주일',
        workDate: '2025.    .',
        managerName: '김영민과장',
        lotNo: 'KD-WE-251015-01-(3)',
        phone: '',
        productionManager: '',
        productCode: 'KWE01',
        productName: '와이어',
        finishType: 'SUS마감',
        finishSpec: '벽면형(120*70)'
      };

      return (
        <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '8mm', fontSize: '10px' }}>
          {/* 헤더 - 공통 함수 사용 */}
          {renderKDHeader('작 업 일 지', '절곡 생산부서', {
            writer: '전진',
            writerDate: '10/15',
            writerDept: '판매/전진'
          })}

          {/* 신청업체 / 신청내용 + 제품명/마감유형 - 공통 함수 사용 */}
          {renderRequestInfoTable(fldSampleData, { showProductInfo: true, siteNameColor: 'text-red-600' })}

          {/* 1. 작업 내역 - 절곡 상세도면 참조 */}
          <div className="text-sm font-bold mb-1">1. 작업 내역 - 절곡 상세도면 참조</div>

          {/* 1.1 벽면형 (120·70) */}
          <table className="w-full border-collapse mb-2" style={{ fontSize: '10px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td colSpan="6" className="font-bold py-1 px-2 bg-gray-50 text-sm" style={{ borderBottom: '1px solid black' }}>1.1 벽면형 (120·70)</td>
              </tr>
              <tr>
                {/* 전개도 영역 */}
                <td colSpan="2" className="p-1 align-top" style={{ width: '40%', borderRight: '1px solid black' }}>
                  <div className="flex gap-2">
                    {/* KSS01 도면 */}
                    <div className="border border-gray-400 bg-gray-50 p-1 flex-1" style={{ minHeight: '90px' }}>
                      <div className="text-red-600 font-bold text-xs mb-1 text-center">KSS01</div>
                      <div className="flex items-center justify-center" style={{ height: '70px' }}>
                        <svg viewBox="0 0 100 70" className="w-full h-full">
                          <rect x="5" y="5" width="60" height="55" fill="none" stroke="#333" strokeWidth="1" />
                          <line x1="65" y1="5" x2="65" y2="60" stroke="#333" strokeWidth="1" />
                          <line x1="65" y1="5" x2="90" y2="5" stroke="#333" strokeWidth="1" />
                          <line x1="65" y1="60" x2="90" y2="60" stroke="#333" strokeWidth="1" />
                          <text x="35" y="35" textAnchor="middle" fontSize="7" fill="#333">120</text>
                          <text x="77" y="35" textAnchor="middle" fontSize="6" fill="#333">70</text>
                          <circle cx="15" cy="15" r="2" fill="#ff0000" />
                          <text x="15" y="22" textAnchor="middle" fontSize="5" fill="#ff0000">①</text>
                          <circle cx="35" cy="15" r="2" fill="#ff0000" />
                          <text x="35" y="22" textAnchor="middle" fontSize="5" fill="#ff0000">④</text>
                          <circle cx="55" cy="15" r="2" fill="#ff0000" />
                          <text x="55" y="22" textAnchor="middle" fontSize="5" fill="#ff0000">②</text>
                          <circle cx="35" cy="50" r="2" fill="#ff0000" />
                          <text x="35" y="57" textAnchor="middle" fontSize="5" fill="#ff0000">⑤</text>
                        </svg>
                      </div>
                    </div>
                    {/* KSE01 도면 */}
                    <div className="border border-gray-400 bg-gray-50 p-1 flex-1" style={{ minHeight: '90px' }}>
                      <div className="text-red-600 font-bold text-xs mb-1 text-center">KSE01</div>
                      <div className="flex items-center justify-center" style={{ height: '70px' }}>
                        <svg viewBox="0 0 100 70" className="w-full h-full">
                          <rect x="5" y="5" width="60" height="55" fill="none" stroke="#333" strokeWidth="1" />
                          <line x1="65" y1="5" x2="65" y2="60" stroke="#333" strokeWidth="1" />
                          <line x1="65" y1="5" x2="90" y2="5" stroke="#333" strokeWidth="1" />
                          <line x1="65" y1="60" x2="90" y2="60" stroke="#333" strokeWidth="1" />
                          <text x="35" y="35" textAnchor="middle" fontSize="7" fill="#333">120</text>
                          <text x="77" y="35" textAnchor="middle" fontSize="6" fill="#333">70</text>
                          <circle cx="15" cy="15" r="2" fill="#ff0000" />
                          <text x="15" y="22" textAnchor="middle" fontSize="5" fill="#ff0000">③</text>
                          <circle cx="35" cy="15" r="2" fill="#ff0000" />
                          <text x="35" y="22" textAnchor="middle" fontSize="5" fill="#ff0000">④</text>
                          <circle cx="55" cy="15" r="2" fill="#ff0000" />
                          <text x="55" y="22" textAnchor="middle" fontSize="5" fill="#ff0000">②</text>
                          <circle cx="35" cy="50" r="2" fill="#ff0000" />
                          <text x="35" y="57" textAnchor="middle" fontSize="5" fill="#ff0000">⑤</text>
                        </svg>
                      </div>
                    </div>
                  </div>
                </td>
                {/* 작업량 테이블 */}
                <td colSpan="4" className="align-top p-0" style={{ width: '60%' }}>
                  <table className="w-full border-collapse" style={{ fontSize: '9px' }}>
                    <thead>
                      <tr>
                        <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '18%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>세부품명</th>
                        <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '15%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>재질</th>
                        <th rowSpan="2" className="bg-yellow-300 py-1 font-bold" style={{ width: '27%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>입고 & 생산 LOT NO</th>
                        <th colSpan="2" className="bg-gray-200 py-1 font-bold" style={{ borderBottom: '1px solid black', fontSize: '8px' }}>작업량</th>
                      </tr>
                      <tr>
                        <th className="bg-gray-100 py-0.5" style={{ width: '22%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>길이/규격</th>
                        <th className="bg-gray-100 py-0.5" style={{ width: '18%', borderBottom: '1px solid black', fontSize: '8px' }}>수량</th>
                      </tr>
                    </thead>
                    <tbody style={{ fontSize: '8px' }}>
                      <tr>
                        <td className="border-b border-r border-black py-1 px-1"><span className="text-red-600 font-bold">①마감재</span></td>
                        <td className="border-b border-r border-black py-1 text-center">EGI1.15T</td>
                        <td className="border-b border-r border-black py-1 px-1"></td>
                        <td className="border-b border-r border-black py-1 text-center">L : 4,300</td>
                        <td className="border-b border-black py-1 text-center font-bold">22</td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 px-1"><span className="font-bold">②</span>가이드레일</td>
                        <td className="border-b border-r border-black py-1 text-center">SUS1.2T</td>
                        <td className="border-b border-r border-black py-1 px-1"></td>
                        <td className="border-b border-r border-black py-1 text-center">L : 4,000</td>
                        <td className="border-b border-black py-1 text-center font-bold">44</td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 px-1"><span className="font-bold">③</span>C형</td>
                        <td className="border-b border-r border-black py-1 text-center">EGI1.55T</td>
                        <td className="border-b border-r border-black py-1 px-1"></td>
                        <td className="border-b border-r border-black py-1 text-center">L : 3,500</td>
                        <td className="border-b border-black py-1 text-center font-bold">22</td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 px-1"><span className="font-bold">④</span>D형</td>
                        <td className="border-b border-r border-black py-1 text-center">EGI1.55T</td>
                        <td className="border-b border-r border-black py-1 px-1"></td>
                        <td className="border-b border-r border-black py-1 text-center">L : 3,000</td>
                        <td className="border-b border-black py-1 text-center font-bold">22</td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 px-1"><span className="text-red-600 font-bold">⑤별도마감재</span></td>
                        <td className="border-b border-r border-black py-1 text-center">SUS1.2T</td>
                        <td className="border-b border-r border-black py-1 px-1"></td>
                        <td className="border-b border-r border-black py-1 text-center">L : 2,438</td>
                        <td className="border-b border-black py-1 text-center font-bold">22</td>
                      </tr>
                      <tr>
                        <td className="border-r border-black py-1 px-1"><span className="font-bold">⑥</span>하부BASE</td>
                        <td className="border-r border-black py-1 text-center">EGI1.55T</td>
                        <td className="border-r border-black py-1 px-1"></td>
                        <td className="border-r border-black py-1 text-center">130·80</td>
                        <td className="border-black py-1 text-center font-bold">22</td>
                      </tr>
                    </tbody>
                  </table>
                </td>
              </tr>
            </tbody>
          </table>

          {/* 2. 하단마감재 [60·40] */}
          <table className="w-full border-collapse mb-2" style={{ fontSize: '10px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td colSpan="6" className="font-bold py-1 px-2 bg-gray-50 text-sm" style={{ borderBottom: '1px solid black' }}>2. 하단마감재 [60·40]</td>
              </tr>
              <tr>
                {/* 전개도 영역 */}
                <td colSpan="2" className="p-1 align-top" style={{ width: '40%', borderRight: '1px solid black' }}>
                  <div className="flex gap-2">
                    {/* KSS01 하단마감재 도면 */}
                    <div className="border border-gray-400 bg-gray-50 p-1 flex-1" style={{ minHeight: '80px' }}>
                      <div className="text-red-600 font-bold text-xs mb-1 text-center">KSS01</div>
                      <div className="flex items-center justify-center" style={{ height: '60px' }}>
                        <svg viewBox="0 0 100 60" className="w-full h-full">
                          <rect x="5" y="5" width="45" height="45" fill="none" stroke="#333" strokeWidth="1" />
                          <line x1="50" y1="5" x2="90" y2="5" stroke="#333" strokeWidth="1" />
                          <line x1="50" y1="50" x2="90" y2="50" stroke="#333" strokeWidth="1" />
                          <text x="27" y="30" textAnchor="middle" fontSize="7" fill="#333">60</text>
                          <text x="70" y="30" textAnchor="middle" fontSize="6" fill="#333">40</text>
                          <circle cx="15" cy="15" r="2" fill="#ff0000" />
                          <text x="15" y="23" textAnchor="middle" fontSize="5" fill="#ff0000">①</text>
                          <circle cx="35" cy="15" r="2" fill="#ff0000" />
                          <text x="35" y="23" textAnchor="middle" fontSize="5" fill="#ff0000">②</text>
                          <circle cx="25" cy="40" r="2" fill="#ff0000" />
                          <text x="25" y="48" textAnchor="middle" fontSize="5" fill="#ff0000">③</text>
                        </svg>
                      </div>
                    </div>
                    {/* KSE01 하단마감재 도면 */}
                    <div className="border border-gray-400 bg-gray-50 p-1 flex-1" style={{ minHeight: '80px' }}>
                      <div className="text-red-600 font-bold text-xs mb-1 text-center">KSE01</div>
                      <div className="flex items-center justify-center" style={{ height: '60px' }}>
                        <svg viewBox="0 0 100 60" className="w-full h-full">
                          <rect x="5" y="5" width="50" height="40" fill="none" stroke="#333" strokeWidth="1" />
                          <text x="30" y="28" textAnchor="middle" fontSize="7" fill="#333">64</text>
                          <text x="70" y="28" textAnchor="middle" fontSize="6" fill="#333">43</text>
                          <circle cx="15" cy="15" r="2" fill="#ff0000" />
                          <text x="15" y="23" textAnchor="middle" fontSize="5" fill="#ff0000">④</text>
                        </svg>
                      </div>
                    </div>
                  </div>
                </td>
                {/* 작업량 테이블 */}
                <td colSpan="4" className="align-top p-0" style={{ width: '60%' }}>
                  <table className="w-full border-collapse" style={{ fontSize: '9px' }}>
                    <thead>
                      <tr>
                        <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '18%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>세부품명</th>
                        <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '15%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>재질</th>
                        <th rowSpan="2" className="bg-yellow-300 py-1 font-bold" style={{ width: '27%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>입고 & 생산 LOT NO</th>
                        <th colSpan="2" className="bg-gray-200 py-1 font-bold" style={{ borderBottom: '1px solid black', fontSize: '8px' }}>작업량</th>
                      </tr>
                      <tr>
                        <th className="bg-gray-100 py-0.5" style={{ width: '22%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>길이/규격</th>
                        <th className="bg-gray-100 py-0.5" style={{ width: '18%', borderBottom: '1px solid black', fontSize: '8px' }}>수량</th>
                      </tr>
                    </thead>
                    <tbody style={{ fontSize: '8px' }}>
                      <tr>
                        <td className="py-1 px-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}><span className="text-red-600 font-bold">①하단마감재</span></td>
                        <td className="border-b border-r border-black py-1 text-center">EGI1.55T</td>
                        <td className="border-b border-r border-black py-1 px-1"></td>
                        <td className="border-b border-r border-black py-1 text-center">L : 4,000</td>
                        <td className="border-b border-black py-1 text-center font-bold">11</td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 px-1"><span className="font-bold">②</span>하단보강엘바</td>
                        <td className="border-b border-r border-black py-1 text-center">EGI1.55T</td>
                        <td className="border-b border-r border-black py-1 px-1"></td>
                        <td className="border-b border-r border-black py-1 text-center">L : 4,000</td>
                        <td className="border-b border-black py-1 text-center font-bold">26</td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 px-1"><span className="font-bold">③</span>하단보강평철</td>
                        <td className="border-b border-r border-black py-1 text-center">EGI1.15T</td>
                        <td className="border-b border-r border-black py-1 px-1"></td>
                        <td className="border-b border-r border-black py-1 text-center">L : 4,000</td>
                        <td className="border-b border-black py-1 text-center font-bold">13</td>
                      </tr>
                      <tr>
                        <td className="border-r border-black py-1 px-1"><span className="text-red-600 font-bold">④별도마감재</span></td>
                        <td className="border-r border-black py-1 text-center">SUS1.2T</td>
                        <td className="border-r border-black py-1 px-1"></td>
                        <td className="border-r border-black py-1 text-center">L : 4,000</td>
                        <td className="border-black py-1 text-center font-bold">11</td>
                      </tr>
                    </tbody>
                  </table>
                </td>
              </tr>
            </tbody>
          </table>

          {/* 3.1 케이스 [500*330] */}
          <table className="w-full border-collapse mb-2" style={{ fontSize: '10px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td colSpan="6" className="font-bold py-1 px-2 bg-gray-50 text-sm" style={{ borderBottom: '1px solid black' }}>3.1 케이스 [500*330]</td>
              </tr>
              <tr>
                {/* 전개도 영역 */}
                <td colSpan="2" className="p-1 align-top" style={{ width: '40%', borderRight: '1px solid black' }}>
                  {/* 케이스 전개도 */}
                  <div className="flex items-center justify-center" style={{ height: '180px' }}>
                    <svg viewBox="0 0 280 180" className="w-full h-full">
                      {/* 상단 치수 */}
                      <text x="35" y="12" fontSize="8" fill="#333">55</text>
                      <line x1="50" y1="15" x2="95" y2="15" stroke="#333" strokeWidth="0.5" />
                      <text x="100" y="12" fontSize="8" fill="#333">50</text>

                      <text x="80" y="28" fontSize="8" fill="#333">389</text>

                      {/* 메인 박스 - 케이스 본체 */}
                      <rect x="25" y="20" width="150" height="120" fill="none" stroke="#333" strokeWidth="1" />
                      <line x1="55" y1="20" x2="55" y2="140" stroke="#333" strokeWidth="0.5" strokeDasharray="2,2" />
                      <line x1="145" y1="20" x2="145" y2="140" stroke="#333" strokeWidth="0.5" strokeDasharray="2,2" />

                      {/* 좌측 치수 */}
                      <text x="5" y="80" fontSize="12" fontWeight="bold" fill="#333">330</text>

                      {/* 내부 치수 */}
                      <text x="90" y="85" fontSize="12" fontWeight="bold" fill="#333">190</text>

                      {/* 하단 치수 */}
                      <text x="30" y="135" fontSize="7" fill="#333">55</text>
                      <text x="60" y="135" fontSize="7" fill="#333">50</text>
                      <text x="95" y="135" fontSize="8" fill="#333">240</text>
                      <text x="150" y="135" fontSize="7" fill="#333">50</text>

                      <text x="55" y="155" fontSize="7" fill="#666">가이드레일 너비 70</text>

                      {/* 우측 마구리 부분 */}
                      <text x="190" y="35" fontSize="7" fill="#333">50</text>
                      <text x="210" y="55" fontSize="8" fill="#333">355</text>
                      <rect x="185" y="40" width="80" height="80" fill="none" stroke="#333" strokeWidth="1" />
                      <text x="215" y="130" fontSize="8" fill="#333">505</text>
                      <text x="270" y="85" fontSize="7" fill="#333">50</text>
                    </svg>
                  </div>
                </td>
                {/* 작업량 테이블 */}
                <td colSpan="4" className="align-top p-0" style={{ width: '60%' }}>
                  <table className="w-full border-collapse" style={{ fontSize: '9px' }}>
                    <thead>
                      <tr>
                        <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '18%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>세부품명</th>
                        <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '14%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>재질</th>
                        <th rowSpan="2" className="bg-yellow-300 py-1 font-bold" style={{ width: '28%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>입고 & 생산 LOT NO</th>
                        <th colSpan="2" className="bg-gray-200 py-1 font-bold" style={{ borderBottom: '1px solid black', fontSize: '8px' }}>작업량</th>
                      </tr>
                      <tr>
                        <th className="bg-gray-100 py-0.5" style={{ width: '22%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>길이/규격</th>
                        <th className="bg-gray-100 py-0.5" style={{ width: '18%', borderBottom: '1px solid black', fontSize: '8px' }}>수량</th>
                      </tr>
                    </thead>
                    <tbody style={{ fontSize: '8px' }}>
                      <tr>
                        <td rowSpan="2" className="py-1 px-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}><span className="font-bold">①</span>전면부</td>
                        <td rowSpan="9" className="border-b border-r border-black py-1 text-center align-middle">EGI1.55T</td>
                        <td rowSpan="9" className="border-b border-r border-black py-1 px-1 align-middle"></td>
                        <td className="border-b border-r border-black py-1 text-center">L : 4,150</td>
                        <td className="border-b border-black py-1 text-center font-bold">1</td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 text-center">L : 4,000</td>
                        <td className="border-b border-black py-1 text-center font-bold">7</td>
                      </tr>
                      <tr>
                        <td rowSpan="2" className="py-1 px-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}><span className="font-bold">②</span>린텔부</td>
                        <td className="border-b border-r border-black py-1 text-center">L : 3,500</td>
                        <td className="border-b border-black py-1 text-center font-bold">5</td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 text-center">L : 3,000</td>
                        <td className="border-b border-black py-1 text-center font-bold">3</td>
                      </tr>
                      <tr>
                        <td rowSpan="2" className="py-1 px-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}><span className="font-bold">③⑤</span>하부점검구</td>
                        <td className="border-b border-r border-black py-1 text-center">L : 2,438</td>
                        <td className="border-b border-black py-1 text-center font-bold">3</td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 text-center">L : 1,219</td>
                        <td className="border-b border-black py-1 text-center font-bold"></td>
                      </tr>
                      <tr>
                        <td className="py-1 px-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}><span className="font-bold">④</span>후면코너부</td>
                        <td className="border-b border-r border-black py-1 text-center bg-gray-100">상부덮개<br />[1219·389]</td>
                        <td className="border-b border-black py-1 text-center font-bold">59</td>
                      </tr>
                      <tr>
                        <td className="py-1 px-1" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}><span className="font-bold">⑥</span>상부덮개</td>
                        <td className="border-b border-r border-black py-1 text-center"></td>
                        <td className="border-b border-black py-1 text-center font-bold"></td>
                      </tr>
                      <tr>
                        <td className="py-1 px-1" style={{ borderRight: '1px solid black' }}><span className="font-bold">⑦</span>측면부(마구리)</td>
                        <td className="border-r border-black py-1 text-center bg-gray-100">마구리<br />505·335</td>
                        <td className="border-black py-1 text-center font-bold">22</td>
                      </tr>
                    </tbody>
                  </table>
                </td>
              </tr>
            </tbody>
          </table>

          {/* 4. 연기차단재 */}
          <table className="w-full border-collapse mb-2" style={{ fontSize: '10px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td colSpan="6" className="font-bold py-1 px-2 bg-gray-50 text-sm" style={{ borderBottom: '1px solid black' }}>4. 연기차단재</td>
              </tr>
              <tr>
                {/* 전개도 영역 */}
                <td colSpan="2" className="p-1 align-top" style={{ width: '40%', borderRight: '1px solid black' }}>
                  {/* 연기차단재 전개도 */}
                  <div className="flex items-center justify-center" style={{ height: '140px' }}>
                    <svg viewBox="0 0 200 120" className="w-full h-full">
                      {/* 연기차단재 프레임 도면 */}
                      <rect x="10" y="10" width="70" height="80" fill="none" stroke="#333" strokeWidth="1" />
                      <line x1="10" y1="60" x2="80" y2="60" stroke="#cc00cc" strokeWidth="3" />

                      {/* 치수 */}
                      <text x="2" y="50" fontSize="9" fill="#333">14</text>
                      <text x="40" y="100" fontSize="9" fill="#333">12</text>

                      {/* 설명 텍스트 */}
                      <text x="95" y="25" fontSize="8" fill="#333">연기차단재 프레임</text>
                      <text x="95" y="40" fontSize="8" fill="#333">(EGI 0.8T)</text>
                      <line x1="95" y1="55" x2="180" y2="55" stroke="#cc00cc" strokeWidth="3" />
                      <text x="95" y="75" fontSize="7" fill="#cc00cc">화이바 글라스 코팅직물</text>
                      <text x="95" y="90" fontSize="7" fill="#cc00cc">(너비 50/80)</text>
                    </svg>
                  </div>
                </td>
                {/* 작업량 테이블 */}
                <td colSpan="4" className="align-top p-0" style={{ width: '60%' }}>
                  <table className="w-full border-collapse" style={{ fontSize: '9px' }}>
                    <thead>
                      <tr>
                        <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '18%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>세부품명</th>
                        <th rowSpan="2" className="bg-gray-200 py-1 font-bold" style={{ width: '18%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>재질</th>
                        <th rowSpan="2" className="bg-yellow-300 py-1 font-bold" style={{ width: '24%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>입고 & 생산 LOT NO</th>
                        <th colSpan="2" className="bg-gray-200 py-1 font-bold" style={{ borderBottom: '1px solid black', fontSize: '8px' }}>작업량</th>
                      </tr>
                      <tr>
                        <th className="bg-gray-100 py-0.5" style={{ width: '22%', borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>길이/규격</th>
                        <th className="bg-gray-100 py-0.5" style={{ width: '18%', borderBottom: '1px solid black', fontSize: '8px' }}>수량</th>
                      </tr>
                    </thead>
                    <tbody style={{ fontSize: '8px' }}>
                      <tr>
                        <td rowSpan="6" className="py-1 px-1 align-middle" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>레일용<br />[W50]</td>
                        <td rowSpan="6" className="border-b border-r border-black py-1 text-center align-middle">EG0.8T +<br />화이바<br />글라스<br />코팅직물</td>
                        <td rowSpan="6" className="border-b border-r border-black py-1 px-1 align-middle">(원단 :          )</td>
                        <td className="border-b border-r border-black py-1 text-center">L : 4,300</td>
                        <td className="border-b border-black py-1 text-center font-bold"></td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 text-center">L : 4,000</td>
                        <td className="border-b border-black py-1 text-center font-bold"></td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 text-center">L : 3,500</td>
                        <td className="border-b border-black py-1 text-center font-bold"></td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 text-center">L : 3,000</td>
                        <td className="border-b border-black py-1 text-center font-bold">44</td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 text-center">L : 2,438</td>
                        <td className="border-b border-black py-1 text-center font-bold"></td>
                      </tr>
                      <tr>
                        <td className="border-b border-r border-black py-1 text-center"></td>
                        <td className="border-b border-black py-1 text-center font-bold"></td>
                      </tr>
                      <tr>
                        <td className="border-r border-black py-1 px-1 align-middle">케이스용<br />[W80]</td>
                        <td className="border-r border-black py-1 text-center align-middle">EG0.8T +<br />화이바<br />글라스<br />코팅직물</td>
                        <td className="border-r border-black py-1 px-1 align-middle">(원단 :          )</td>
                        <td className="border-r border-black py-1 text-center">L : 3,000</td>
                        <td className="border-black py-1 text-center font-bold">47</td>
                      </tr>
                    </tbody>
                  </table>
                </td>
              </tr>
            </tbody>
          </table>

          {/* 생산량 합계 / 비고 - 두 줄 테이블 */}
          <table className="w-full border-collapse" style={{ fontSize: '10px', border: '2px solid black' }}>
            <tbody>
              {/* 첫째 줄: 생산량 합계 (kg) | SUS | 값 | 비고 | 비고내용 */}
              <tr>
                <td rowSpan="2" className="font-bold py-2 px-3 bg-gray-100 text-center align-middle" style={{ width: '15%', borderRight: '1px solid black' }}>
                  <div>생산량 합계</div>
                  <div className="text-xs">(kg)</div>
                </td>
                <td className="font-bold py-2 px-2 bg-gray-100 text-center" style={{ width: '8%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>SUS</td>
                <td className="py-2 px-2 text-center" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                  <span className="text-lg font-bold"></span>
                </td>
                <td rowSpan="2" className="font-bold py-2 px-3 bg-gray-100 text-center align-middle" style={{ width: '8%', borderRight: '1px solid black' }}>비 고</td>
                <td rowSpan="2" className="py-2 px-3 align-top" style={{ width: '57%' }}></td>
              </tr>
              {/* 둘째 줄: (생산량 합계 병합됨) | EGI | 값 | (비고 병합됨) | (비고내용 병합됨) */}
              <tr>
                <td className="font-bold py-2 px-2 bg-gray-100 text-center" style={{ borderRight: '1px solid black' }}>EGI</td>
                <td className="py-2 px-2 text-center" style={{ borderRight: '1px solid black' }}>
                  <span className="text-lg font-bold"></span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      );
    }

    // 재고생산 작업일지 (중간검사성적서) - 첨부파일 기준 완전 구현
    if (docCode === 'WL-STK') {
      return (
        <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '8mm', fontSize: '10px' }}>
          {/* 헤더 - 공통 함수 사용 (부제목 포함) */}
          {renderKDHeader('절곡품 재고생산 작업일지', '재고생산 부서', {
            writer: '개발자',
            writerDate: '11/04',
            reviewer: '개발자',
            reviewerDate: '11/05',
            approver: '개발자',
            approverDate: '11/05',
            writerDept: '판매/개발자'
          }, { subtitle: '중간검사성적서', subTitle: 'KD FIRE DOOR COMPANY', logoColor: 'text-blue-700' })}

          {/* 제품 기본정보 테이블 */}
          <table className="w-full border-collapse mb-2" style={{ fontSize: '11px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td className="text-center bg-gray-200 font-bold py-2" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>품명</td>
                <td className="px-3 py-2" style={{ width: '28%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>케이스 - 전면부</td>
                <td className="text-center bg-yellow-300 font-bold py-2" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>생산 LOT NO</td>
                <td className="px-3 py-2 font-bold" style={{ borderBottom: '1px solid black' }}>CF4A15-40</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-200 font-bold py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>규격</td>
                <td className="px-3 py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>EGI 1.55T (W576)</td>
                <td className="text-center bg-gray-200 font-bold py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>로트크기</td>
                <td className="px-3 py-2" style={{ borderBottom: '1px solid black' }}>16 EA</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-200 font-bold py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>길이</td>
                <td className="px-3 py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>4,000</td>
                <td className="text-center bg-gray-200 font-bold py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>검사일자</td>
                <td className="px-3 py-2" style={{ borderBottom: '1px solid black' }}></td>
              </tr>
              <tr>
                <td className="text-center bg-yellow-300 font-bold py-2" style={{ borderRight: '1px solid black' }}>입고 LOT NO</td>
                <td className="px-3 py-2 font-bold" style={{ borderRight: '1px solid black' }}>240927-01</td>
                <td className="text-center bg-gray-200 font-bold py-2" style={{ borderRight: '1px solid black' }}>검사자</td>
                <td className="px-3 py-2">개발자</td>
              </tr>
            </tbody>
          </table>

          {/* 중간 검사 기준서 섹션 - 첨부파일 기준 (가로형 텍스트) */}
          <table className="w-full border-collapse mb-2" style={{ border: '2px solid black' }}>
            <tbody>
              <tr>
                {/* 좌측 - 중간 검사 기준서 라벨 (가로형) */}
                <td rowSpan="2" className="text-center align-middle bg-gray-100 font-bold p-2" style={{ width: '7%', borderRight: '1px solid black' }}>
                  <div style={{ fontSize: '10px' }}>중간 검사</div>
                  <div style={{ fontSize: '10px' }}>기준서</div>
                  <div style={{ fontSize: '11px', marginTop: '4px' }} className="font-bold">KDPS-20</div>
                </td>
                <td rowSpan="2" className="text-center align-middle bg-gray-50 font-bold p-2" style={{ width: '5%', borderRight: '1px solid black' }}>
                  <div style={{ fontSize: '10px' }}>케이스</div>
                  <div style={{ fontSize: '10px' }}>전면부</div>
                </td>
                {/* 도면 영역 */}
                <td className="p-3" style={{ borderBottom: '1px solid black', height: '200px' }}>
                  {/* 케이스 전면부 도면 - SVG */}
                  <svg viewBox="0 0 450 200" className="w-full h-full" style={{ maxHeight: '180px' }}>
                    {/* 메인 프레임 외곽 */}
                    <rect x="80" y="25" width="280" height="150" fill="none" stroke="black" strokeWidth="1.5" />

                    {/* 상단 돌출 - 상부 덮개 */}
                    <path d="M 200 25 L 200 8 L 280 8 L 280 25" fill="none" stroke="black" strokeWidth="1" />
                    <path d="M 280 8 L 320 8 L 320 45 L 360 45 L 360 90" fill="none" stroke="black" strokeWidth="1" />

                    {/* 우측 상단 - 후면 코너부 */}
                    <path d="M 360 45 L 360 25 L 380 25 L 380 70" fill="none" stroke="black" strokeWidth="1" />

                    {/* 좌측 내부 구조 - 전면부 */}
                    <path d="M 80 70 L 130 70 L 130 45 L 80 45" fill="none" stroke="black" strokeWidth="1" />

                    {/* 중앙 - 후면 점검구 */}
                    <rect x="200" y="60" width="80" height="45" fill="none" stroke="black" strokeWidth="1" />

                    {/* 하단 중앙 - 린텔부 */}
                    <path d="M 150 115 L 150 145 L 220 145 L 220 115" fill="none" stroke="black" strokeWidth="1" />

                    {/* 하단 - 하부 점검구 */}
                    <rect x="230" y="130" width="60" height="45" fill="none" stroke="black" strokeWidth="1" />

                    {/* 우측 하단 - 후면 코너부 */}
                    <path d="M 320 130 L 320 175 L 360 175 L 360 130" fill="none" stroke="black" strokeWidth="1" />

                    {/* 치수선 - 파란색 화살표 */}
                    <defs>
                      <marker id="arrowhead-stk" markerWidth="6" markerHeight="4" refX="0" refY="2" orient="auto">
                        <polygon points="0 0, 6 2, 0 4" fill="blue" />
                      </marker>
                      <marker id="arrowhead-stk-rev" markerWidth="6" markerHeight="4" refX="6" refY="2" orient="auto">
                        <polygon points="6 0, 0 2, 6 4" fill="blue" />
                      </marker>
                    </defs>

                    {/* 수직 치수선 좌측 */}
                    <line x1="60" y1="25" x2="60" y2="175" stroke="blue" strokeWidth="1" markerEnd="url(#arrowhead-stk)" markerStart="url(#arrowhead-stk-rev)" />

                    {/* 수평 치수선 하단 */}
                    <line x1="80" y1="190" x2="360" y2="190" stroke="blue" strokeWidth="1" markerEnd="url(#arrowhead-stk)" markerStart="url(#arrowhead-stk-rev)" />

                    {/* 포인트 원 - 검정 원에 흰 숫자 */}
                    <circle cx="105" cy="85" r="12" fill="#333" />
                    <text x="105" y="89" textAnchor="middle" fill="white" fontSize="11" fontWeight="bold">1</text>

                    <circle cx="185" cy="155" r="12" fill="#333" />
                    <text x="185" y="159" textAnchor="middle" fill="white" fontSize="11" fontWeight="bold">2</text>

                    <circle cx="260" cy="155" r="12" fill="#333" />
                    <text x="260" y="159" textAnchor="middle" fill="white" fontSize="11" fontWeight="bold">3</text>

                    <circle cx="335" cy="65" r="12" fill="#333" />
                    <text x="335" y="69" textAnchor="middle" fill="white" fontSize="11" fontWeight="bold">4</text>

                    <circle cx="290" cy="18" r="12" fill="#333" />
                    <text x="290" y="22" textAnchor="middle" fill="white" fontSize="11" fontWeight="bold">4</text>

                    <circle cx="335" cy="110" r="12" fill="#333" />
                    <text x="335" y="114" textAnchor="middle" fill="white" fontSize="11" fontWeight="bold">3</text>

                    {/* 부분 라벨 */}
                    <text x="95" y="55" fontSize="9">① 전면부</text>
                    <text x="150" y="135" fontSize="9">②린텔부</text>
                    <text x="205" y="88" fontSize="9">⑤ 후면 점검구</text>
                    <text x="210" y="15" fontSize="9">⑥상부 덮개</text>
                    <text x="350" y="40" fontSize="9">④후면 코너부</text>
                    <text x="230" y="172" fontSize="9">③하부 점검구</text>
                    <text x="335" y="160" fontSize="9">④후면 코너부</text>
                  </svg>
                </td>
              </tr>
              <tr>
                {/* 하단 검사기준 테이블 */}
                <td style={{ padding: 0, verticalAlign: 'top' }}>
                  <table className="w-full border-collapse" style={{ fontSize: '9px' }}>
                    <thead>
                      <tr>
                        <th className="bg-gray-200 py-1.5 font-bold text-center" style={{ width: '15%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>도해</th>
                        <th className="bg-gray-200 py-1.5 font-bold text-center" style={{ width: '10%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>검사항목</th>
                        <th colSpan="2" className="bg-gray-200 py-1.5 font-bold text-center" style={{ width: '30%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>검사기준</th>
                        <th className="bg-gray-200 py-1.5 font-bold text-center" style={{ width: '10%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>검사방법</th>
                        <th className="bg-gray-200 py-1.5 font-bold text-center" style={{ width: '10%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>검사주기</th>
                        <th className="bg-gray-200 py-1.5 font-bold text-center" style={{ width: '15%', borderBottom: '1px solid black' }}>관련규정</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td rowSpan="3" className="text-center py-2 text-blue-600 align-middle" style={{ borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>
                          절곡품 중간검사 상세도면 참조
                        </td>
                        <td className="text-center py-2" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>겉모양</td>
                        <td className="text-center py-2" style={{ width: '10%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>절곡상태</td>
                        <td className="text-center py-2" style={{ borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '8px' }}>사용상 해로운 결함이 없을것</td>
                        <td className="text-center py-2" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>육안검사</td>
                        <td rowSpan="3" className="text-center py-2 align-middle" style={{ borderBottom: '1px solid black', borderRight: '1px solid black', fontSize: '9px' }}>n = 1, c = 0</td>
                        <td className="text-center py-2" style={{ borderBottom: '1px solid black', fontSize: '8px' }}>KS F 4510 5.1항</td>
                      </tr>
                      <tr>
                        <td rowSpan="2" className="text-center py-2 align-middle" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>치수<br />(mm)</td>
                        <td className="text-center py-2" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>길이</td>
                        <td className="text-center py-2" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>도면치수 ± 4</td>
                        <td rowSpan="2" className="text-center py-2 align-middle" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>체크검사</td>
                        <td className="text-center py-2" style={{ borderBottom: '1px solid black', fontSize: '8px' }}>KS F 4510 7항<br />표9</td>
                      </tr>
                      <tr>
                        <td className="text-center py-2" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>간격</td>
                        <td className="text-center py-2" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>도면치수 ± 2</td>
                        <td className="text-center py-2" style={{ borderBottom: '1px solid black', fontSize: '8px' }}>KS F 4510 7항<br />표9 / 자체규정</td>
                      </tr>
                    </tbody>
                  </table>
                </td>
              </tr>
            </tbody>
          </table>

          {/* 중간검사 DATA 섹션 - 첨부파일 기준 */}
          <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
            <thead>
              <tr>
                <th colSpan="12" className="bg-gray-200 py-1.5 font-bold text-center" style={{ borderBottom: '1px solid black' }}>중간검사 DATA</th>
              </tr>
              <tr>
                <th rowSpan="3" className="bg-gray-100 py-1 font-bold text-center" style={{ width: '4%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>NO</th>
                <th rowSpan="3" className="bg-gray-100 py-1 font-bold text-center" style={{ width: '10%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>품명</th>
                <th className="bg-gray-100 py-1 font-bold text-center" style={{ width: '8%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>겉모양</th>
                <th colSpan="7" className="bg-gray-100 py-1 font-bold text-center" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>치수(mm)</th>
                <th rowSpan="3" className="bg-gray-100 py-1 font-bold text-center" style={{ width: '5%', borderBottom: '1px solid black' }}>판정<br />(적/부)</th>
              </tr>
              <tr>
                <th rowSpan="2" className="bg-gray-100 py-1 font-bold text-center" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>절곡상태</th>
                <th colSpan="2" className="bg-gray-100 py-1 font-bold text-center" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>길이</th>
                <th colSpan="2" className="bg-gray-100 py-1 font-bold text-center" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>너비</th>
                <th colSpan="3" className="bg-gray-100 py-1 font-bold text-center" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>간격</th>
              </tr>
              <tr>
                <th className="bg-gray-100 py-1 font-bold text-center" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>도면치수</th>
                <th className="bg-gray-100 py-1 font-bold text-center" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>측정값</th>
                <th className="bg-gray-100 py-1 font-bold text-center" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>도면치수</th>
                <th className="bg-gray-100 py-1 font-bold text-center" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>측정값</th>
                <th className="bg-gray-100 py-1 font-bold text-center" style={{ width: '5%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>POINT</th>
                <th className="bg-gray-100 py-1 font-bold text-center" style={{ width: '7%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>도면치수</th>
                <th className="bg-gray-100 py-1 font-bold text-center" style={{ width: '8%', borderBottom: '1px solid black', borderRight: '1px solid black' }}>측정값</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>1</td>
                <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>케이스-전면부</td>
                <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>
                  <div className="flex items-center justify-center gap-1">
                    <span className="inline-flex items-center">
                      <span className="inline-block w-4 h-4 border border-black mr-1 bg-green-500 text-white text-center leading-4 text-xs">✓</span>
                      양호
                    </span>
                    <span className="inline-flex items-center ml-2">
                      <span className="inline-block w-4 h-4 border border-black mr-1"></span>
                      불량
                    </span>
                  </div>
                </td>
                <td className="text-center py-2.5 font-bold text-red-600" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>4000</td>
                <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>4000</td>
                <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>N/A</td>
                <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>N/A</td>
                <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>①</td>
                <td className="text-center py-2.5 font-bold text-red-600" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>380</td>
                <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>380</td>
                <td className="text-center py-2.5 font-bold" style={{ borderBottom: '1px solid black' }}>적</td>
              </tr>
              {/* 빈 행들 */}
              {[2, 3, 4, 5].map((num) => (
                <tr key={num}>
                  <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}>{num}</td>
                  <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                  <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                  <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                  <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                  <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                  <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                  <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                  <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                  <td className="text-center py-2.5" style={{ borderBottom: '1px solid black', borderRight: '1px solid black' }}></td>
                  <td className="text-center py-2.5" style={{ borderBottom: '1px solid black' }}></td>
                </tr>
              ))}
              {/* 부적합 내용 + 종합판정 행 */}
              <tr>
                <td colSpan={10} style={{ borderRight: '1px solid black', padding: 0, verticalAlign: 'top' }}>
                  <div className="px-2 py-1 font-bold border-b border-black bg-gray-50">[부적합 내용]</div>
                  <div className="h-24"></div>
                </td>
                <td style={{ padding: 0, verticalAlign: 'top' }}>
                  <div className="bg-yellow-300 text-center font-bold px-2 py-1 border-b border-black">종합판정</div>
                  <div className="h-24 flex items-center justify-center">
                    <span className="text-lg font-bold"></span>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>

          {/* 문서번호 푸터 */}
          <div className="flex justify-between items-center mt-4 text-[10px] font-bold">
            <span>KDQP-01-009</span>
            <span>KDPS-10-03</span>
          </div>
        </div>
      );
    }

    // 출고증 (SHP/TS) 미리보기 - 작업일지 스타일 적용
    if (docCode === 'SHP' || docCode === 'TS') {
      const shpSampleData = {
        lotNo: 'KD-WE-251015-01-(3)',
        productName: '국민방화스크린플러스셔터',
        productCode: 'KWE01',
        certNo: 'FDS-OTS23-0117-4',
        orderDate: '2025년 10월 15일 수요일',
        customerName: '주일',
        siteName: '용신고등학교(4층)',
        dueDate: '2025년 10월 30일 목요일',
        shipmentDate: '2025년 10월 29일 수요일',
        receiverName: '오천식반장',
        receiverPhone: '010-9414-7929',
        totalQty: 11,
        dispatchType: '상차',
        vehicleType: '선불',
        deliveryAddress: '경기도 용인시 처인구 고림동 320-6 용신고등학교',
      };
      return (
        <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '8mm', fontSize: '10px' }}>
          {/* 헤더 - 공통 함수 사용 */}
          {renderKDHeader('출 고 증', '출하 관리부서', {
            writer: '전진',
            writerDate: '10/29',
            writerDept: '판매/전진',
            reviewerDept: '출하',
            approverDept: '생산관리'
          })}

          {/* 로트번호 */}
          <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td className="text-center bg-yellow-300 py-1.5 font-bold" style={{ width: '100px', borderRight: '1px solid black' }}>제품 LOT NO.</td>
                <td className="px-2 py-1.5 font-bold">{shpSampleData.lotNo}</td>
              </tr>
            </tbody>
          </table>

          {/* 전화 / 팩스 / 이메일 */}
          <div className="text-xs text-center mb-2 text-gray-600">
            전화 : 031-938-5130 | 팩스 : 02-6911-6315 | 이메일 : kd5130@naver.com
          </div>

          {/* 상품명 / 제품명 / 인정번호 */}
          <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '70px', borderRight: '1px solid black' }}>상 품 명</td>
                <td className="px-2 py-1.5 font-bold" style={{ borderRight: '1px solid black' }}>{shpSampleData.productName}</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '60px', borderRight: '1px solid black' }}>제품명</td>
                <td className="px-2 py-1.5 font-bold" style={{ width: '80px', borderRight: '1px solid black' }}>{shpSampleData.productCode}</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '60px', borderRight: '1px solid black' }}>인정번호</td>
                <td className="px-2 py-1.5" style={{ width: '120px' }}>{shpSampleData.certNo}</td>
              </tr>
            </tbody>
          </table>

          {/* 신청업체 / 신청내용 / 납품정보 테이블 */}
          <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '40%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>신 청 업 체</td>
                <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '30%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>신 청 내 용</td>
                <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '30%', borderBottom: '1px solid black' }}>납 품 정 보</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 일</td>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shpSampleData.orderDate}</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>현 장 명</td>
                <td className="px-2 py-1.5 font-bold text-yellow-600" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shpSampleData.siteName}</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>인수담당자</td>
                <td className="px-2 py-1.5 font-bold" style={{ borderBottom: '1px solid black' }}>{shpSampleData.receiverName}</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 처</td>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shpSampleData.customerName}</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>납기요청일</td>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shpSampleData.dueDate}</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>인수자연락처</td>
                <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}>{shpSampleData.receiverPhone}</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발주 담당자</td>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>김영민과장</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>출 고 일</td>
                <td className="px-2 py-1.5 font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shpSampleData.shipmentDate}</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>배 송 방 법</td>
                <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}>
                  <span className={shpSampleData.dispatchType === '상차' ? 'font-bold' : ''}>{shpSampleData.dispatchType}</span>
                  <span className="ml-4">{shpSampleData.vehicleType}</span>
                </td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>담당자 연락처</td>
                <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>셔터총수량</td>
                <td className="px-2 py-1.5 font-bold text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shpSampleData.totalQty}</td>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>개소</td>
                <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}></td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black' }}>배송지 주소</td>
                <td className="px-2 py-1.5" colSpan="5">{shpSampleData.deliveryAddress}</td>
              </tr>
            </tbody>
          </table>

          {/* 1. 부자재 - 감기샤프트, 각파이프, 앵글 */}
          <div className="text-sm font-bold mb-1">1. 부자재 - 감기샤프트, 각파이프, 앵글</div>
          <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
            <tbody>
              <tr>
                {/* 감기샤프트 2인치 */}
                <td className="align-top p-1" style={{ borderRight: '1px solid black', width: '25%' }}>
                  <div className="text-xs font-bold mb-1">감기샤프트</div>
                  <div className="text-xs text-gray-600 mb-1">2인치</div>
                  <div className="text-xs">L : 300</div>
                </td>
                <td className="align-top p-1 text-center font-bold text-lg" style={{ borderRight: '1px solid black', width: '8%' }}>
                  <div className="text-xs text-gray-500 mb-1">수량</div>
                  <div className="text-red-600">11</div>
                </td>
                {/* 감기샤프트 4인치 */}
                <td className="align-top p-1" style={{ borderRight: '1px solid black', width: '25%' }}>
                  <div className="text-xs font-bold mb-1">감기샤프트</div>
                  <div className="text-xs text-gray-600 mb-1">4인치</div>
                  <table className="w-full text-xs">
                    <tbody>
                      <tr><td>L : 3,000</td></tr>
                      <tr><td>L : 4,500</td><td className="text-right font-bold text-red-600">3</td></tr>
                      <tr><td>L : 6,000</td><td className="text-right font-bold text-red-600">3</td></tr>
                    </tbody>
                  </table>
                </td>
                <td className="align-top p-1 text-center font-bold text-lg" style={{ borderRight: '1px solid black', width: '8%' }}>
                  <div className="text-xs text-gray-500 mb-1">수량</div>
                </td>
                {/* 감기샤프트 5인치 */}
                <td className="align-top p-1" style={{ borderRight: '1px solid black', width: '25%' }}>
                  <div className="text-xs font-bold mb-1">감기샤프트</div>
                  <div className="text-xs text-gray-600 mb-1">5인치</div>
                  <table className="w-full text-xs">
                    <tbody>
                      <tr><td>L : 6,000</td></tr>
                      <tr><td>L : 7,000</td><td className="text-right font-bold text-red-600">2</td></tr>
                      <tr><td>L : 8,200</td><td className="text-right font-bold text-red-600">3</td></tr>
                    </tbody>
                  </table>
                </td>
                <td className="align-top p-1 text-center font-bold text-lg" style={{ width: '9%' }}>
                  <div className="text-xs text-gray-500 mb-1">수량</div>
                </td>
              </tr>
              <tr style={{ borderTop: '1px solid black' }}>
                {/* 각파이프 */}
                <td className="align-top p-1" style={{ borderRight: '1px solid black' }}>
                  <div className="text-xs font-bold mb-1">각파이프</div>
                  <div className="text-xs text-gray-600">(50*30*1.4T)</div>
                  <div className="text-xs mt-1">L : 3,000</div>
                  <div className="text-xs">L : 6,000</div>
                </td>
                <td className="align-top p-1 text-center font-bold text-lg" style={{ borderRight: '1px solid black' }}>
                  <div className="text-xs text-gray-500 mb-1">수량</div>
                  <div className="text-red-600">56</div>
                </td>
                {/* 마철봉 */}
                <td className="align-top p-1" style={{ borderRight: '1px solid black' }}>
                  <div className="text-xs font-bold mb-1">마철봉</div>
                  <div className="text-xs text-gray-600">(6mm)</div>
                  <div className="text-xs mt-1">L : 3,000</div>
                </td>
                <td className="align-top p-1 text-center font-bold text-lg" style={{ borderRight: '1px solid black' }}>
                  <div className="text-xs text-gray-500 mb-1">수량</div>
                  <div className="text-red-600">27</div>
                </td>
                {/* 하단 무게평철 */}
                <td className="align-top p-1" style={{ borderRight: '1px solid black' }}>
                  <div className="text-xs font-bold mb-1">하단 무게평철</div>
                  <div className="text-xs text-gray-600">[50*12T]</div>
                  <div className="text-xs mt-1">L : 2,000</div>
                </td>
                <td className="align-top p-1 text-center font-bold text-lg">
                  <div className="text-xs text-gray-500 mb-1">수량</div>
                  <div className="text-red-600">67</div>
                </td>
              </tr>
              <tr style={{ borderTop: '1px solid black' }}>
                <td colSpan="4" className="p-1 text-xs text-gray-600">
                  ※ 별도 추가사항 - 부자재
                </td>
                {/* 앵글 */}
                <td className="align-top p-1" style={{ borderRight: '1px solid black' }}>
                  <div className="text-xs font-bold mb-1">앵글</div>
                  <div className="text-xs text-gray-600">(40*40*3T)</div>
                  <div className="text-xs mt-1">L : 380</div>
                  <div className="text-xs">L : 2,500</div>
                </td>
                <td className="align-top p-1 text-center font-bold text-lg">
                  <div className="text-xs text-gray-500 mb-1">수량</div>
                  <div className="text-red-600">44</div>
                </td>
              </tr>
            </tbody>
          </table>

          {/* 2. 모터 */}
          <div className="text-sm font-bold mb-1">2. 모터</div>
          <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
            <tbody>
              <tr>
                {/* 2-1. 모터(220V 단상) */}
                <td colSpan="3" className="p-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black', width: '50%' }}>
                  <div className="text-xs font-bold mb-2">2-1. 모터(220V 단상)</div>
                  <table className="w-full text-xs">
                    <thead>
                      <tr className="bg-gray-100">
                        <th className="py-1 border-b border-gray-300 text-left px-1">모터 용량</th>
                        <th className="py-1 border-b border-gray-300 text-center" style={{ width: '50px' }}>수량</th>
                        <th className="py-1 border-b border-gray-300 text-center">입고 LOT NO.</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr><td className="py-1 px-1">KD-150K</td><td className="text-center"></td><td></td></tr>
                      <tr><td className="py-1 px-1">KD-300K</td><td className="text-center"></td><td></td></tr>
                      <tr><td className="py-1 px-1">KD-400K</td><td className="text-center"></td><td></td></tr>
                    </tbody>
                  </table>
                </td>
                {/* 2-2. 모터(380V 삼상) */}
                <td colSpan="3" className="p-1" style={{ borderBottom: '1px solid black' }}>
                  <div className="text-xs font-bold mb-2">2-2. 모터(380V 삼상)</div>
                  <table className="w-full text-xs">
                    <thead>
                      <tr className="bg-gray-100">
                        <th className="py-1 border-b border-gray-300 text-left px-1">모터 용량</th>
                        <th className="py-1 border-b border-gray-300 text-center" style={{ width: '50px' }}>수량</th>
                        <th className="py-1 border-b border-gray-300 text-center">입고 LOT NO.</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr><td className="py-1 px-1">KD-150K</td><td className="text-center font-bold text-red-600">6</td><td></td></tr>
                      <tr><td className="py-1 px-1">KD-300K</td><td className="text-center font-bold text-red-600">5</td><td></td></tr>
                      <tr><td className="py-1 px-1">KD-400K</td><td className="text-center"></td><td></td></tr>
                    </tbody>
                  </table>
                </td>
              </tr>
              <tr>
                {/* 2-3. 브라켓트 */}
                <td colSpan="3" className="p-1" style={{ borderRight: '1px solid black' }}>
                  <div className="text-xs font-bold mb-2">2-3. 브라켓트</div>
                  <table className="w-full text-xs">
                    <thead>
                      <tr className="bg-gray-100">
                        <th className="py-1 border-b border-gray-300 text-left px-1">브라켓트</th>
                        <th className="py-1 border-b border-gray-300 text-center" style={{ width: '50px' }}>수량</th>
                        <th className="py-1 border-b border-gray-300 text-center">입고 LOT NO.</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr><td className="py-1 px-1">380*180 (2-4")</td><td className="text-center font-bold text-red-600">6</td><td></td></tr>
                      <tr><td className="py-1 px-1">380*180 (2-5")</td><td className="text-center font-bold text-red-600">5</td><td></td></tr>
                    </tbody>
                  </table>
                </td>
                {/* 2-4. 연동제어기 */}
                <td colSpan="3" className="p-1">
                  <div className="text-xs font-bold mb-2">2-4. 연동제어기</div>
                  <table className="w-full text-xs">
                    <thead>
                      <tr className="bg-gray-100">
                        <th className="py-1 border-b border-gray-300 text-left px-1">품명</th>
                        <th className="py-1 border-b border-gray-300 text-center" style={{ width: '50px' }}>수량</th>
                        <th className="py-1 border-b border-gray-300 text-center">입고 LOT NO.</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr><td className="py-1 px-1">매립형</td><td className="text-center"></td><td></td></tr>
                      <tr><td className="py-1 px-1">노출형</td><td className="text-center"></td><td></td></tr>
                      <tr><td className="py-1 px-1">뒷박스</td><td className="text-center"></td><td></td></tr>
                    </tbody>
                  </table>
                </td>
              </tr>
              <tr style={{ borderTop: '1px solid black' }}>
                <td colSpan="6" className="p-1 text-xs text-gray-600">
                  ※ 별도 추가사항 - 모터
                </td>
              </tr>
            </tbody>
          </table>

          {/* 하단 - 서명 영역 */}
          <div className="flex justify-end mt-8">
            <table className="border-collapse" style={{ fontSize: '10px', border: '1px solid black' }}>
              <tbody>
                <tr>
                  <td className="px-4 py-2 text-center bg-gray-100 font-semibold" style={{ borderRight: '1px solid black' }}>출고 담당</td>
                  <td className="px-8 py-4 text-center" style={{ width: '100px' }}></td>
                </tr>
                <tr>
                  <td className="px-4 py-2 text-center bg-gray-100 font-semibold" style={{ borderRight: '1px solid black', borderTop: '1px solid black' }}>인수 확인</td>
                  <td className="px-8 py-4 text-center" style={{ borderTop: '1px solid black' }}></td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      );
    }

    // 납품확인서 (DC) 미리보기
    if (docCode === 'DC') {
      const dlvSampleData = {
        orderDate: '2025년 10월 15일 수요일',
        customerName: '주일',
        siteName: '용신고등학교(4층)',
        managerName: '김영민과장',
        phone: '010-1234-5678',
        deliveryDate: '2025년 10월 29일 수요일',
        lotNo: 'KD-WE-251015-01-(3)',
        receiverName: '오천식반장',
        receiverPhone: '010-9414-7929',
        deliveryAddress: '경기도 용인시 처인구 고림동 320-6 용신고등학교',
      };

      const dlvItems = [
        { no: 1, productName: '국민방화스크린플러스셔터', spec: 'W3000 x H3500', unit: 'SET', qty: 3, remark: '' },
        { no: 2, productName: '국민방화스크린플러스셔터', spec: 'W4500 x H4000', unit: 'SET', qty: 5, remark: '' },
        { no: 3, productName: '국민방화스크린플러스셔터', spec: 'W6000 x H3200', unit: 'SET', qty: 3, remark: '' },
        { no: 4, productName: '감기샤프트 4인치', spec: 'L4500', unit: 'EA', qty: 3, remark: '' },
        { no: 5, productName: '감기샤프트 4인치', spec: 'L6000', unit: 'EA', qty: 3, remark: '' },
        { no: 6, productName: '감기샤프트 5인치', spec: 'L7000', unit: 'EA', qty: 2, remark: '' },
        { no: 7, productName: '감기샤프트 5인치', spec: 'L8200', unit: 'EA', qty: 3, remark: '' },
      ];

      return (
        <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '10mm', fontSize: '10px' }}>
          {/* 헤더 - 공통 함수 사용 */}
          {renderKDHeader('납 품 확 인 서', '출하 관리부서', {
            writer: '전진',
            writerDate: '10/29',
            writerDept: '판매/전진',
            reviewerDept: '출하',
            approverDept: '품질'
          })}

          {/* 전화 / 팩스 / 이메일 */}
          <div className="text-xs text-center mb-3 text-gray-600">
            전화 : 031-938-5130 | 팩스 : 02-6911-6315 | 이메일 : kd5130@naver.com
          </div>

          {/* 납품 정보 테이블 */}
          <table className="w-full border-collapse mb-3" style={{ fontSize: '9px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td colSpan="2" className="text-center font-bold py-1.5 bg-gray-200 text-sm" style={{ width: '50%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 정 보</td>
                <td colSpan="2" className="text-center font-bold py-1.5 bg-gray-200 text-sm" style={{ width: '50%', borderBottom: '1px solid black' }}>납 품 정 보</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-2 font-semibold" style={{ width: '80px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 일</td>
                <td className="px-2 py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{dlvSampleData.orderDate}</td>
                <td className="text-center bg-gray-100 py-2 font-semibold" style={{ width: '80px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>납 품 일</td>
                <td className="px-2 py-2 font-bold" style={{ borderBottom: '1px solid black' }}>{dlvSampleData.deliveryDate}</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 처</td>
                <td className="px-2 py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{dlvSampleData.customerName}</td>
                <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>현 장 명</td>
                <td className="px-2 py-2 font-bold" style={{ borderBottom: '1px solid black' }}>{dlvSampleData.siteName}</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>담 당 자</td>
                <td className="px-2 py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{dlvSampleData.managerName}</td>
                <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>인수담당자</td>
                <td className="px-2 py-2 font-bold" style={{ borderBottom: '1px solid black' }}>{dlvSampleData.receiverName}</td>
              </tr>
              <tr>
                <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>연 락 처</td>
                <td className="px-2 py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{dlvSampleData.phone}</td>
                <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>인수자연락처</td>
                <td className="px-2 py-2" style={{ borderBottom: '1px solid black' }}>{dlvSampleData.receiverPhone}</td>
              </tr>
              <tr>
                <td className="text-center bg-yellow-300 py-2 font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>제품 LOT NO.</td>
                <td className="px-2 py-2 font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{dlvSampleData.lotNo}</td>
                <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>납품지 주소</td>
                <td className="px-2 py-2" style={{ borderBottom: '1px solid black' }}>{dlvSampleData.deliveryAddress}</td>
              </tr>
            </tbody>
          </table>

          {/* 납품 품목 테이블 */}
          <div className="text-sm font-bold mb-2">납품 품목</div>
          <table className="w-full border-collapse mb-4" style={{ fontSize: '9px', border: '2px solid black' }}>
            <thead>
              <tr className="bg-gray-200">
                <th className="py-2 text-center font-bold" style={{ width: '40px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>No</th>
                <th className="py-2 text-center font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>품 명</th>
                <th className="py-2 text-center font-bold" style={{ width: '120px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>규 격</th>
                <th className="py-2 text-center font-bold" style={{ width: '50px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>단위</th>
                <th className="py-2 text-center font-bold" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>수량</th>
                <th className="py-2 text-center font-bold" style={{ width: '100px', borderBottom: '1px solid black' }}>비 고</th>
              </tr>
            </thead>
            <tbody>
              {dlvItems.map((item, idx) => (
                <tr key={idx}>
                  <td className="py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.no}</td>
                  <td className="py-2 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.productName}</td>
                  <td className="py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.spec}</td>
                  <td className="py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.unit}</td>
                  <td className="py-2 text-center font-bold text-red-600" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.qty}</td>
                  <td className="py-2 px-2" style={{ borderBottom: '1px solid black' }}>{item.remark}</td>
                </tr>
              ))}
              {/* 빈 행 추가 (총 10행) */}
              {Array.from({ length: 10 - dlvItems.length }).map((_, idx) => (
                <tr key={`empty-${idx}`}>
                  <td className="py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{dlvItems.length + idx + 1}</td>
                  <td className="py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                  <td className="py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                  <td className="py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                  <td className="py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                  <td className="py-2" style={{ borderBottom: '1px solid black' }}></td>
                </tr>
              ))}
            </tbody>
          </table>

          {/* 특기사항 */}
          <div className="text-sm font-bold mb-2">특기사항</div>
          <table className="w-full border-collapse mb-6" style={{ fontSize: '9px', border: '2px solid black' }}>
            <tbody>
              <tr>
                <td className="p-3" style={{ height: '60px' }}>
                  위 물품을 상기와 같이 납품합니다.
                </td>
              </tr>
            </tbody>
          </table>

          {/* 하단 - 서명 영역 */}
          <div className="flex justify-between mt-8">
            {/* 납품자 서명 */}
            <table className="border-collapse" style={{ fontSize: '10px', border: '1px solid black' }}>
              <tbody>
                <tr>
                  <td colSpan="2" className="px-4 py-2 text-center bg-gray-200 font-bold" style={{ borderBottom: '1px solid black' }}>납 품 자</td>
                </tr>
                <tr>
                  <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>회 사 명</td>
                  <td className="px-4 py-2" style={{ width: '150px', borderBottom: '1px solid black' }}>경동기업</td>
                </tr>
                <tr>
                  <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>담 당 자</td>
                  <td className="px-4 py-2" style={{ borderBottom: '1px solid black' }}>전진</td>
                </tr>
                <tr>
                  <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black' }}>서명/날인</td>
                  <td className="px-4 py-6 text-center"></td>
                </tr>
              </tbody>
            </table>

            {/* 인수자 서명 */}
            <table className="border-collapse" style={{ fontSize: '10px', border: '1px solid black' }}>
              <tbody>
                <tr>
                  <td colSpan="2" className="px-4 py-2 text-center bg-gray-200 font-bold" style={{ borderBottom: '1px solid black' }}>인 수 자</td>
                </tr>
                <tr>
                  <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>회 사 명</td>
                  <td className="px-4 py-2" style={{ width: '150px', borderBottom: '1px solid black' }}></td>
                </tr>
                <tr>
                  <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>담 당 자</td>
                  <td className="px-4 py-2" style={{ borderBottom: '1px solid black' }}></td>
                </tr>
                <tr>
                  <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black' }}>서명/날인</td>
                  <td className="px-4 py-6 text-center"></td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 하단 안내문 */}
          <div className="text-xs text-center text-gray-500 mt-6">
            상기 물품을 정히 인수하였음을 확인합니다.
          </div>
        </div>
      );
    }

    return <div className="text-center text-gray-500 py-8">미리보기가 준비되지 않은 문서입니다.</div>;
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <FileText className="w-6 h-6 text-blue-500" />
          문서양식 목록
        </h1>
        <div className="flex items-center justify-end">
          <button
            onClick={handleOpenCreateModal}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm flex items-center gap-1"
          >
            <Plus className="w-4 h-4" /> 문서양식 등록
          </button>
        </div>
      </div>

      {/* 카테고리 필터 */}
      <div className="flex items-center gap-2 flex-wrap">
        <button
          onClick={() => setSelectedCategory('all')}
          className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-full border transition-colors ${selectedCategory === 'all'
              ? 'bg-gray-900 text-white border-gray-900'
              : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
            }`}
        >
          전체 ({documentTypes.length})
        </button>
        {documentCategories.map(cat => (
          <button
            key={cat.id}
            onClick={() => setSelectedCategory(cat.id)}
            className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-full border transition-colors ${selectedCategory === cat.id
                ? 'bg-gray-900 text-white border-gray-900'
                : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
              }`}
          >
            {cat.name} ({documentTypes.filter(dt => dt.category === cat.id).length})
          </button>
        ))}
      </div>

      {/* 문서 유형 목록 */}
      <Card>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredDocTypes.map(docType => {
            const category = documentCategories.find(c => c.id === docType.category);
            const hasTemplate = documentTemplates[docType.code];
            return (
              <div
                key={docType.id}
                className={`p-4 border rounded-lg transition-all cursor-pointer ${hasTemplate
                    ? 'hover:border-blue-300 hover:shadow-md'
                    : 'opacity-60 cursor-not-allowed'
                  }`}
                onClick={() => hasTemplate && handleSelectDocType(docType)}
              >
                <div className="flex items-start justify-between">
                  <div>
                    <h3 className="font-medium text-gray-900">{docType.name}</h3>
                    <p className="text-xs text-gray-500">{docType.code}</p>
                  </div>
                  <div className="flex gap-1 items-center">
                    <span className={`px-2 py-0.5 text-xs rounded-full ${docType.isActive ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
                      }`}>
                      {docType.isActive ? '활성' : '비활성'}
                    </span>
                    {hasTemplate && (
                      <span className="px-2 py-0.5 text-xs rounded-full bg-blue-100 text-blue-700">
                        템플릿
                      </span>
                    )}
                  </div>
                </div>
                <p className="mt-2 text-sm text-gray-600">{docType.description}</p>
                <div className="mt-3 flex items-center justify-between">
                  <span className="text-xs text-gray-400">{category?.name}</span>
                  {hasTemplate && (
                    <span className="text-xs text-blue-600">미리보기</span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      {/* 템플릿 상세 보기 */}
      {showTemplateEditor && selectedDocType && (
        <div className="space-y-4">
          {/* 편집기 헤더 */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <button
                onClick={() => setShowTemplateEditor(false)}
                className="p-2 hover:bg-gray-100 rounded-lg"
              >
                <ArrowLeft className="w-5 h-5" />
              </button>
              <div className="flex items-center gap-2">
                <FileText className="w-5 h-5 text-blue-500" />
                <h2 className="text-lg font-semibold">{selectedDocType.name} 템플릿</h2>
                <span className="text-sm text-gray-500">({selectedDocType.code})</span>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => setShowPreviewModal(true)}
                className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
              >
                <Eye className="w-4 h-4" />
                미리보기
              </button>
            </div>
          </div>

          {/* 템플릿 정보 */}
          <Card>
            <div className="space-y-4">
              <div className="font-medium text-gray-900">템플릿 정보</div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">문서 제목</label>
                  <div className="px-3 py-2 border rounded-lg text-sm bg-gray-50">
                    {documentTemplates[selectedDocType.code]?.title || selectedDocType.name}
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">레이아웃</label>
                  <div className="px-3 py-2 border rounded-lg text-sm bg-gray-50">
                    {documentTemplates[selectedDocType.code]?.layout || '-'}
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">회사로고 표시</label>
                  <div className="px-3 py-2 border rounded-lg text-sm bg-gray-50">
                    {documentTemplates[selectedDocType.code]?.showCompanyLogo ? '표시' : '미표시'}
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">결재란 표시</label>
                  <div className="px-3 py-2 border rounded-lg text-sm bg-gray-50">
                    {documentTemplates[selectedDocType.code]?.showApprovalBox ? '표시' : '미표시'}
                  </div>
                </div>
              </div>
            </div>
          </Card>

          {/* 결재라인 설정 */}
          {documentTemplates[selectedDocType.code]?.showApprovalBox && (
            <Card>
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <div className="font-medium text-gray-900">결재라인 설정</div>
                    <p className="text-sm text-gray-500">문서 승인을 위한 결재라인을 구성합니다</p>
                  </div>
                  <button
                    onClick={handleAddApprovalLine}
                    className="flex items-center gap-2 px-3 py-1.5 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600"
                  >
                    <Plus className="w-4 h-4" />
                    결재자 추가
                  </button>
                </div>
                <div className="space-y-3">
                  {templateForm.approvalLines.map((line, index) => (
                    <div key={index} className="flex items-center gap-3">
                      <span className="w-8 h-8 bg-blue-100 text-blue-700 rounded-full flex items-center justify-center text-sm font-medium">
                        {index + 1}
                      </span>
                      <select
                        value={line.role}
                        onChange={(e) => {
                          const newLines = [...templateForm.approvalLines];
                          newLines[index].role = e.target.value;
                          setTemplateForm(prev => ({ ...prev, approvalLines: newLines }));
                        }}
                        className="px-3 py-2 border rounded-lg text-sm"
                      >
                        {approvalRoles.map(role => (
                          <option key={role.id} value={role.id}>{role.name}</option>
                        ))}
                      </select>
                      <input
                        type="text"
                        value={line.department || ''}
                        onChange={(e) => {
                          const newLines = [...templateForm.approvalLines];
                          newLines[index].department = e.target.value;
                          setTemplateForm(prev => ({ ...prev, approvalLines: newLines }));
                        }}
                        placeholder="부서"
                        className="flex-1 px-3 py-2 border rounded-lg text-sm"
                      />
                      <button
                        onClick={() => handleRemoveApprovalLine(index)}
                        className="p-2 text-red-500 hover:bg-red-50 rounded-lg"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            </Card>
          )}

          {/* 섹션 구성 */}
          <Card>
            <div className="space-y-4">
              <div className="font-medium text-gray-900">섹션 구성</div>
              <p className="text-sm text-gray-500">문서를 구성하는 섹션 목록입니다</p>
              <div className="space-y-2">
                {documentTemplates[selectedDocType.code]?.sections?.map((section, index) => (
                  <div key={index} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                    <span className="w-6 h-6 bg-blue-100 text-blue-700 rounded-full flex items-center justify-center text-xs font-medium">
                      {index + 1}
                    </span>
                    <div className="flex-1">
                      <div className="font-medium text-gray-800">{section.id}</div>
                      <div className="text-xs text-gray-500">타입: {section.type}</div>
                    </div>
                  </div>
                )) || (
                    <div className="text-center py-4 text-gray-500">섹션 정보가 없습니다</div>
                  )}
              </div>
            </div>
          </Card>

          {/* 미리보기 카드 */}
          <Card>
            <div className="space-y-4">
              <div className="font-medium text-gray-900">문서 미리보기</div>
              <div className="flex justify-center">
                <button
                  onClick={() => setShowPreviewModal(true)}
                  className="flex items-center gap-2 px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                >
                  <Eye className="w-5 h-5" />
                  전체 화면 미리보기
                </button>
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* 필드구성 탭 */}
      {activeTab === 'field' && (
        <Card>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div className="font-medium text-gray-900">사용 가능한 필드 풀</div>
            </div>

            {/* 필드 카테고리별 표시 */}
            <div className="space-y-6">
              {config.fieldCategories.map(category => (
                <div key={category.id} className="space-y-2">
                  <h3 className="font-medium text-gray-800 flex items-center gap-2">
                    <span className="w-6 h-6 bg-blue-100 rounded flex items-center justify-center">
                      <FileText className="w-4 h-4 text-blue-600" />
                    </span>
                    {category.name}
                  </h3>
                  <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2">
                    {config.commonFieldPool
                      .filter(f => f.category === category.id)
                      .map(field => (
                        <div key={field.id} className="p-2 border rounded-lg text-sm hover:bg-gray-50">
                          <div className="font-medium text-gray-800">{field.fieldName}</div>
                          <div className="text-xs text-gray-500">{field.fieldKey} ({field.fieldType})</div>
                        </div>
                      ))
                    }
                  </div>
                </div>
              ))}
            </div>
          </div>
        </Card>
      )}

      {/* 결재라인 탭 */}
      {activeTab === 'approval' && (
        <Card>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div className="font-medium text-gray-900">결재라인 프리셋</div>
              <button className="flex items-center gap-2 px-3 py-1.5 bg-blue-500 text-white rounded-lg text-sm hover:bg-blue-600">
                <Plus className="w-4 h-4" />
                프리셋 추가
              </button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {config.approvalPresets.map(preset => (
                <div key={preset.id} className="p-4 border rounded-lg hover:shadow-md transition-all">
                  <h3 className="font-medium text-gray-900">{preset.name}</h3>
                  <p className="text-sm text-gray-500 mt-1">{preset.description}</p>
                  <div className="mt-3 space-y-2">
                    {preset.lines.map((line, index) => (
                      <div key={index} className="flex items-center gap-2 text-sm">
                        <span className="w-5 h-5 bg-blue-100 text-blue-700 rounded-full flex items-center justify-center text-xs">
                          {index + 1}
                        </span>
                        <span className="text-gray-700">{config.approvalRoles.find(r => r.id === line.role)?.name}</span>
                        {line.department && <span className="text-gray-500">({line.department})</span>}
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </Card>
      )}

      {/* 미리보기 탭 */}
      {activeTab === 'preview' && (
        <Card>
          <div className="text-center py-12 text-gray-500">
            <Eye className="w-12 h-12 mx-auto mb-4 opacity-50" />
            <p>문서유형을 선택하고 편집기에서 미리보기를 확인하세요</p>
          </div>
        </Card>
      )}

      {/* 미리보기 모달 */}
      {showPreviewModal && selectedDocType && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl w-[900px] max-h-[95vh] overflow-hidden">
            <div className="flex items-center justify-between p-4 border-b">
              <div className="flex items-center gap-3">
                <h3 className="font-semibold">{selectedDocType.name} 미리보기</h3>
                <span className="text-sm text-gray-500">({selectedDocType.code})</span>
              </div>
              <div className="flex items-center gap-2">
                <button className="px-3 py-1.5 bg-red-500 text-white rounded text-sm hover:bg-red-600 flex items-center gap-1">
                  <FileText className="w-4 h-4" />
                  PDF
                </button>
                <button className="px-3 py-1.5 bg-blue-500 text-white rounded text-sm hover:bg-blue-600 flex items-center gap-1">
                  <Mail className="w-4 h-4" />
                  이메일
                </button>
                <button className="px-3 py-1.5 bg-purple-500 text-white rounded text-sm hover:bg-purple-600">팩스</button>
                <button className="px-3 py-1.5 bg-yellow-500 text-white rounded text-sm hover:bg-yellow-600">카카오톡</button>
                <button className="px-3 py-1.5 border rounded text-sm flex items-center gap-1 hover:bg-gray-50">
                  <Printer className="w-4 h-4" />
                  인쇄
                </button>
                <button
                  onClick={() => setShowPreviewModal(false)}
                  className="p-1.5 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold"
                >
                  ✕
                </button>
              </div>
            </div>
            <div className="p-6 overflow-y-auto max-h-[calc(95vh-70px)] bg-gray-100">
              {renderDocumentPreview(selectedDocType.code)}
            </div>
          </div>
        </div>
      )}

      {/* 통합 문서양식 등록/편집 모달 */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl w-[1200px] max-h-[95vh] overflow-hidden">
            {/* 모달 헤더 */}
            <div className="flex items-center justify-between p-4 border-b bg-gradient-to-r from-blue-500 to-blue-600">
              <div className="flex items-center gap-3 text-white">
                <FileText className="w-6 h-6" />
                <div>
                  <h3 className="font-bold text-lg">새 문서양식 등록</h3>
                  <p className="text-sm text-blue-100">섹션을 조합하여 새로운 문서 양식을 만듭니다</p>
                </div>
              </div>
              <button
                onClick={() => setShowCreateModal(false)}
                className="p-2 hover:bg-white/20 rounded-lg transition-colors"
              >
                <X className="w-5 h-5 text-white" />
              </button>
            </div>

            {/* 모달 본문 - 2컬럼 레이아웃 */}
            <div className="flex h-[calc(95vh-140px)]">
              {/* 왼쪽: 설정 영역 */}
              <div className="w-1/2 p-6 overflow-y-auto border-r">
                {/* 기본 정보 */}
                <div className="mb-6">
                  <h4 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
                    <Settings className="w-4 h-4" />
                    기본 정보
                  </h4>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">문서 코드 *</label>
                      <input
                        type="text"
                        value={templateForm.code}
                        onChange={(e) => setTemplateForm(prev => ({ ...prev, code: e.target.value.toUpperCase() }))}
                        placeholder="예: QT, SO, WO"
                        className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">카테고리 *</label>
                      <select
                        value={templateForm.category}
                        onChange={(e) => setTemplateForm(prev => ({ ...prev, category: e.target.value }))}
                        className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      >
                        {documentCategories.map(cat => (
                          <option key={cat.id} value={cat.id}>{cat.icon} {cat.name}</option>
                        ))}
                      </select>
                    </div>
                    <div className="col-span-2">
                      <label className="block text-sm font-medium text-gray-700 mb-1">문서 제목 *</label>
                      <input
                        type="text"
                        value={templateForm.title}
                        onChange={(e) => setTemplateForm(prev => ({ ...prev, title: e.target.value }))}
                        placeholder="예: 견 적 서, 수입검사 성적서"
                        className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      />
                    </div>
                    <div className="col-span-2">
                      <label className="block text-sm font-medium text-gray-700 mb-1">설명</label>
                      <input
                        type="text"
                        value={templateForm.description}
                        onChange={(e) => setTemplateForm(prev => ({ ...prev, description: e.target.value }))}
                        placeholder="문서에 대한 간단한 설명"
                        className="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      />
                    </div>
                  </div>
                </div>

                {/* 용지 설정 */}
                <div className="mb-6">
                  <h4 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
                    <FileText className="w-4 h-4" />
                    용지 설정
                  </h4>
                  <div className="grid grid-cols-3 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">용지 크기</label>
                      <select
                        value={templateForm.paperSize}
                        onChange={(e) => setTemplateForm(prev => ({ ...prev, paperSize: e.target.value }))}
                        className="w-full px-3 py-2 border rounded-lg text-sm"
                      >
                        <option value="A4">A4</option>
                        <option value="A3">A3</option>
                        <option value="B4">B4</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">방향</label>
                      <select
                        value={templateForm.orientation}
                        onChange={(e) => setTemplateForm(prev => ({ ...prev, orientation: e.target.value }))}
                        className="w-full px-3 py-2 border rounded-lg text-sm"
                      >
                        <option value="portrait">세로</option>
                        <option value="landscape">가로</option>
                      </select>
                    </div>
                    <div className="flex flex-col justify-end gap-2">
                      <label className="flex items-center gap-2 text-sm">
                        <input
                          type="checkbox"
                          checked={templateForm.showCompanyLogo}
                          onChange={(e) => setTemplateForm(prev => ({ ...prev, showCompanyLogo: e.target.checked }))}
                          className="rounded"
                        />
                        회사 로고 표시
                      </label>
                      <label className="flex items-center gap-2 text-sm">
                        <input
                          type="checkbox"
                          checked={templateForm.showApprovalBox}
                          onChange={(e) => setTemplateForm(prev => ({ ...prev, showApprovalBox: e.target.checked }))}
                          className="rounded"
                        />
                        결재란 표시
                      </label>
                    </div>
                  </div>
                </div>

                {/* 섹션 추가 */}
                <div className="mb-6">
                  <h4 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
                    <Layers className="w-4 h-4" />
                    섹션 추가
                  </h4>
                  <p className="text-sm text-gray-500 mb-3">아래 섹션을 클릭하여 문서에 추가하세요</p>
                  <div className="grid grid-cols-3 gap-2">
                    {sectionTypeOptions.map(section => (
                      <button
                        key={section.id}
                        onClick={() => handleAddSection(section)}
                        className="p-3 border rounded-lg text-left hover:border-blue-400 hover:bg-blue-50 transition-colors group"
                      >
                        <div className="font-medium text-sm text-gray-800 group-hover:text-blue-600">{section.name}</div>
                        <div className="text-xs text-gray-500">{section.description}</div>
                      </button>
                    ))}
                  </div>
                </div>

                {/* 구성된 섹션 목록 */}
                <div>
                  <h4 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
                    <ClipboardList className="w-4 h-4" />
                    구성된 섹션 ({templateForm.sections.length})
                  </h4>
                  {templateForm.sections.length === 0 ? (
                    <div className="text-center py-8 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
                      <Layers className="w-12 h-12 mx-auto text-gray-300 mb-2" />
                      <p className="text-gray-500 text-sm">위에서 섹션을 선택하여 추가하세요</p>
                    </div>
                  ) : (
                    <div className="space-y-2">
                      {templateForm.sections.map((section, index) => (
                        <div key={section.id} className="flex items-center gap-2 p-3 bg-gray-50 rounded-lg border">
                          <span className="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-xs font-bold">
                            {index + 1}
                          </span>
                          <div className="flex-1">
                            <div className="font-medium text-sm">{section.typeName}</div>
                            <div className="text-xs text-gray-500">타입: {section.type}</div>
                          </div>
                          <div className="flex items-center gap-1">
                            <button
                              onClick={() => handleMoveSectionUp(index)}
                              disabled={index === 0}
                              className={`p-1.5 rounded ${index === 0 ? 'text-gray-300' : 'text-gray-500 hover:bg-gray-200'}`}
                            >
                              <ChevronUp className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => handleMoveSectionDown(index)}
                              disabled={index === templateForm.sections.length - 1}
                              className={`p-1.5 rounded ${index === templateForm.sections.length - 1 ? 'text-gray-300' : 'text-gray-500 hover:bg-gray-200'}`}
                            >
                              <ChevronDown className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => handleRemoveSection(section.id)}
                              className="p-1.5 text-red-500 hover:bg-red-50 rounded"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>

              {/* 오른쪽: 실시간 미리보기 */}
              <div className="w-1/2 p-6 bg-gray-100 overflow-y-auto">
                <h4 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
                  <Eye className="w-4 h-4" />
                  실시간 미리보기
                </h4>
                <div className="bg-white shadow-lg mx-auto" style={{ width: '180mm', minHeight: '250mm', padding: '10mm', fontSize: '9px' }}>
                  {/* 미리보기 헤더 */}
                  {templateForm.title && (
                    <div className="text-center mb-4">
                      <h1 className="text-xl font-bold tracking-[0.5em]">{templateForm.title}</h1>
                      <div className="text-xs text-gray-500 mt-1">
                        문서번호: {templateForm.code || 'XX'}-YYMMDD-01
                      </div>
                    </div>
                  )}

                  {/* 섹션별 미리보기 */}
                  {templateForm.sections.map((section, index) => (
                    <div key={section.id} className="mb-3 border border-dashed border-gray-300 p-2 rounded">
                      <div className="text-xs text-blue-600 font-medium mb-1">
                        [{index + 1}] {section.typeName}
                      </div>
                      {/* 섹션 타입별 미리보기 */}
                      {section.type === 'header' && (
                        <div className="bg-gray-50 p-2 text-center text-sm font-bold">문서 제목 영역</div>
                      )}
                      {section.type === 'partyInfo' && (
                        <table className="w-full border text-xs">
                          <tbody>
                            <tr><th className="border bg-gray-100 p-1 w-20">상호</th><td className="border p-1">OOO건설</td><th className="border bg-gray-100 p-1 w-20">사업자번호</th><td className="border p-1">000-00-00000</td></tr>
                            <tr><th className="border bg-gray-100 p-1">대표자</th><td className="border p-1">홍길동</td><th className="border bg-gray-100 p-1">연락처</th><td className="border p-1">02-000-0000</td></tr>
                          </tbody>
                        </table>
                      )}
                      {section.type === 'infoTable' && (
                        <table className="w-full border text-xs">
                          <tbody>
                            <tr><th className="border bg-gray-100 p-1 w-24">항목1</th><td className="border p-1">값1</td><th className="border bg-gray-100 p-1 w-24">항목2</th><td className="border p-1">값2</td></tr>
                          </tbody>
                        </table>
                      )}
                      {section.type === 'amountBox' && (
                        <div className="border-2 border-black p-3 text-center">
                          <div className="text-xs">총 금액</div>
                          <div className="text-lg font-bold">₩ 0,000,000</div>
                        </div>
                      )}
                      {section.type === 'productTable' && (
                        <table className="w-full border text-xs">
                          <thead className="bg-gray-100"><tr><th className="border p-1">NO</th><th className="border p-1">품명</th><th className="border p-1">규격</th><th className="border p-1">수량</th><th className="border p-1">단가</th><th className="border p-1">금액</th></tr></thead>
                          <tbody><tr><td className="border p-1 text-center">1</td><td className="border p-1"></td><td className="border p-1"></td><td className="border p-1"></td><td className="border p-1"></td><td className="border p-1"></td></tr></tbody>
                        </table>
                      )}
                      {section.type === 'inspectionTable' && (
                        <table className="w-full border text-xs">
                          <thead className="bg-gray-100"><tr><th className="border p-1">NO</th><th className="border p-1">검사항목</th><th className="border p-1">검사기준</th><th className="border p-1">측정값</th><th className="border p-1">판정</th></tr></thead>
                          <tbody><tr><td className="border p-1 text-center">1</td><td className="border p-1">외관검사</td><td className="border p-1">육안검사</td><td className="border p-1"></td><td className="border p-1 text-center">□적합 □부적합</td></tr></tbody>
                        </table>
                      )}
                      {section.type === 'remarks' && (
                        <div className="border p-2 min-h-[40px]">
                          <div className="text-xs text-gray-400">[비고사항 입력 영역]</div>
                        </div>
                      )}
                      {section.type === 'signature' && (
                        <div className="flex justify-end items-end mt-4">
                          <div className="text-right text-xs mr-4">
                            <p>상기와 같이 확인합니다.</p>
                            <p className="mt-2">2025년 00월 00일</p>
                            <p>회사명: (주)OOO (인)</p>
                          </div>
                          <div className="border w-12 h-12 flex items-center justify-center text-[8px] text-gray-400">(인감)</div>
                        </div>
                      )}
                      {section.type === 'approval' && (
                        <table className="border text-xs ml-auto">
                          <thead><tr><th className="border bg-gray-100 px-4 py-1">작성</th><th className="border bg-gray-100 px-4 py-1">검토</th><th className="border bg-gray-100 px-4 py-1">승인</th></tr></thead>
                          <tbody><tr><td className="border px-4 py-4"></td><td className="border px-4 py-4"></td><td className="border px-4 py-4"></td></tr></tbody>
                        </table>
                      )}
                      {section.type === 'judgement' && (
                        <div className="flex justify-center gap-4 py-2">
                          <span className="border px-4 py-2 text-sm">□ 합격</span>
                          <span className="border px-4 py-2 text-sm">□ 불합격</span>
                        </div>
                      )}
                      {section.type === 'diagram' && (
                        <div className="border-2 border-dashed border-gray-300 p-4 text-center text-gray-400">
                          [도면/사진 영역]
                        </div>
                      )}
                    </div>
                  ))}

                  {templateForm.sections.length === 0 && !templateForm.title && (
                    <div className="text-center py-16 text-gray-400">
                      <FileText className="w-16 h-16 mx-auto mb-4 opacity-30" />
                      <p>문서 정보와 섹션을 추가하면</p>
                      <p>여기에 미리보기가 표시됩니다</p>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* 모달 푸터 */}
            <div className="flex items-center justify-between p-4 border-t bg-gray-50">
              <div className="text-sm text-gray-500">
                {templateForm.sections.length > 0 && (
                  <span>총 {templateForm.sections.length}개 섹션 구성됨</span>
                )}
              </div>
              <div className="flex gap-2">
                <button
                  onClick={() => setShowCreateModal(false)}
                  className="px-4 py-2 border rounded-lg text-gray-700 hover:bg-gray-100"
                >
                  취소
                </button>
                <button
                  onClick={handleSaveTemplate}
                  disabled={!templateForm.title || !templateForm.code || templateForm.sections.length === 0}
                  className={`px-6 py-2 rounded-lg flex items-center gap-2 ${templateForm.title && templateForm.code && templateForm.sections.length > 0
                      ? 'bg-blue-600 text-white hover:bg-blue-700'
                      : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                    }`}
                >
                  <Save className="w-4 h-4" />
                  문서양식 저장
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============ 단가 관리 (4탭 구조: 매입단가/매출단가/BOM제품단가/리포트) ============

const PriceList = ({ onNavigate }) => {
  const [search, setSearch] = useState('');
  const [activeMainTab, setActiveMainTab] = useState('purchase'); // purchase, sales, bom, report
  const [itemTypeFilter, setItemTypeFilter] = useState('전체');
  const [showModal, setShowModal] = useState(false);
  const [modalMode, setModalMode] = useState(''); // purchase-edit, sales-edit, sales-batch, version-new
  const [selectedItem, setSelectedItem] = useState(null);

  // ===== ① 매입단가 데이터 =====
  const [purchasePrices, setPurchasePrices] = useState([
    { id: 1, itemType: '부품', itemCode: 'GR-001', itemName: '가이드레일 130×80', spec: '130×80×2438', unit: 'EA', supplier: '철강공업', purchasePrice: 45000, validFrom: '2025-01-01', validTo: '2025-12-31', status: '활성', history: [{ date: '2025-01-01', price: 45000, supplier: '철강공업', by: '김관리' }, { date: '2024-07-01', price: 42000, supplier: '철강공업', by: '김관리' }] },
    { id: 2, itemType: '부품', itemCode: 'CASE-001', itemName: '케이스 철재', spec: '표준형', unit: 'EA', supplier: '케이스공업', purchasePrice: 35000, validFrom: '2025-01-01', validTo: null, status: '활성', history: [{ date: '2025-01-01', price: 35000, supplier: '케이스공업', by: '김관리' }] },
    { id: 3, itemType: '부품', itemCode: 'MOTOR-001', itemName: '모터 0.4KW', spec: '0.4KW', unit: 'EA', supplier: '모터공급사', purchasePrice: 120000, validFrom: '2025-01-01', validTo: null, status: '활성', history: [{ date: '2025-01-01', price: 120000, supplier: '모터공급사', by: '김관리' }, { date: '2024-06-01', price: 115000, supplier: '모터공급사', by: '이담당' }] },
    { id: 4, itemType: '부품', itemCode: 'CTL-001', itemName: '제어기 기본형', spec: '기본형', unit: 'EA', supplier: '제어기공급사', purchasePrice: 80000, validFrom: '2025-01-01', validTo: null, status: '활성', history: [] },
    { id: 5, itemType: '원자재', itemCode: 'STEEL-P01', itemName: '아연도금강판', spec: 't1.2×1219×2438', unit: 'EA', supplier: '포스코', purchasePrice: 32000, validFrom: '2025-01-01', validTo: null, status: '활성', history: [{ date: '2025-01-01', price: 32000, supplier: '포스코', by: '김관리' }] },
    { id: 6, itemType: '부자재', itemCode: 'BOLT-001', itemName: '볼트 M8×20', spec: 'M8×20', unit: 'EA', supplier: '나사공급사', purchasePrice: 120, validFrom: '2025-01-01', validTo: null, status: '활성', history: [] },
    { id: 7, itemType: '부품', itemCode: 'SLT-001', itemName: '슬랫 0.6T', spec: '0.6T×110', unit: 'M', supplier: '슬랫공업', purchasePrice: 8500, validFrom: '2025-01-01', validTo: null, status: '활성', history: [{ date: '2025-01-01', price: 8500, supplier: '슬랫공업', by: '김관리' }] },
  ]);

  // ===== ② 매출단가 데이터 (버전관리) =====
  const [salesSubTab, setSalesSubTab] = useState('items'); // items, versions, customer-groups
  const [selectedVersionId, setSelectedVersionId] = useState(1);

  const [salesPriceVersions, setSalesPriceVersions] = useState([
    { id: 1, versionNo: 'V2025-01', versionName: '2025년 상반기 단가표', status: '활성', createdAt: '2025-01-01', activatedAt: '2025-01-01', createdBy: '김관리', itemCount: 7, note: '2025년 상반기 공시가격 반영' },
    { id: 2, versionNo: 'V2024-02', versionName: '2024년 하반기 단가표', status: '보관', createdAt: '2024-07-01', activatedAt: '2024-07-01', archivedAt: '2024-12-31', createdBy: '김관리', itemCount: 6, note: '2024년 하반기 적용' },
    { id: 3, versionNo: 'V2025-02', versionName: '2025년 하반기 단가표(임시)', status: '임시', createdAt: '2025-06-01', createdBy: '이담당', itemCount: 4, note: '작성중 - 원자재 인상 반영 예정' },
  ]);

  const [salesPrices, setSalesPrices] = useState([
    { id: 1, versionId: 1, itemType: '부품', itemCode: 'GR-001', itemName: '가이드레일 130×80', spec: '130×80×2438', unit: 'EA', purchasePrice: 45000, processingCost: 5000, lossRate: 3, marginType: 'rate', marginValue: 20, sellingPrice: 60000, status: '활성' },
    { id: 2, versionId: 1, itemType: '부품', itemCode: 'CASE-001', itemName: '케이스 철재', spec: '표준형', unit: 'EA', purchasePrice: 35000, processingCost: 10000, lossRate: 2, marginType: 'rate', marginValue: 25, sellingPrice: 56250, status: '활성' },
    { id: 3, versionId: 1, itemType: '부품', itemCode: 'MOTOR-001', itemName: '모터 0.4KW', spec: '0.4KW', unit: 'EA', purchasePrice: 120000, processingCost: 10000, lossRate: 0, marginType: 'rate', marginValue: 15, sellingPrice: 149500, status: '활성' },
    { id: 4, versionId: 1, itemType: '부품', itemCode: 'CTL-001', itemName: '제어기 기본형', spec: '기본형', unit: 'EA', purchasePrice: 80000, processingCost: 5000, lossRate: 0, marginType: 'rate', marginValue: 20, sellingPrice: 102000, status: '활성' },
    { id: 5, versionId: 1, itemType: '원자재', itemCode: 'STEEL-P01', itemName: '아연도금강판', spec: 't1.2×1219×2438', unit: 'EA', purchasePrice: 32000, processingCost: 0, lossRate: 5, marginType: 'rate', marginValue: 15, sellingPrice: 38640, status: '활성' },
    { id: 6, versionId: 1, itemType: '부자재', itemCode: 'BOLT-001', itemName: '볼트 M8×20', spec: 'M8×20', unit: 'EA', purchasePrice: 120, processingCost: 0, lossRate: 0, marginType: 'amount', marginValue: 30, sellingPrice: 150, status: '활성' },
    { id: 7, versionId: 1, itemType: '부품', itemCode: 'SLT-001', itemName: '슬랫 0.6T', spec: '0.6T×110', unit: 'M', purchasePrice: 8500, processingCost: 500, lossRate: 2, marginType: 'rate', marginValue: 18, sellingPrice: 10827, status: '활성' },
  ]);

  // 거래처그룹 단가
  const [customerGroups, setCustomerGroups] = useState([
    { id: 1, groupCode: 'VIP', groupName: 'VIP 고객', discountRate: 10, description: '연간 거래액 1억 이상', customerCount: 5 },
    { id: 2, groupCode: 'GOLD', groupName: '골드 고객', discountRate: 7, description: '연간 거래액 5천만원 이상', customerCount: 12 },
    { id: 3, groupCode: 'SILVER', groupName: '실버 고객', discountRate: 5, description: '연간 거래액 1천만원 이상', customerCount: 28 },
    { id: 4, groupCode: 'NORMAL', groupName: '일반 고객', discountRate: 0, description: '일반 거래 고객', customerCount: 156 },
  ]);

  // ===== ③ BOM/제품단가 데이터 =====
  const [bomViewMode, setBomViewMode] = useState('detail'); // detail, compare
  const [selectedBomProduct, setSelectedBomProduct] = useState(null);

  const [bomProducts, setBomProducts] = useState([
    {
      id: 1, productCode: 'SCREEN-001', productName: '스크린 셔터 기본형', spec: '표준형', unit: 'SET', bomCost: 459000, processingCost: 85000, marginRate: 25, finalPrice: 680000, status: '활성',
      bom: [
        { partCode: 'GR-001', partName: '가이드레일 130×80', qty: 2, unit: 'EA', unitPrice: 45000, totalPrice: 90000 },
        { partCode: 'CASE-001', partName: '케이스 철재', qty: 1, unit: 'EA', unitPrice: 35000, totalPrice: 35000 },
        { partCode: 'MOTOR-001', partName: '모터 0.4KW', qty: 1, unit: 'EA', unitPrice: 120000, totalPrice: 120000 },
        { partCode: 'CTL-001', partName: '제어기 기본형', qty: 1, unit: 'EA', unitPrice: 80000, totalPrice: 80000 },
        { partCode: 'STEEL-P01', partName: '아연도금강판', qty: 4, unit: 'EA', unitPrice: 32000, totalPrice: 128000 },
        { partCode: 'BOLT-001', partName: '볼트 M8×20', qty: 50, unit: 'EA', unitPrice: 120, totalPrice: 6000 },
      ]
    },
    {
      id: 2, productCode: 'SCREEN-002', productName: '스크린 셔터 오픈형', spec: '오픈형', unit: 'SET', bomCost: 520000, processingCost: 95000, marginRate: 25, finalPrice: 768750, status: '활성',
      bom: [
        { partCode: 'GR-001', partName: '가이드레일 130×80', qty: 2, unit: 'EA', unitPrice: 45000, totalPrice: 90000 },
        { partCode: 'CASE-001', partName: '케이스 철재', qty: 1, unit: 'EA', unitPrice: 38000, totalPrice: 38000 },
        { partCode: 'MOTOR-001', partName: '모터 0.4KW', qty: 1, unit: 'EA', unitPrice: 135000, totalPrice: 135000 },
        { partCode: 'CTL-001', partName: '제어기 기본형', qty: 1, unit: 'EA', unitPrice: 85000, totalPrice: 85000 },
        { partCode: 'STEEL-P01', partName: '아연도금강판', qty: 5, unit: 'EA', unitPrice: 32000, totalPrice: 160000 },
        { partCode: 'BOLT-001', partName: '볼트 M8×20', qty: 100, unit: 'EA', unitPrice: 120, totalPrice: 12000 },
      ]
    },
    {
      id: 3, productCode: 'STEEL-001', productName: '철재 셔터 기본형', spec: '표준형', unit: 'SET', bomCost: 380000, processingCost: 70000, marginRate: 22, finalPrice: 548780, status: '활성',
      bom: [
        { partCode: 'GR-001', partName: '가이드레일 130×80', qty: 2, unit: 'EA', unitPrice: 45000, totalPrice: 90000 },
        { partCode: 'CASE-001', partName: '케이스 철재', qty: 1, unit: 'EA', unitPrice: 35000, totalPrice: 35000 },
        { partCode: 'MOTOR-001', partName: '모터 0.4KW', qty: 1, unit: 'EA', unitPrice: 120000, totalPrice: 120000 },
        { partCode: 'SLT-001', partName: '슬랫 0.6T', qty: 15, unit: 'M', unitPrice: 8500, totalPrice: 127500 },
        { partCode: 'BOLT-001', partName: '볼트 M8×20', qty: 60, unit: 'EA', unitPrice: 120, totalPrice: 7200 },
      ]
    },
  ]);

  // ===== ④ 리포트 데이터 =====
  const priceChangeReport = {
    currentMonth: '2025-01', previousMonth: '2024-12',
    summary: { totalItems: 7, increasedItems: 3, decreasedItems: 1, unchangedItems: 3, avgChangeRate: 3.8 },
    details: [
      { itemCode: 'GR-001', itemName: '가이드레일 130×80', prevPrice: 42000, currPrice: 45000, changeAmount: 3000, changeRate: 7.14, direction: 'up' },
      { itemCode: 'MOTOR-001', itemName: '모터 0.4KW', prevPrice: 115000, currPrice: 120000, changeAmount: 5000, changeRate: 4.35, direction: 'up' },
      { itemCode: 'STEEL-P01', itemName: '아연도금강판', prevPrice: 34000, currPrice: 32000, changeAmount: -2000, changeRate: -5.88, direction: 'down' },
      { itemCode: 'CASE-001', itemName: '케이스 철재', prevPrice: 35000, currPrice: 35000, changeAmount: 0, changeRate: 0, direction: 'unchanged' },
      { itemCode: 'CTL-001', itemName: '제어기 기본형', prevPrice: 78000, currPrice: 80000, changeAmount: 2000, changeRate: 2.56, direction: 'up' },
      { itemCode: 'BOLT-001', itemName: '볼트 M8×20', prevPrice: 120, currPrice: 120, changeAmount: 0, changeRate: 0, direction: 'unchanged' },
      { itemCode: 'SLT-001', itemName: '슬랫 0.6T', prevPrice: 8500, currPrice: 8500, changeAmount: 0, changeRate: 0, direction: 'unchanged' },
    ]
  };

  // ===== 탭/필터 정의 =====
  const mainTabs = [
    { id: 'purchase', label: '매입단가', icon: Download },
    { id: 'sales', label: '매출단가', icon: TrendingUp },
    { id: 'bom', label: 'BOM/제품단가', icon: Layers },
    { id: 'report', label: '리포트', icon: BarChart3 },
  ];
  const itemTypeTabs = ['전체', '제품', '부품', '부자재', '원자재', '소모품'];

  // 품목유형별 카운트
  const getTypeCount = (type) => {
    const data = activeMainTab === 'purchase' ? purchasePrices : salesPrices.filter(p => p.versionId === selectedVersionId);
    if (type === '전체') return data.length;
    return data.filter(p => p.itemType === type).length;
  };

  // 필터링 - 매입단가
  const filteredPurchase = purchasePrices
    .filter(p => itemTypeFilter === '전체' || p.itemType === itemTypeFilter)
    .filter(p => p.itemCode.toLowerCase().includes(search.toLowerCase()) || p.itemName.includes(search) || p.spec?.includes(search))
    .sort((a, b) => b.id - a.id); // ID 기준 내림차순 (최신 등록 최상단)

  // 필터링 - 매출단가
  const filteredSales = salesPrices
    .filter(p => p.versionId === selectedVersionId)
    .filter(p => itemTypeFilter === '전체' || p.itemType === itemTypeFilter)
    .filter(p => p.itemCode.toLowerCase().includes(search.toLowerCase()) || p.itemName.includes(search))
    .sort((a, b) => b.id - a.id); // ID 기준 내림차순 (최신 등록 최상단)

  // ===== 통계 =====
  const purchaseTotal = purchasePrices.length;
  const salesTotal = salesPrices.filter(p => p.versionId === selectedVersionId).length;
  const bomTotal = bomProducts.length;
  const activeVersion = salesPriceVersions.find(v => v.status === '활성');

  // ===== 핸들러 =====
  const openPurchaseEditModal = (item) => {
    setSelectedItem(item);
    setModalMode('purchase-edit');
    setShowModal(true);
  };

  const openSalesEditModal = (item) => {
    setSelectedItem(item);
    setModalMode('sales-edit');
    setShowModal(true);
  };

  const handleSavePurchasePrice = (updatedItem) => {
    const now = new Date().toISOString().slice(0, 10);
    const historyEntry = { date: now, price: updatedItem.purchasePrice, supplier: updatedItem.supplier, by: '시스템' };
    const newHistory = [...(updatedItem.history || [])];
    if (!newHistory.some(h => h.date === now && h.price === updatedItem.purchasePrice)) {
      newHistory.unshift(historyEntry);
    }
    setPurchasePrices(prev => prev.map(p => p.id === updatedItem.id ? { ...updatedItem, history: newHistory } : p));
    setShowModal(false);
  };

  const handleSaveSalesPrice = (updatedItem) => {
    setSalesPrices(prev => prev.map(p => p.id === updatedItem.id ? updatedItem : p));
    setShowModal(false);
  };

  // 버전 활성화
  const handleActivateVersion = (versionId) => {
    const now = new Date().toISOString().slice(0, 10);
    setSalesPriceVersions(prev => prev.map(v => ({
      ...v,
      status: v.id === versionId ? '활성' : (v.status === '활성' ? '보관' : v.status),
      activatedAt: v.id === versionId ? now : v.activatedAt,
      archivedAt: v.status === '활성' && v.id !== versionId ? now : v.archivedAt,
    })));
    setSelectedVersionId(versionId);
  };

  // 일괄 재계산
  const handleBatchRecalculate = () => {
    setSalesPrices(prev => prev.map(p => {
      if (p.versionId !== selectedVersionId || !p.purchasePrice) return p;
      const base = p.purchasePrice + (p.processingCost || 0);
      const lossApplied = Math.round(base * (1 + (p.lossRate || 0) / 100));
      const newSellingPrice = p.marginType === 'rate'
        ? Math.round(lossApplied * (1 + p.marginValue / 100))
        : lossApplied + p.marginValue;
      return { ...p, sellingPrice: newSellingPrice };
    }));
  };

  return (
    <div className="space-y-4">
      {/* 헤더 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <DollarSign className="w-6 h-6 text-blue-500" />
          단가 목록
        </h1>
        <div className="flex items-center justify-end gap-2">
          {activeMainTab === 'purchase' && (
            <button onClick={() => { setSelectedItem(null); setModalMode('purchase-add'); setShowModal(true); }}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2">
              <Plus className="w-4 h-4" /> 등록
            </button>
          )}
          {activeMainTab === 'sales' && salesSubTab === 'items' && (
            <button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2">
              <Plus className="w-4 h-4" /> 등록
            </button>
          )}
          {activeMainTab === 'sales' && salesSubTab === 'versions' && (
            <button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2">
              <Plus className="w-4 h-4" /> 새 버전 생성
            </button>
          )}
        </div>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border p-4">
          <div className="flex justify-between items-start">
            <div>
              <p className="text-sm text-gray-500">매입단가 품목</p>
              <p className="text-2xl font-bold text-gray-900 mt-1">{purchaseTotal}</p>
            </div>
            <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
              <Download className="w-5 h-5 text-blue-600" />
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="flex justify-between items-start">
            <div>
              <p className="text-sm text-gray-500">매출단가 품목</p>
              <p className="text-2xl font-bold text-green-600 mt-1">{salesTotal}</p>
            </div>
            <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
              <TrendingUp className="w-5 h-5 text-green-600" />
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="flex justify-between items-start">
            <div>
              <p className="text-sm text-gray-500">BOM 제품</p>
              <p className="text-2xl font-bold text-purple-600 mt-1">{bomTotal}</p>
            </div>
            <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
              <Layers className="w-5 h-5 text-purple-600" />
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="flex justify-between items-start">
            <div>
              <p className="text-sm text-gray-500">활성 버전</p>
              <p className="text-xl font-bold text-orange-600 mt-1">{activeVersion?.versionNo || '-'}</p>
            </div>
            <div className="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center">
              <FileText className="w-5 h-5 text-orange-600" />
            </div>
          </div>
        </div>
      </div>

      {/* 검색 */}
      <div className="bg-white rounded-xl border p-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <input
            type="text"
            placeholder="품목코드, 품목명, 규격 검색..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border-0 text-sm focus:ring-0"
          />
        </div>
      </div>

      {/* 메인 4탭 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        <div className="border-b">
          <div className="flex">
            {mainTabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveMainTab(tab.id)}
                className={`px-6 py-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 ${activeMainTab === tab.id
                    ? 'border-blue-500 text-blue-600 bg-blue-50/50'
                    : 'border-transparent text-gray-500 hover:text-gray-700'
                  }`}
              >
                <tab.icon className="w-4 h-4" />
                {tab.label}
              </button>
            ))}
          </div>
        </div>

        {/* ========== ① 매입단가 탭 ========== */}
        {activeMainTab === 'purchase' && (
          <>
            {/* 품목유형 서브탭 (칩 스타일) */}
            <div className="px-4 py-3 border-b bg-gray-50">
              <div className="flex flex-wrap gap-2">
                {itemTypeTabs.map(tab => (
                  <button
                    key={tab}
                    onClick={() => setItemTypeFilter(tab)}
                    className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-full border transition-colors ${itemTypeFilter === tab
                        ? 'bg-gray-900 text-white border-gray-900'
                        : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                      }`}
                  >
                    {tab}
                    <span className={`text-xs px-1.5 py-0.5 rounded-full ${itemTypeFilter === tab
                        ? 'bg-gray-700 text-white'
                        : 'bg-gray-100 text-gray-500'
                      }`}>
                      {getTypeCount(tab)}
                    </span>
                  </button>
                ))}
              </div>
            </div>

            {/* 매입단가 테이블 */}
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">번호</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목유형</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목코드</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">규격</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">단위</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">공급업체</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">매입단가</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">유효기간</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">이력</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {filteredPurchase.map((item, idx) => (
                    <tr key={item.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3 text-sm text-gray-500">{filteredPurchase.length - idx}</td>
                      <td className="px-4 py-3">
                        <span className={`px-2 py-0.5 rounded text-xs font-medium ${item.itemType === '제품' ? 'bg-blue-100 text-blue-700' :
                            item.itemType === '부품' ? 'bg-orange-100 text-orange-700' :
                              'bg-gray-100 text-gray-700'
                          }`}>
                          {item.itemType}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-sm font-mono text-gray-900">{item.itemCode}</td>
                      <td className="px-4 py-3 text-sm text-gray-900">{item.itemName}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{item.spec || '-'}</td>
                      <td className="px-4 py-3 text-sm text-center text-gray-600">{item.unit}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{item.supplier || '-'}</td>
                      <td className="px-4 py-3 text-sm text-right font-medium text-gray-900">
                        {item.purchasePrice ? `${item.purchasePrice.toLocaleString()}원` : '-'}
                      </td>
                      <td className="px-4 py-3 text-sm text-center text-gray-600">
                        {item.validFrom ? (
                          <span className="text-xs">
                            {item.validFrom}~{item.validTo || '무기한'}
                          </span>
                        ) : '-'}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-0.5 rounded text-xs font-medium ${item.status === '활성' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
                          }`}>
                          {item.status}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-center">
                        {item.history && item.history.length > 0 ? (
                          <button className="text-xs text-blue-600 hover:underline">
                            {item.history.length}건
                          </button>
                        ) : '-'}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <div className="flex justify-center gap-1">
                          <button
                            onClick={() => openPurchaseEditModal(item)}
                            className="p-1 hover:bg-gray-100 rounded"
                            title="수정"
                          >
                            <Edit3 className="w-4 h-4 text-gray-500" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                  {filteredPurchase.length === 0 && (
                    <tr>
                      <td colSpan={12} className="px-4 py-8 text-center text-gray-500">
                        등록된 매입단가가 없습니다.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </>
        )}

        {/* ② 매출단가 탭 */}
        {activeMainTab === 'sales' && (
          <>
            {/* 매출단가 서브탭 */}
            <div className="flex items-center gap-4 mb-4 border-b">
              {[
                { id: 'items', label: '품목별 단가' },
                { id: 'versions', label: '버전관리' },
                { id: 'groups', label: '거래처그룹' },
              ].map(tab => (
                <button
                  key={tab.id}
                  onClick={() => setSalesSubTab(tab.id)}
                  className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px ${salesSubTab === tab.id
                      ? 'border-blue-600 text-blue-600'
                      : 'border-transparent text-gray-500 hover:text-gray-700'
                    }`}
                >
                  {tab.label}
                </button>
              ))}
            </div>

            {/* 품목별 단가 */}
            {salesSubTab === 'items' && (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">번호</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목코드</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">규격</th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">단위</th>
                      <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">원가</th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">마진유형</th>
                      <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">마진</th>
                      <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">판매단가</th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">버전</th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {filteredSales.map((item, idx) => (
                      <tr key={item.id} className="hover:bg-gray-50">
                        <td className="px-4 py-3 text-sm text-gray-500">{filteredSales.length - idx}</td>
                        <td className="px-4 py-3 text-sm font-mono text-gray-900">{item.itemCode}</td>
                        <td className="px-4 py-3 text-sm text-gray-900">{item.itemName}</td>
                        <td className="px-4 py-3 text-sm text-gray-600">{item.spec || '-'}</td>
                        <td className="px-4 py-3 text-sm text-center text-gray-600">{item.unit}</td>
                        <td className="px-4 py-3 text-sm text-right text-gray-600">
                          {item.costPrice?.toLocaleString()}원
                        </td>
                        <td className="px-4 py-3 text-center">
                          <span className={`px-2 py-0.5 rounded text-xs font-medium ${item.marginType === 'rate' ? 'bg-blue-100 text-blue-700' : 'bg-purple-100 text-purple-700'
                            }`}>
                            {item.marginType === 'rate' ? '율(%)' : '액(원)'}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-sm text-right text-gray-600">
                          {item.marginType === 'rate'
                            ? `${item.marginValue}%`
                            : `${item.marginValue?.toLocaleString()}원`}
                        </td>
                        <td className="px-4 py-3 text-sm text-right font-medium text-gray-900">
                          {item.sellingPrice?.toLocaleString()}원
                        </td>
                        <td className="px-4 py-3 text-center">
                          <span className="text-xs text-gray-500">{item.versionNo}</span>
                        </td>
                        <td className="px-4 py-3 text-center">
                          <button
                            onClick={() => openSalesEditModal(item)}
                            className="p-1 hover:bg-gray-100 rounded"
                            title="수정"
                          >
                            <Edit3 className="w-4 h-4 text-gray-500" />
                          </button>
                        </td>
                      </tr>
                    ))}
                    {filteredSales.length === 0 && (
                      <tr>
                        <td colSpan={11} className="px-4 py-8 text-center text-gray-500">
                          등록된 매출단가가 없습니다.
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            )}

            {/* 버전관리 */}
            {salesSubTab === 'versions' && (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">버전번호</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">버전명</th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">품목수</th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">적용기간</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">생성일</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">생성자</th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {[...salesPriceVersions].sort((a, b) => b.id - a.id).map((ver) => (
                      <tr key={ver.id} className={`hover:bg-gray-50 ${selectedVersionId === ver.id ? 'bg-blue-50' : ''}`}>
                        <td className="px-4 py-3 text-sm font-mono text-gray-900">{ver.versionNo}</td>
                        <td className="px-4 py-3 text-sm text-gray-900">{ver.versionName}</td>
                        <td className="px-4 py-3 text-center">
                          <span className={`px-2 py-0.5 rounded text-xs font-medium ${ver.status === '활성' ? 'bg-green-100 text-green-700' :
                              ver.status === '임시' ? 'bg-yellow-100 text-yellow-700' :
                                'bg-gray-100 text-gray-500'
                            }`}>
                            {ver.status}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-sm text-center text-gray-600">{ver.itemCount}건</td>
                        <td className="px-4 py-3 text-sm text-center text-gray-600">
                          {ver.validFrom}~{ver.validTo || '무기한'}
                        </td>
                        <td className="px-4 py-3 text-sm text-gray-600">{ver.createdAt}</td>
                        <td className="px-4 py-3 text-sm text-gray-600">{ver.createdBy}</td>
                        <td className="px-4 py-3 text-center">
                          <div className="flex justify-center gap-1">
                            {ver.status === '임시' && (
                              <button
                                onClick={() => handleActivateVersion(ver.id)}
                                className="px-2 py-1 text-xs bg-green-100 text-green-700 rounded hover:bg-green-200"
                              >
                                활성화
                              </button>
                            )}
                            <button
                              onClick={() => setSelectedVersionId(ver.id)}
                              className="p-1 hover:bg-gray-100 rounded"
                              title="선택"
                            >
                              <Eye className="w-4 h-4 text-gray-500" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}

            {/* 거래처그룹 */}
            {salesSubTab === 'groups' && (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">그룹명</th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">할인율</th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">거래처수</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">설명</th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {[...customerGroups].sort((a, b) => b.id - a.id).map((group) => (
                      <tr key={group.id} className="hover:bg-gray-50">
                        <td className="px-4 py-3 text-sm font-medium text-gray-900">{group.groupName}</td>
                        <td className="px-4 py-3 text-center">
                          <span className="text-sm text-red-600 font-medium">-{group.discountRate}%</span>
                        </td>
                        <td className="px-4 py-3 text-sm text-center text-gray-600">{group.customerCount}개사</td>
                        <td className="px-4 py-3 text-sm text-gray-600">{group.description || '-'}</td>
                        <td className="px-4 py-3 text-center">
                          <button className="p-1 hover:bg-gray-100 rounded" title="수정">
                            <Edit3 className="w-4 h-4 text-gray-500" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </>
        )}

        {/* ③ BOM/제품단가 탭 */}
        {activeMainTab === 'bom' && (
          <div className="flex gap-4">
            {/* 좌측: 제품 목록 */}
            <div className="w-1/3 border-r pr-4">
              <div className="text-sm font-medium text-gray-700 mb-2">제품 목록</div>
              <div className="space-y-1">
                {[...bomProducts].sort((a, b) => b.id - a.id).map((product) => (
                  <button
                    key={product.id}
                    onClick={() => setSelectedBomProduct(product)}
                    className={`w-full text-left px-3 py-2 rounded text-sm ${selectedBomProduct?.id === product.id
                        ? 'bg-blue-100 text-blue-700'
                        : 'hover:bg-gray-100 text-gray-700'
                      }`}
                  >
                    <div className="font-medium">{product.productName}</div>
                    <div className="text-xs text-gray-500">{product.productCode}</div>
                  </button>
                ))}
              </div>
            </div>

            {/* 우측: BOM 상세/비교 */}
            <div className="flex-1">
              {/* 보기모드 선택 */}
              <div className="flex items-center gap-2 mb-4">
                <button
                  onClick={() => setBomViewMode('detail')}
                  className={`px-3 py-1 text-sm rounded ${bomViewMode === 'detail' ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700'
                    }`}
                >
                  BOM 상세
                </button>
                <button
                  onClick={() => setBomViewMode('compare')}
                  className={`px-3 py-1 text-sm rounded ${bomViewMode === 'compare' ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700'
                    }`}
                >
                  부품 비교
                </button>
              </div>

              {selectedBomProduct ? (
                <>
                  {/* BOM 상세 */}
                  {bomViewMode === 'detail' && (
                    <div>
                      <div className="bg-gray-50 p-3 rounded mb-4">
                        <div className="text-sm font-medium">{selectedBomProduct.productName}</div>
                        <div className="text-xs text-gray-500">{selectedBomProduct.productCode}</div>
                        <div className="mt-2 flex gap-4 text-sm">
                          <span>총 원가: <strong>{selectedBomProduct.totalCost?.toLocaleString()}원</strong></span>
                          <span>판매가: <strong>{selectedBomProduct.sellingPrice?.toLocaleString()}원</strong></span>
                          <span className="text-green-600">마진: {((selectedBomProduct.sellingPrice - selectedBomProduct.totalCost) / selectedBomProduct.sellingPrice * 100).toFixed(1)}%</span>
                        </div>
                      </div>
                      <table className="w-full">
                        <thead className="bg-gray-50">
                          <tr>
                            <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">부품코드</th>
                            <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">부품명</th>
                            <th className="px-3 py-2 text-center text-xs font-medium text-gray-500">수량</th>
                            <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">단가</th>
                            <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">금액</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-200">
                          {selectedBomProduct.bom?.map((part, idx) => (
                            <tr key={idx} className="hover:bg-gray-50">
                              <td className="px-3 py-2 text-sm font-mono text-gray-600">{part.partCode}</td>
                              <td className="px-3 py-2 text-sm text-gray-900">{part.partName}</td>
                              <td className="px-3 py-2 text-sm text-center text-gray-600">{part.qty}</td>
                              <td className="px-3 py-2 text-sm text-right text-gray-600">{part.unitPrice?.toLocaleString()}원</td>
                              <td className="px-3 py-2 text-sm text-right font-medium text-gray-900">{(part.qty * part.unitPrice)?.toLocaleString()}원</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  )}

                  {/* 부품 비교 */}
                  {bomViewMode === 'compare' && (
                    <div className="text-sm text-gray-500 text-center py-8">
                      부품별 가격 비교 기능 (구현 예정)
                    </div>
                  )}
                </>
              ) : (
                <div className="text-sm text-gray-500 text-center py-8">
                  좌측에서 제품을 선택하세요
                </div>
              )}
            </div>
          </div>
        )}

        {/* ④ 리포트 탭 */}
        {activeMainTab === 'report' && (
          <div>
            <div className="bg-gray-50 p-4 rounded mb-4">
              <div className="text-sm font-medium text-gray-700 mb-2">
                {priceChangeReport.currentMonth} 대비 {priceChangeReport.previousMonth} 단가 변동 현황
              </div>
              <div className="flex gap-6 text-sm">
                <span className="flex items-center gap-1">
                  <TrendingUp className="w-4 h-4 text-red-500" />
                  상승: <strong className="text-red-600">{priceChangeReport.summary.increased}건</strong>
                </span>
                <span className="flex items-center gap-1">
                  <TrendingDown className="w-4 h-4 text-blue-500" />
                  하락: <strong className="text-blue-600">{priceChangeReport.summary.decreased}건</strong>
                </span>
                <span className="flex items-center gap-1">
                  <span className="w-4 h-4 text-gray-400">-</span>
                  유지: <strong className="text-gray-600">{priceChangeReport.summary.unchanged}건</strong>
                </span>
              </div>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목코드</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">이전단가</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">현재단가</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">변동</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">변동율</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {priceChangeReport.details.map((item, idx) => (
                    <tr key={idx} className="hover:bg-gray-50">
                      <td className="px-4 py-3 text-sm font-mono text-gray-600">{item.itemCode}</td>
                      <td className="px-4 py-3 text-sm text-gray-900">{item.itemName}</td>
                      <td className="px-4 py-3 text-sm text-right text-gray-500">{item.prevPrice?.toLocaleString()}원</td>
                      <td className="px-4 py-3 text-sm text-right font-medium text-gray-900">{item.currPrice?.toLocaleString()}원</td>
                      <td className="px-4 py-3 text-center">
                        {item.changeRate > 0 ? (
                          <TrendingUp className="w-4 h-4 text-red-500 inline" />
                        ) : item.changeRate < 0 ? (
                          <TrendingDown className="w-4 h-4 text-blue-500 inline" />
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <span className={`text-sm font-medium ${item.changeRate > 0 ? 'text-red-600' : item.changeRate < 0 ? 'text-blue-600' : 'text-gray-500'
                          }`}>
                          {item.changeRate > 0 ? '+' : ''}{item.changeRate}%
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>

      {/* 모달 */}
      {showModal && modalMode === 'edit' && selectedItem && (
        <PriceEditModal
          item={selectedItem}
          onClose={() => setShowModal(false)}
          onSave={handleSaveBasePrice}
        />
      )}

      {showModal && modalMode === 'detail' && selectedItem && (
        <PriceDetailModal
          item={selectedItem}
          onClose={() => setShowModal(false)}
          onEdit={() => { setModalMode('edit'); }}
        />
      )}

      {showModal && modalMode === 'customer' && (
        <CustomerPriceModal
          item={selectedItem}
          basePrices={basePrices.filter(p => p.status === '활성')}
          onClose={() => setShowModal(false)}
          onSave={handleSaveCustomerPrice}
        />
      )}
    </div>
  );
};

// 기본단가 수정 모달
const PriceEditModal = ({ item, onClose, onSave }) => {
  const [formData, setFormData] = useState({
    validFrom: item.validFrom || new Date().toISOString().slice(0, 10),
    validTo: item.validTo || '',
    supplier: item.supplier || '',
    purchaseDate: item.purchaseDate || '',
    author: item.author || '',
    purchasePrice: item.purchasePrice || 0,
    unit: item.unit || 'EA',
    lossRate: item.lossRate || 0,
    processingCost: item.processingCost || 0,
    roundingRule: item.roundingRule || '반올림',
    roundingUnit: item.roundingUnit || '1원 단위',
    marginRate: item.marginRate || 0,
    sellingPrice: item.sellingPrice || 0,
    note: item.note || '',
    qtyPricing: item.qtyPricing || [],
  });

  // 수량별 단가 추가
  const addQtyPricing = () => {
    setFormData(prev => ({
      ...prev,
      qtyPricing: [...prev.qtyPricing, { minQty: 1, maxQty: 10, price: prev.sellingPrice }]
    }));
  };

  // 수량별 단가 삭제
  const removeQtyPricing = (idx) => {
    setFormData(prev => ({
      ...prev,
      qtyPricing: prev.qtyPricing.filter((_, i) => i !== idx)
    }));
  };

  // 수량별 단가 수정
  const updateQtyPricing = (idx, field, value) => {
    setFormData(prev => ({
      ...prev,
      qtyPricing: prev.qtyPricing.map((qp, i) => i === idx ? { ...qp, [field]: value } : qp)
    }));
  };

  // 원가 계산
  const subtotal = formData.purchasePrice + formData.processingCost;
  const lossAppliedCost = Math.round(subtotal * (1 + formData.lossRate / 100));

  // 마진 계산
  const margin = formData.sellingPrice - lossAppliedCost;
  const calculatedMarginRate = lossAppliedCost > 0 ? ((margin / lossAppliedCost) * 100) : 0;

  // 마진율로 판매단가 자동 계산
  const handleMarginRateChange = (rate) => {
    const newSellingPrice = Math.round(lossAppliedCost * (1 + rate / 100));
    setFormData(prev => ({
      ...prev,
      marginRate: rate,
      sellingPrice: newSellingPrice,
    }));
  };

  // 판매단가로 마진율 자동 계산
  const handleSellingPriceChange = (price) => {
    const newMarginRate = lossAppliedCost > 0 ? ((price - lossAppliedCost) / lossAppliedCost * 100) : 0;
    setFormData(prev => ({
      ...prev,
      sellingPrice: price,
      marginRate: parseFloat(newMarginRate.toFixed(1)),
    }));
  };

  // 저장
  const handleSave = () => {
    const now = new Date().toISOString().slice(0, 10);
    const historyEntry = item.status === '활성'
      ? { date: now, action: '단가 변경', oldPrice: item.sellingPrice, newPrice: formData.sellingPrice, by: formData.author || '시스템' }
      : { date: now, action: '단가 등록', oldPrice: null, newPrice: formData.sellingPrice, by: formData.author || '시스템' };

    onSave({
      ...item,
      ...formData,
      status: '활성',
      history: [...(item.history || []), historyEntry],
    });
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
        {/* 헤더 */}
        <div className="flex justify-between items-center p-4 border-b sticky top-0 bg-white z-10">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center">
              <DollarSign className="w-4 h-4 text-green-600" />
            </div>
            <h3 className="text-lg font-bold">단가 {item.status === '활성' ? '수정' : '등록'}</h3>
          </div>
          <button onClick={onClose} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
            ✕
          </button>
        </div>

        {/* 품목 정보 */}
        <div className="p-4">
          <div className="bg-blue-50 rounded-lg p-4 border border-blue-100">
            <div className="flex items-center gap-2 mb-3">
              <Package className="w-4 h-4 text-blue-600" />
              <span className="font-medium text-blue-900">품목 정보</span>
            </div>
            <div className="grid grid-cols-4 gap-4 text-sm">
              <div>
                <span className="text-gray-500">품목코드</span>
                <p className="font-mono font-medium mt-1">{item.itemCode}</p>
              </div>
              <div>
                <span className="text-gray-500">품목명</span>
                <p className="font-medium mt-1">{item.itemName}</p>
              </div>
              <div>
                <span className="text-gray-500">품목유형</span>
                <p className="font-medium mt-1">{item.itemType}</p>
              </div>
              <div>
                <span className="text-gray-500">단위</span>
                <p className="font-medium mt-1">{item.unit}</p>
              </div>
            </div>
          </div>
        </div>

        {/* 단가 정보 */}
        <div className="p-4 pt-0 space-y-4">
          {/* 유효기간 */}
          <div className="bg-white rounded-lg border p-4">
            <h4 className="font-medium text-gray-900 mb-3 flex items-center gap-2">
              <Calendar className="w-4 h-4 text-gray-600" /> 유효기간
            </h4>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm text-gray-700 mb-1">
                  시작일 <span className="text-red-500">*</span>
                </label>
                <input
                  type="date"
                  value={formData.validFrom}
                  onChange={(e) => setFormData(prev => ({ ...prev, validFrom: e.target.value }))}
                  className="w-full border rounded-lg px-3 py-2 text-sm"
                />
              </div>
              <div>
                <label className="block text-sm text-gray-700 mb-1">종료일</label>
                <input
                  type="date"
                  value={formData.validTo}
                  onChange={(e) => setFormData(prev => ({ ...prev, validTo: e.target.value }))}
                  className="w-full border rounded-lg px-3 py-2 text-sm"
                  placeholder="무기한"
                />
                <p className="text-xs text-gray-400 mt-1">비워두면 무기한</p>
              </div>
            </div>
          </div>

          {/* 매입 정보 */}
          <div className="bg-white rounded-lg border p-4">
            <h4 className="font-medium text-gray-900 mb-3 flex items-center gap-2">
              <DollarSign className="w-4 h-4 text-gray-600" /> 매입 정보
            </h4>

            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <label className="block text-sm text-gray-700 mb-1">공급업체</label>
                <input
                  type="text"
                  value={formData.supplier}
                  onChange={(e) => setFormData(prev => ({ ...prev, supplier: e.target.value }))}
                  placeholder="공급업체명"
                  className="w-full border rounded-lg px-3 py-2 text-sm"
                />
              </div>
              <div>
                <label className="block text-sm text-gray-700 mb-1">작성자</label>
                <input
                  type="text"
                  value={formData.author}
                  onChange={(e) => setFormData(prev => ({ ...prev, author: e.target.value }))}
                  placeholder="작성자명"
                  className="w-full border rounded-lg px-3 py-2 text-sm"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <label className="block text-sm text-gray-700 mb-1">
                  입고가 <span className="text-red-500">*</span>
                </label>
                <div className="flex items-center gap-2">
                  <input
                    type="number"
                    value={formData.purchasePrice}
                    onChange={(e) => setFormData(prev => ({ ...prev, purchasePrice: parseInt(e.target.value) || 0 }))}
                    className="flex-1 border rounded-lg px-3 py-2 text-sm text-right"
                  />
                  <span className="text-sm text-gray-500">원</span>
                </div>
              </div>
              <div>
                <label className="block text-sm text-gray-700 mb-1">가공비</label>
                <div className="flex items-center gap-2">
                  <input
                    type="number"
                    value={formData.processingCost}
                    onChange={(e) => setFormData(prev => ({ ...prev, processingCost: parseInt(e.target.value) || 0 }))}
                    className="flex-1 border rounded-lg px-3 py-2 text-sm text-right"
                  />
                  <span className="text-sm text-gray-500">원</span>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm text-gray-700 mb-1">LOSS (%)</label>
                <div className="flex items-center gap-2">
                  <input
                    type="number"
                    value={formData.lossRate}
                    onChange={(e) => setFormData(prev => ({ ...prev, lossRate: parseFloat(e.target.value) || 0 }))}
                    className="flex-1 border rounded-lg px-3 py-2 text-sm text-right"
                    step="0.1"
                  />
                  <span className="text-sm text-gray-500">%</span>
                </div>
                <p className="text-xs text-gray-400 mt-1">제조 손실율</p>
              </div>
              <div>
                <label className="block text-sm text-gray-700 mb-1">반올림 단위</label>
                <select
                  value={formData.roundingUnit}
                  onChange={(e) => setFormData(prev => ({ ...prev, roundingUnit: e.target.value }))}
                  className="w-full border rounded-lg px-3 py-2 text-sm"
                >
                  <option value="1원 단위">1원 단위</option>
                  <option value="10원 단위">10원 단위</option>
                  <option value="100원 단위">100원 단위</option>
                </select>
              </div>
            </div>

            {/* 원가 계산 */}
            <div className="bg-blue-50 rounded-lg p-3 mt-4 border border-blue-100">
              <div className="flex items-center gap-2 mb-2">
                <Clipboard className="w-4 h-4 text-blue-600" />
                <span className="font-medium text-blue-900 text-sm">원가 계산</span>
              </div>
              <div className="grid grid-cols-4 gap-2 text-sm">
                <div className="text-center">
                  <span className="text-gray-500 text-xs">입고가</span>
                  <p className="font-medium">{formData.purchasePrice.toLocaleString()}원</p>
                </div>
                <div className="text-center">
                  <span className="text-gray-500 text-xs">+ 가공비</span>
                  <p className="font-medium">{formData.processingCost.toLocaleString()}원</p>
                </div>
                <div className="text-center">
                  <span className="text-gray-500 text-xs">= 소계</span>
                  <p className="font-medium">{subtotal.toLocaleString()}원</p>
                </div>
                <div className="text-center bg-blue-100 rounded p-1">
                  <span className="text-blue-700 text-xs">LOSS 적용</span>
                  <p className="font-bold text-blue-700">{lossAppliedCost.toLocaleString()}원</p>
                </div>
              </div>
            </div>
          </div>

          {/* 판매 정보 */}
          <div className="bg-white rounded-lg border p-4">
            <h4 className="font-medium text-gray-900 mb-3 flex items-center gap-2">
              <BarChart3 className="w-4 h-4 text-gray-600" /> 판매 정보
            </h4>

            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <label className="block text-sm text-gray-700 mb-1">마진율 (%)</label>
                <div className="flex items-center gap-2">
                  <input
                    type="number"
                    value={formData.marginRate}
                    onChange={(e) => handleMarginRateChange(parseFloat(e.target.value) || 0)}
                    className="flex-1 border rounded-lg px-3 py-2 text-sm text-right"
                    step="0.1"
                  />
                  <span className="text-sm text-gray-500">%</span>
                </div>
                <p className="text-xs text-gray-400 mt-1">입력 시 판매단가 자동 계산</p>
              </div>
              <div>
                <label className="block text-sm text-gray-700 mb-1">
                  판매단가 <span className="text-red-500">*</span>
                </label>
                <div className="flex items-center gap-2">
                  <input
                    type="number"
                    value={formData.sellingPrice}
                    onChange={(e) => handleSellingPriceChange(parseInt(e.target.value) || 0)}
                    className="flex-1 border rounded-lg px-3 py-2 text-sm text-right"
                  />
                  <span className="text-sm text-gray-500">원</span>
                </div>
                <p className="text-xs text-gray-400 mt-1">입력 시 마진율 자동 계산</p>
              </div>
            </div>

            {/* 마진 계산 */}
            <div className="bg-green-50 rounded-lg p-3 border border-green-100">
              <div className="flex justify-between items-center">
                <span className="text-sm text-green-800">마진</span>
                <span className="font-bold text-green-700">
                  {margin.toLocaleString()}원 ({calculatedMarginRate.toFixed(1)}%)
                </span>
              </div>
            </div>
          </div>

          {/* 수량별 단가 */}
          <div className="bg-white rounded-lg border p-4">
            <div className="flex justify-between items-center mb-3">
              <h4 className="font-medium text-gray-900 flex items-center gap-2">
                <Layers className="w-4 h-4 text-gray-600" /> 수량별 단가 (물량 할인)
              </h4>
              <button
                onClick={addQtyPricing}
                className="text-sm text-blue-600 hover:text-blue-700 flex items-center gap-1"
              >
                <Plus className="w-4 h-4" /> 추가
              </button>
            </div>

            {formData.qtyPricing.length === 0 ? (
              <p className="text-sm text-gray-500 text-center py-4">
                수량별 단가가 없습니다. 기본 판매단가가 적용됩니다.
              </p>
            ) : (
              <div className="space-y-2">
                {formData.qtyPricing.map((qp, idx) => (
                  <div key={idx} className="flex items-center gap-2 bg-gray-50 rounded-lg p-2">
                    <input
                      type="number"
                      value={qp.minQty}
                      onChange={(e) => updateQtyPricing(idx, 'minQty', parseInt(e.target.value) || 0)}
                      className="w-20 border rounded px-2 py-1 text-sm text-right"
                    />
                    <span className="text-gray-500">~</span>
                    <input
                      type="number"
                      value={qp.maxQty}
                      onChange={(e) => updateQtyPricing(idx, 'maxQty', parseInt(e.target.value) || 0)}
                      className="w-20 border rounded px-2 py-1 text-sm text-right"
                    />
                    <span className="text-gray-500">개</span>
                    <span className="text-gray-400 mx-2">→</span>
                    <input
                      type="number"
                      value={qp.price}
                      onChange={(e) => updateQtyPricing(idx, 'price', parseInt(e.target.value) || 0)}
                      className="w-28 border rounded px-2 py-1 text-sm text-right"
                    />
                    <span className="text-gray-500">원</span>
                    <button
                      onClick={() => removeQtyPricing(idx)}
                      className="p-1 hover:bg-red-100 rounded ml-auto"
                    >
                      <Trash2 className="w-4 h-4 text-red-400" />
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 비고 */}
          <div className="bg-white rounded-lg border p-4">
            <label className="block text-sm text-gray-700 mb-1">비고</label>
            <textarea
              value={formData.note}
              onChange={(e) => setFormData(prev => ({ ...prev, note: e.target.value }))}
              placeholder="비고 사항"
              rows={2}
              className="w-full border rounded-lg px-3 py-2 text-sm"
            />
          </div>
        </div>

        {/* 푸터 */}
        <div className="flex justify-end gap-2 p-4 border-t bg-gray-50 sticky bottom-0">
          <button
            onClick={onClose}
            className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            취소
          </button>
          <button
            onClick={handleSave}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
          >
            <Check className="w-4 h-4" /> 저장
          </button>
        </div>
      </div>
    </div>
  );
};

// 기본단가 상세보기 모달 (이력 포함)
const PriceDetailModal = ({ item, onClose, onEdit }) => {
  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        {/* 헤더 */}
        <div className="flex justify-between items-center p-4 border-b sticky top-0 bg-white">
          <h3 className="text-lg font-bold">단가 상세</h3>
          <button onClick={onClose} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
            ✕
          </button>
        </div>

        <div className="p-4 space-y-4">
          {/* 품목 정보 */}
          <div className="bg-blue-50 rounded-lg p-4 border border-blue-100">
            <div className="grid grid-cols-4 gap-4 text-sm">
              <div>
                <span className="text-gray-500">품목코드</span>
                <p className="font-mono font-medium mt-1">{item.itemCode}</p>
              </div>
              <div>
                <span className="text-gray-500">품목명</span>
                <p className="font-medium mt-1">{item.itemName}</p>
              </div>
              <div>
                <span className="text-gray-500">품목유형</span>
                <p className="font-medium mt-1">{item.itemType}</p>
              </div>
              <div>
                <span className="text-gray-500">공급업체</span>
                <p className="font-medium mt-1">{item.supplier || '-'}</p>
              </div>
            </div>
          </div>

          {/* 가격 정보 */}
          <div className="grid grid-cols-4 gap-3">
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <span className="text-xs text-gray-500">입고가</span>
              <p className="font-bold text-gray-900">{item.purchasePrice?.toLocaleString()}원</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center">
              <span className="text-xs text-gray-500">가공비</span>
              <p className="font-bold text-gray-900">{item.processingCost?.toLocaleString()}원</p>
            </div>
            <div className="bg-blue-50 rounded-lg p-3 text-center">
              <span className="text-xs text-blue-600">판매단가</span>
              <p className="font-bold text-blue-600">{item.sellingPrice?.toLocaleString()}원</p>
            </div>
            <div className="bg-green-50 rounded-lg p-3 text-center">
              <span className="text-xs text-green-600">마진율</span>
              <p className="font-bold text-green-600">{item.marginRate?.toFixed(1)}%</p>
            </div>
          </div>

          {/* 유효기간 */}
          <div className="bg-gray-50 rounded-lg p-3">
            <span className="text-xs text-gray-500">유효기간</span>
            <p className="font-medium">{item.validFrom} ~ {item.validTo || '무기한'}</p>
          </div>

          {/* 수량별 단가 */}
          {item.qtyPricing?.length > 0 && (
            <div className="bg-white rounded-lg border p-4">
              <h4 className="font-medium text-gray-900 mb-3">수량별 단가</h4>
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-3 py-2 text-left">수량 범위</th>
                    <th className="px-3 py-2 text-right">적용단가</th>
                    <th className="px-3 py-2 text-right">할인율</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {item.qtyPricing.map((qp, idx) => (
                    <tr key={idx}>
                      <td className="px-3 py-2">{qp.minQty} ~ {qp.maxQty}개</td>
                      <td className="px-3 py-2 text-right font-medium">{qp.price.toLocaleString()}원</td>
                      <td className="px-3 py-2 text-right text-red-600">
                        -{((item.sellingPrice - qp.price) / item.sellingPrice * 100).toFixed(1)}%
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {/* 변경 이력 */}
          <div className="bg-white rounded-lg border p-4">
            <h4 className="font-medium text-gray-900 mb-3 flex items-center gap-2">
              <Clock className="w-4 h-4" /> 단가 변경 이력
            </h4>
            {item.history?.length > 0 ? (
              <div className="space-y-2">
                {item.history.map((h, idx) => (
                  <div key={idx} className="flex items-start gap-3 p-2 bg-gray-50 rounded">
                    <div className="w-2 h-2 mt-2 rounded-full bg-blue-500" />
                    <div className="flex-1">
                      <div className="flex justify-between">
                        <span className="font-medium text-sm">{h.action}</span>
                        <span className="text-xs text-gray-500">{h.date}</span>
                      </div>
                      {h.oldPrice !== null && (
                        <p className="text-sm text-gray-600">
                          {h.oldPrice?.toLocaleString()}원 → {h.newPrice?.toLocaleString()}원
                        </p>
                      )}
                      {h.oldPrice === null && (
                        <p className="text-sm text-gray-600">{h.newPrice?.toLocaleString()}원</p>
                      )}
                      <p className="text-xs text-gray-400">{h.by}</p>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-sm text-gray-500 text-center py-4">변경 이력이 없습니다.</p>
            )}
          </div>
        </div>

        {/* 푸터 */}
        <div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
          <button
            onClick={onClose}
            className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            닫기
          </button>
          <button
            onClick={onEdit}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
          >
            <Edit3 className="w-4 h-4" /> 수정
          </button>
        </div>
      </div>
    </div>
  );
};

// 거래처별 단가 등록/수정 모달
const CustomerPriceModal = ({ item, basePrices, onClose, onSave }) => {
  const [formData, setFormData] = useState({
    id: item?.id || null,
    customerId: item?.customerId || '',
    customerName: item?.customerName || '',
    itemCode: item?.itemCode || '',
    itemName: item?.itemName || '',
    unit: item?.unit || 'EA',
    basePrice: item?.basePrice || 0,
    discountType: item?.discountType || 'rate', // rate 또는 fixed
    discountRate: item?.discountRate || 0,
    discountAmount: item?.discountAmount || 0,
    sellingPrice: item?.sellingPrice || 0,
    validFrom: item?.validFrom || new Date().toISOString().slice(0, 10),
    validTo: item?.validTo || '',
    note: item?.note || '',
  });

  // 품목 선택 시
  const handleItemSelect = (itemCode) => {
    const selected = basePrices.find(p => p.itemCode === itemCode);
    if (selected) {
      setFormData(prev => ({
        ...prev,
        itemCode: selected.itemCode,
        itemName: selected.itemName,
        unit: selected.unit,
        basePrice: selected.sellingPrice,
        sellingPrice: selected.sellingPrice,
      }));
    }
  };

  // 할인율 변경 시
  const handleDiscountRateChange = (rate) => {
    const newPrice = Math.round(formData.basePrice * (1 - rate / 100));
    setFormData(prev => ({
      ...prev,
      discountRate: rate,
      sellingPrice: newPrice,
    }));
  };

  // 적용단가 직접 변경 시
  const handleSellingPriceChange = (price) => {
    const newRate = formData.basePrice > 0 ? ((formData.basePrice - price) / formData.basePrice * 100) : 0;
    setFormData(prev => ({
      ...prev,
      sellingPrice: price,
      discountRate: parseFloat(newRate.toFixed(1)),
    }));
  };

  // 저장
  const handleSave = () => {
    onSave({
      ...formData,
      status: '활성',
    });
  };

  // 샘플 거래처 목록
  const customers = [
    { id: 'C001', name: '삼성전자' },
    { id: 'C002', name: 'LG전자' },
    { id: 'C003', name: '현대건설' },
    { id: 'C004', name: 'SK하이닉스' },
    { id: 'C005', name: '포스코' },
  ];

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-xl max-h-[90vh] overflow-y-auto">
        {/* 헤더 */}
        <div className="flex justify-between items-center p-4 border-b sticky top-0 bg-white">
          <h3 className="text-lg font-bold">
            거래처별 단가 {item ? '수정' : '등록'}
          </h3>
          <button onClick={onClose} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
            ✕
          </button>
        </div>

        <div className="p-4 space-y-4">
          {/* 거래처 선택 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              거래처 <span className="text-red-500">*</span>
            </label>
            <select
              value={formData.customerId}
              onChange={(e) => {
                const selected = customers.find(c => c.id === e.target.value);
                setFormData(prev => ({
                  ...prev,
                  customerId: e.target.value,
                  customerName: selected?.name || '',
                }));
              }}
              className="w-full border rounded-lg px-3 py-2 text-sm"
            >
              <option value="">거래처 선택</option>
              {customers.map(c => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
          </div>

          {/* 품목 선택 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              품목 <span className="text-red-500">*</span>
            </label>
            <select
              value={formData.itemCode}
              onChange={(e) => handleItemSelect(e.target.value)}
              className="w-full border rounded-lg px-3 py-2 text-sm"
            >
              <option value="">품목 선택</option>
              {basePrices.map(p => (
                <option key={p.itemCode} value={p.itemCode}>
                  {p.itemCode} - {p.itemName} ({p.sellingPrice?.toLocaleString()}원)
                </option>
              ))}
            </select>
          </div>

          {/* 기본단가 표시 */}
          {formData.basePrice > 0 && (
            <div className="bg-gray-50 rounded-lg p-3">
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-600">기본 판매단가</span>
                <span className="font-bold text-gray-900">{formData.basePrice.toLocaleString()}원</span>
              </div>
            </div>
          )}

          {/* 할인 설정 */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">할인율 (%)</label>
              <div className="flex items-center gap-2">
                <input
                  type="number"
                  value={formData.discountRate}
                  onChange={(e) => handleDiscountRateChange(parseFloat(e.target.value) || 0)}
                  className="flex-1 border rounded-lg px-3 py-2 text-sm text-right"
                  step="0.1"
                />
                <span className="text-sm text-gray-500">%</span>
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                적용단가 <span className="text-red-500">*</span>
              </label>
              <div className="flex items-center gap-2">
                <input
                  type="number"
                  value={formData.sellingPrice}
                  onChange={(e) => handleSellingPriceChange(parseInt(e.target.value) || 0)}
                  className="flex-1 border rounded-lg px-3 py-2 text-sm text-right"
                />
                <span className="text-sm text-gray-500">원</span>
              </div>
            </div>
          </div>

          {/* 할인 금액 표시 */}
          {formData.basePrice > 0 && formData.discountRate > 0 && (
            <div className="bg-red-50 rounded-lg p-3 border border-red-100">
              <div className="flex justify-between items-center">
                <span className="text-sm text-red-700">할인 금액</span>
                <span className="font-bold text-red-600">
                  -{(formData.basePrice - formData.sellingPrice).toLocaleString()}원
                </span>
              </div>
            </div>
          )}

          {/* 유효기간 */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                시작일 <span className="text-red-500">*</span>
              </label>
              <input
                type="date"
                value={formData.validFrom}
                onChange={(e) => setFormData(prev => ({ ...prev, validFrom: e.target.value }))}
                className="w-full border rounded-lg px-3 py-2 text-sm"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">종료일</label>
              <input
                type="date"
                value={formData.validTo}
                onChange={(e) => setFormData(prev => ({ ...prev, validTo: e.target.value }))}
                className="w-full border rounded-lg px-3 py-2 text-sm"
              />
              <p className="text-xs text-gray-400 mt-1">비워두면 무기한</p>
            </div>
          </div>

          {/* 비고 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
            <textarea
              value={formData.note}
              onChange={(e) => setFormData(prev => ({ ...prev, note: e.target.value }))}
              placeholder="계약 조건, 특이사항 등"
              rows={2}
              className="w-full border rounded-lg px-3 py-2 text-sm"
            />
          </div>
        </div>

        {/* 푸터 */}
        <div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
          <button
            onClick={onClose}
            className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            취소
          </button>
          <button
            onClick={handleSave}
            disabled={!formData.customerId || !formData.itemCode}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2"
          >
            <Check className="w-4 h-4" /> 저장
          </button>
        </div>
      </div>
    </div>
  );
};

// 이전 패널 컴포넌트들 (하위 호환용)
const PriceDetailPanel = ({ price, onEdit, onClose }) => null;
const PriceFormPanel = ({ formData, setFormData, onSave, onCancel, isEdit }) => null;

// 견적 목록
const QuoteList = ({ quotes = sampleQuotesData, onNavigate, onCreateOrder, onUpdateQuote, onDeleteQuotes }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');

  // 체크박스 선택 상태
  const [selectedIds, setSelectedIds] = useState([]);
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  // 수주전환 모달 상태
  const [showConvertModal, setShowConvertModal] = useState(false);
  const [selectedQuote, setSelectedQuote] = useState(null);
  const [convertForm, setConvertForm] = useState({
    shipDate: '',
    shipDateUndecided: false,
    dueDate: '',
    dueDateUndecided: false,
    deliveryMethod: '상차',
    freightCost: '선불',
    receiverName: '',
    receiverPhone: '',
    postalCode: '',
    deliveryAddress: '',
    deliveryAddressDetail: '',
    note: '',
  });

  // 배송방식 옵션 (선불/착불 구분)
  const deliveryMethodOptions = [
    { id: 'pickup-prepaid', label: '상차(선불)', category: '상차' },
    { id: 'pickup-collect', label: '상차(착불)', category: '상차' },
    { id: 'direct', label: '직접배차', category: '직접' },
    { id: 'self', label: '직접수령', category: '직접' },
    { id: 'kyungdong-prepaid', label: '경동화물(선불)', category: '화물' },
    { id: 'kyungdong-collect', label: '경동화물(착불)', category: '화물' },
    { id: 'kyungdong-parcel-prepaid', label: '경동택배(선불)', category: '택배' },
    { id: 'kyungdong-parcel-collect', label: '경동택배(착불)', category: '택배' },
    { id: 'daesin-prepaid', label: '대신화물(선불)', category: '화물' },
    { id: 'daesin-collect', label: '대신화물(착불)', category: '화물' },
    { id: 'daesin-parcel-prepaid', label: '대신택배(선불)', category: '택배' },
    { id: 'daesin-parcel-collect', label: '대신택배(착불)', category: '택배' },
  ];

  const getStatusCount = (status) => {
    if (status === 'all') return quotes.length;
    if (status === 'editing') return quotes.filter(q => q.status.includes('수정')).length;
    return quotes.filter(q => q.status === status).length;
  };

  const tabs = [
    { id: 'all', label: '전체', count: getStatusCount('all') },
    { id: '최초작성', label: '최초작성', count: getStatusCount('최초작성') },
    { id: 'editing', label: '수정중', count: getStatusCount('editing') },
    { id: '최종확정', label: '최종확정', count: getStatusCount('최종확정') },
    { id: '수주전환', label: '수주전환', count: getStatusCount('수주전환') },
  ];

  const statusFilter = {
    all: () => true,
    '최초작성': (q) => q.status === '최초작성',
    editing: (q) => q.status.includes('수정'),
    '최종확정': (q) => q.status === '최종확정',
    '수주전환': (q) => q.status === '수주전환',
  };

  const filtered = quotes
    .filter(statusFilter[activeTab])
    .filter(q =>
      q.quoteNo.toLowerCase().includes(search.toLowerCase()) ||
      q.customerName.includes(search) ||
      q.siteName.includes(search) ||
      q.productName.includes(search)
    )
    .sort((a, b) => b.id - a.id); // ID 기준 내림차순 (최신 등록 최상단)

  // 전체 선택/해제
  const handleSelectAll = (e) => {
    if (e.target.checked) {
      setSelectedIds(filtered.map(q => q.id));
    } else {
      setSelectedIds([]);
    }
  };

  // 개별 선택
  const handleSelectOne = (id, e) => {
    e.stopPropagation();
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  };

  // 삭제 확인
  const handleDeleteConfirm = () => {
    if (onDeleteQuotes && selectedIds.length > 0) {
      onDeleteQuotes(selectedIds);
    }
    setSelectedIds([]);
    setShowDeleteModal(false);
  };

  // 통계 계산
  const thisMonthQuotes = quotes.filter(q => {
    const date = new Date(q.quoteDate);
    const now = new Date();
    return date.getMonth() === now.getMonth() && date.getFullYear() === now.getFullYear();
  });

  const thisMonthAmount = thisMonthQuotes.reduce((sum, q) => sum + q.totalAmount, 0);
  const progressAmount = quotes.filter(q => !['최종확정', '수주전환'].includes(q.status))
    .reduce((sum, q) => sum + q.totalAmount, 0);
  const thisWeekNew = quotes.filter(q => {
    const date = new Date(q.quoteDate);
    const now = new Date();
    const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
    return date >= weekAgo;
  }).length;
  const conversionRate = quotes.length > 0
    ? ((quotes.filter(q => q.status === '수주전환').length / quotes.length) * 100).toFixed(1)
    : 0;

  // 수주전환 모달 열기
  const handleOpenConvertModal = (quote, e) => {
    e?.stopPropagation();
    setSelectedQuote(quote);
    // 견적 정보로 기본값 설정
    setConvertForm({
      shipDate: '',
      shipDateUndecided: false,
      dueDate: '',
      dueDateUndecided: false,
      deliveryMethod: '상차',
      freightCost: '선불',
      receiverName: '',
      receiverPhone: '010-0000-0000',
      postalCode: '',
      deliveryAddress: '',
      deliveryAddressDetail: '',
      note: '',
    });
    setShowConvertModal(true);
  };

  // 수주전환 실행 - 실제 수주 데이터 생성
  const handleConvertToOrder = () => {
    if (!selectedQuote) return;

    // 수주번호 생성 - 채번관리 규칙 적용 (제품유형에 따라 스크린/슬랫/절곡 구분)
    const productType = selectedQuote.productType || selectedQuote.productName || '';
    const newOrderNo = generateNumber('수주번호', productType, []);

    // 새 수주 데이터 생성
    const newOrder = {
      id: Date.now(),
      orderNo: newOrderNo,
      quoteNo: selectedQuote.quoteNo,
      orderDate: new Date().toISOString().split('T')[0],
      customerName: selectedQuote.customerName,
      siteName: selectedQuote.siteName,
      siteAddress: selectedQuote.siteAddress || convertForm.deliveryAddress,
      manager: selectedQuote.manager,
      contact: selectedQuote.contact,
      productName: selectedQuote.productName,
      qty: selectedQuote.qty,
      totalAmount: selectedQuote.finalAmount || selectedQuote.totalAmount,
      status: '수주등록',
      dueDate: convertForm.dueDateUndecided ? '미정' : convertForm.dueDate,
      shipDate: convertForm.shipDateUndecided ? '미정' : convertForm.shipDate,
      deliveryMethod: convertForm.deliveryMethod,
      freightCost: convertForm.freightCost,
      receiverName: convertForm.receiverName,
      receiverPhone: convertForm.receiverPhone,
      deliveryAddress: convertForm.deliveryAddress,
      deliveryAddressDetail: convertForm.deliveryAddressDetail,
      note: convertForm.note,
      creditGrade: selectedQuote.creditGrade,
      items: selectedQuote.items || [],
      calculatedItems: selectedQuote.calculatedItems || [],
      bomData: selectedQuote.bomData || {},
      splits: [],
      history: [{
        id: Date.now(),
        changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
        changeType: '수주등록',
        description: `견적(${selectedQuote.quoteNo})에서 수주전환`,
        changedBy: '현재 사용자',
      }],
    };

    // 수주 생성 콜백 호출
    if (onCreateOrder) {
      onCreateOrder(newOrder);
    }

    // 견적 상태 업데이트
    if (onUpdateQuote) {
      onUpdateQuote({
        ...selectedQuote,
        status: '수주전환',
        convertedOrderNo: newOrderNo,
      });
    }

    alert(`수주전환 완료!\n\n수주번호: ${newOrderNo}\n발주처: ${selectedQuote.customerName}\n현장: ${selectedQuote.siteName}\n금액: ${(selectedQuote.finalAmount || selectedQuote.totalAmount).toLocaleString()}원`);

    setShowConvertModal(false);
    setSelectedQuote(null);

    // 수주 목록으로 이동
    onNavigate('orders');
  };

  // 신용등급 배지
  const CreditGradeBadge = ({ grade }) => {
    const colors = {
      'A': 'bg-green-100 text-green-700',
      'B': 'bg-yellow-100 text-yellow-700',
      'C': 'bg-red-100 text-red-700',
    };
    const labels = { 'A': '우량', 'B': '관리', 'C': '위험' };
    return (
      <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium ${colors[grade] || 'bg-gray-100 text-gray-700'}`}>
        {grade}{labels[grade] ? `(${labels[grade]})` : ''}
      </span>
    );
  };

  return (
    <div className="space-y-6">
      <PageHeader
        icon={FileText}
        title="견적 목록"
        actions={
          <Button variant="primary" onClick={() => onNavigate('quote-create')}>
            <Plus className="w-4 h-4" /> 견적 등록
          </Button>
        }
      />

      {/* 리포트 카드 (4개, 한 줄) */}
      <div className="grid grid-cols-4 gap-4">
        <DashboardCard
          icon={Calendar}
          title="이번 달 견적 금액"
          value={`${thisMonthAmount.toLocaleString()}원`}
          color="blue"
        />
        <DashboardCard
          icon={FileText}
          title="진행중 견적 금액"
          value={`${progressAmount.toLocaleString()}원`}
          color="orange"
        />
        <DashboardCard
          icon={Edit}
          title="이번 주 신규 견적"
          value={thisWeekNew.toString()}
          color="green"
        />
        <DashboardCard
          icon={CheckCircle}
          title="이번 달 수주 전환율"
          value={`${conversionRate}%`}
          color="purple"
        />
      </div>

      {/* 검색 */}
      <SearchInput
        placeholder="견적번호, 발주처, 담당자, 제품명, 현장코드, 현장명 검색..."
        value={search}
        onChange={setSearch}
      />

      <TabFilter tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />

      {/* 테이블 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        {/* 선택 삭제 버튼 (2개 이상 선택 시) */}
        {selectedIds.length >= 2 && (
          <div className="px-4 py-3 bg-gray-50 border-b flex items-center justify-between">
            <span className="text-sm text-gray-600">
              {selectedIds.length}개 항목 선택됨
            </span>
            <button
              onClick={() => setShowDeleteModal(true)}
              className="px-4 py-2 bg-red-600 text-white text-sm rounded-lg hover:bg-red-700 flex items-center gap-2"
            >
              <Trash2 className="w-4 h-4" />
              선택 삭제({selectedIds.length})
            </button>
          </div>
        )}
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-3 py-3 text-center text-xs font-medium text-gray-500 w-12">
                <input
                  type="checkbox"
                  className="rounded"
                  checked={filtered.length > 0 && selectedIds.length === filtered.length}
                  onChange={handleSelectAll}
                />
              </th>
              <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 w-16">번호</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">견적번호</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">접수일</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">상태</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">제품명</th>
              <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">수량</th>
              <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">금액</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">발주처</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">현장명</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">담당자</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">비고</th>
              {/* 작업 컬럼 (1개 이상 선택 시에만 헤더 표시) */}
              {selectedIds.length >= 1 && (
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500 w-24">작업</th>
              )}
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map((quote, index) => {
              const isSelected = selectedIds.includes(quote.id);
              const rowNumber = filtered.length - index;
              return (
                <tr
                  key={quote.id}
                  className={`hover:bg-gray-50 cursor-pointer ${isSelected ? 'bg-blue-50' : ''}`}
                  onClick={() => onNavigate('quote-detail', quote)}
                >
                  <td className="px-3 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                    <input
                      type="checkbox"
                      className="rounded"
                      checked={isSelected}
                      onChange={(e) => handleSelectOne(quote.id, e)}
                    />
                  </td>
                  <td className="px-4 py-3 text-center text-sm text-gray-900">{rowNumber}</td>
                  <td className="px-4 py-3">
                    <div className="text-sm font-mono text-blue-600">{quote.quoteNo}</div>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-900">{quote.quoteDate}</td>
                  <td className="px-4 py-3"><StatusBadge status={quote.status} /></td>
                  <td className="px-4 py-3 text-sm text-gray-900">{quote.productName}</td>
                  <td className="px-4 py-3 text-right text-sm text-gray-900">{quote.qty}</td>
                  <td className="px-4 py-3 text-right">
                    <div className="text-sm font-medium text-gray-900">
                      {((quote.finalAmount || quote.totalAmount) / 10000).toLocaleString()}만원
                    </div>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-900">{quote.customerName}</td>
                  <td className="px-4 py-3">
                    <div className="text-sm text-gray-900">{quote.siteName}</div>
                    {quote.siteCode && <div className="text-xs text-gray-400 font-mono">{quote.siteCode}</div>}
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-900">{quote.manager}</td>
                  <td className="px-4 py-3 text-sm text-gray-500">{quote.note || '-'}</td>
                  {/* 작업 컬럼 (1개 이상 선택된 경우에만 표시) */}
                  {selectedIds.length >= 1 && (
                    <td className="px-3 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                      {isSelected && (
                        <div className="flex items-center justify-center gap-1">
                          <button
                            onClick={() => onNavigate('quote-edit', quote)}
                            className="p-1.5 text-blue-600 hover:bg-blue-50 rounded transition-colors"
                            title="수정"
                          >
                            <Edit2 className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => setShowDeleteModal(true)}
                            className="p-1.5 text-red-600 hover:bg-red-50 rounded transition-colors"
                            title="삭제"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      )}
                    </td>
                  )}
                </tr>
              );
            })}
          </tbody>
        </table>

        {filtered.length === 0 && (
          <div className="text-center py-12 text-gray-500">
            검색 결과가 없습니다.
          </div>
        )}
      </div>

      {/* 수주전환 모달 (스크린샷 형태) */}
      {showConvertModal && selectedQuote && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg mx-4">
            {/* 모달 헤더 */}
            <div className="flex items-center justify-between p-4 border-b">
              <div>
                <h3 className="text-lg font-bold text-gray-900">수주전환</h3>
                <p className="text-sm text-gray-500">배송 정보를 입력하여 수주로 전환합니다</p>
              </div>
              <button
                onClick={() => setShowConvertModal(false)}
                className="p-2 hover:bg-gray-100 rounded-full transition-colors"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            {/* 모달 본문 - 배송 정보 입력 */}
            <div className="p-5 space-y-4 max-h-[70vh] overflow-y-auto">
              {/* 출고예정일 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    출고예정일 <span className="text-red-500">*</span>
                  </label>
                  <div className="flex items-center gap-2">
                    <input
                      type="date"
                      className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm disabled:bg-gray-100"
                      value={convertForm.shipDate}
                      onChange={(e) => setConvertForm({ ...convertForm, shipDate: e.target.value })}
                      placeholder="연도 - 월 - 일"
                      disabled={convertForm.shipDateUndecided}
                    />
                    <label className="flex items-center gap-1.5 text-sm text-gray-600 whitespace-nowrap">
                      <input
                        type="checkbox"
                        checked={convertForm.shipDateUndecided}
                        onChange={(e) => setConvertForm({ ...convertForm, shipDateUndecided: e.target.checked })}
                        className="w-4 h-4 rounded border-gray-300"
                      />
                      미정
                    </label>
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">발주처</label>
                  <p className="text-sm text-gray-900 py-2">{selectedQuote.customerName}</p>
                </div>
              </div>

              {/* 납품요청일 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    납품요청일 <span className="text-red-500">*</span>
                  </label>
                  <div className="flex items-center gap-2">
                    <input
                      type="date"
                      className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm disabled:bg-gray-100"
                      value={convertForm.dueDate}
                      onChange={(e) => setConvertForm({ ...convertForm, dueDate: e.target.value })}
                      placeholder="연도 - 월 - 일"
                      disabled={convertForm.dueDateUndecided}
                    />
                    <label className="flex items-center gap-1.5 text-sm text-gray-600 whitespace-nowrap">
                      <input
                        type="checkbox"
                        checked={convertForm.dueDateUndecided}
                        onChange={(e) => setConvertForm({ ...convertForm, dueDateUndecided: e.target.checked })}
                        className="w-4 h-4 rounded border-gray-300"
                      />
                      미정
                    </label>
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">현장명</label>
                  <p className="text-sm text-gray-900 py-2">{selectedQuote.siteName}</p>
                </div>
              </div>

              {/* 배송방식 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">배송방식</label>
                <select
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                  value={convertForm.deliveryMethod}
                  onChange={(e) => setConvertForm({ ...convertForm, deliveryMethod: e.target.value })}
                >
                  <option value="상차">상차</option>
                  <option value="직접배차">직접배차</option>
                  <option value="직접수령">직접수령</option>
                  <option value="경동화물">경동화물</option>
                  <option value="경동택배">경동택배</option>
                  <option value="대신화물">대신화물</option>
                  <option value="대신택배">대신택배</option>
                </select>
              </div>

              {/* 운임비용 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">운임비용</label>
                <select
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                  value={convertForm.freightCost}
                  onChange={(e) => setConvertForm({ ...convertForm, freightCost: e.target.value })}
                >
                  <option value="선불">선불</option>
                  <option value="착불">착불</option>
                </select>
              </div>

              {/* 수신(반장/업체) */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  수신(반장/업체) <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                  placeholder="수신(반장/업체) 이름"
                  value={convertForm.receiverName}
                  onChange={(e) => setConvertForm({ ...convertForm, receiverName: e.target.value })}
                />
              </div>

              {/* 수신처 연락처 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  수신처 연락처 <span className="text-red-500">*</span>
                </label>
                <input
                  type="tel"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                  placeholder="010-0000-0000"
                  value={convertForm.receiverPhone}
                  onChange={(e) => setConvertForm({ ...convertForm, receiverPhone: e.target.value })}
                />
              </div>

              {/* 수신처 주소 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  수신처 주소 <span className="text-red-500">*</span>
                </label>
                <div className="flex gap-2 mb-2">
                  <input
                    type="text"
                    className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm"
                    placeholder="우편번호"
                    value={convertForm.postalCode}
                    onChange={(e) => setConvertForm({ ...convertForm, postalCode: e.target.value })}
                  />
                  <button
                    type="button"
                    className="px-4 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm hover:bg-gray-200 flex items-center gap-1"
                  >
                    <Search className="w-4 h-4" />
                    우편번호 찾기
                  </button>
                </div>
                <input
                  type="text"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm mb-2"
                  placeholder="기본 주소 (우편번호 검색 후 자동 입력됩니다)"
                  value={convertForm.deliveryAddress}
                  onChange={(e) => setConvertForm({ ...convertForm, deliveryAddress: e.target.value })}
                />
                <input
                  type="text"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                  placeholder="상세 주소를 입력하세요"
                  value={convertForm.deliveryAddressDetail}
                  onChange={(e) => setConvertForm({ ...convertForm, deliveryAddressDetail: e.target.value })}
                />
              </div>

              {/* 비고 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <input
                  type="text"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                  placeholder="특이사항"
                  value={convertForm.note}
                  onChange={(e) => setConvertForm({ ...convertForm, note: e.target.value })}
                />
              </div>
            </div>

            {/* 모달 푸터 */}
            <div className="flex items-center justify-end gap-3 p-4 border-t bg-gray-50">
              <button
                onClick={() => setShowConvertModal(false)}
                className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
              >
                취소
              </button>
              <button
                onClick={handleConvertToOrder}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
              >
                저장
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full">
            <div className="p-6 border-b">
              <h3 className="text-lg font-bold flex items-center gap-2 text-red-600">
                <AlertTriangle className="w-5 h-5" />
                삭제 확인
              </h3>
            </div>
            <div className="p-6">
              <p className="text-gray-700 mb-4">
                선택한 <span className="font-bold text-red-600">{selectedIds.length}개</span>의 견적을 삭제하시겠습니까?
              </p>
              <div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700">
                <p className="font-medium mb-1">⚠️ 주의</p>
                <p>삭제된 견적은 복구할 수 없습니다.</p>
              </div>
            </div>
            <div className="p-4 border-t bg-gray-50 flex justify-end gap-2">
              <button
                onClick={() => { setShowDeleteModal(false); }}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg"
              >
                취소
              </button>
              <button
                onClick={handleDeleteConfirm}
                className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 flex items-center gap-2"
              >
                <Trash2 className="w-4 h-4" />
                삭제
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============================================================
// 견적 산출내역서 컴포넌트 (스크린샷 기반)
// ============================================================
const QuoteCalculationSheet = ({ quote }) => {
  // 품목별 세부 산출 데이터 생성 (실제로는 견적 데이터에서 가져옴)
  const generateCalculationItems = (item) => {
    const width = item?.width || 4300;
    const height = item?.height || 3000;
    const area = (width * height) / 1000000; // m²

    // 철재스라트 기준 산출 항목
    return [
      { id: 1, name: '검사비', qty: 1, unit: 'SET', formula: '', areaM2: '', areaMmPrice: '', unitPrice: 50000, amount: 50000 },
      { id: 2, name: '스라트', qty: 1, unit: 'SET', formula: '', areaM2: area.toFixed(2), areaMmPrice: 45000, unitPrice: Math.round(area * 45000), amount: Math.round(area * 45000) },
      { id: 3, name: '조인트바', qty: 5, unit: 'SET', formula: '300', areaM2: '', areaMmPrice: '', unitPrice: 5000, amount: 25000 },
      { id: 4, name: '모터', qty: 1, unit: 'SET', formula: '400KG', areaM2: '', areaMmPrice: '', unitPrice: 330000, amount: 330000 },
      { id: 5, name: '매립/노출 연동제어기(뒷박스 포함)', qty: 1, unit: 'SET', formula: '', areaM2: '', areaMmPrice: '', unitPrice: 140000, amount: 140000 },
      { id: 6, name: '케이스', qty: 1, unit: 'SET', formula: '650*550', areaM2: '4.54', areaMmPrice: 74412, unitPrice: 337830, amount: 337830 },
      { id: 7, name: '케이스용 연기차단재', qty: 1, unit: '식', formula: 'W80', areaM2: '4.54', areaMmPrice: 8590, unitPrice: 38999, amount: 38999 },
      { id: 8, name: '케이스 마구리', qty: 1, unit: 'SET', formula: '655*555', areaM2: '', areaMmPrice: '', unitPrice: 26704, amount: 26704 },
      { id: 9, name: '모터 받침용 앵글', qty: 4, unit: 'EA', formula: '50*50*530', areaM2: '', areaMmPrice: '', unitPrice: 4000, amount: 16000 },
      { id: 10, name: '가이드레일', qty: 1, unit: 'SET', formula: '벽면형(130*75) S', areaM2: '3.25', areaMmPrice: 74988, unitPrice: 243711, amount: 243711 },
      { id: 11, name: '레일용 연기차단재', qty: 1, unit: 'SET', formula: 'W50', areaM2: '3.25', areaMmPrice: 5080, unitPrice: 16510, amount: 16510 },
      { id: 12, name: '하장바', qty: 1, unit: 'SET', formula: 'SUS마감', areaM2: '4.30', areaMmPrice: '', unitPrice: 13330, amount: 57319 },
      { id: 13, name: '감기샤프트', qty: 1, unit: '식', formula: '4500x1EA', areaM2: '', areaMmPrice: '', unitPrice: 41000, amount: 41000 },
      { id: 14, name: '각파이프(6000)', qty: 4, unit: 'EA', formula: '6000x4EA', areaM2: '', areaMmPrice: '', unitPrice: 14000, amount: 56000 },
    ];
  };

  // 소요자재 내역 데이터
  const materialSpecs = {
    body: {
      finishType: '철재',
      installType: 'SUS마감',
      guideRail: '벽면형(130*75)',
      openSize: { width: 4300, height: 3000 },
      makeSize: { width: 4410, height: 3350 },
      qty: 1,
      caseSize: '650*550'
    },
    motor: {
      kg: 400,
      selected: true,
      controller: { buried: true, exposed: false, backBox: true },
      bracket: 1,
      angle: 4
    },
    cutting: {
      guideRail: [
        { size: 2438, qty: 0 },
        { size: 3000, qty: 0 },
        { size: 3500, qty: 2 },
        { size: 4000, qty: 0 },
        { size: 4300, qty: 0 },
      ],
      case: [
        { size: 1219, qty: 1 },
        { size: 2438, qty: 0 },
        { size: 3000, qty: 0 },
        { size: 3500, qty: 1 },
        { size: 4000, qty: 0 },
        { size: 4150, qty: 0 },
      ],
      caseExtra: { topCover: 4, end: 2 },
      bottomFinish: { type: 'SUS 1.2T', size3000: 2, size4000: 0 },
      smokeBlock: {
        rail: [
          { size: 2438, qty: 0 },
          { size: 3000, qty: 0 },
          { size: 3500, qty: 2 },
          { size: 4000, qty: 0 },
          { size: 4300, qty: 0 },
        ],
        case: [{ size: 3000, qty: 4 }]
      }
    },
    subMaterial: {
      shaft: { inch: 4, size: 4500, qty: 1 },
      jointBar: { size: 300, qty: 5 },
      squarePipe: { size: 6000, qty: 4 },
      angle: { size: 2500, qty: 0 }
    }
  };

  const items = quote?.items || [{ width: 4300, height: 3000, productName: '철재스라트' }];
  const firstItem = items[0];
  const calculationItems = generateCalculationItems(firstItem);
  const totalAmount = calculationItems.reduce((sum, item) => sum + item.amount, 0);

  return (
    <div className="space-y-6">
      {/* 견적 산출내역서 헤더 */}
      <Card>
        <div className="border-b-2 border-blue-500 pb-4 mb-4">
          <div className="flex justify-between items-start">
            <div>
              <p className="text-sm text-gray-500">작성일자</p>
              <p className="font-medium">{quote?.quoteDate || '2025-07-17'}</p>
            </div>
            <div className="text-center">
              <h2 className="text-xl font-bold text-blue-600">(철재스라트) 견적 산출내역서</h2>
            </div>
            <div className="text-right">
              <p className="text-sm text-gray-500">견적번호</p>
              <p className="font-mono font-medium">{quote?.quoteNo || 'KD-PR-250717-02'}</p>
            </div>
          </div>
        </div>

        {/* 업체/공급자 정보 */}
        <div className="grid grid-cols-2 gap-6 mb-6">
          <div className="border rounded-lg p-4">
            <h3 className="text-sm font-medium text-blue-600 mb-3 border-b pb-2">업체정보</h3>
            <div className="grid grid-cols-2 gap-2 text-sm">
              <div><span className="text-gray-500">업체명:</span> <span className="font-medium">{quote?.customerName || '성지금속 주식회사 (귀하)'}</span></div>
              <div><span className="text-gray-500">담당자:</span> <span className="font-medium">{quote?.manager || '박성근'}</span></div>
              <div><span className="text-gray-500">제품명:</span> <span className="font-medium">자동방화셔터 철재인정제품</span></div>
              <div><span className="text-gray-500">연락처:</span> <span className="font-medium">{quote?.contact || '02-2625-5600'}</span></div>
              <div className="col-span-2"><span className="text-gray-500">현장명:</span> <span className="font-medium">{quote?.siteName || '인천 롯데백화점'}</span></div>
            </div>
          </div>
          <div className="border rounded-lg p-4">
            <h3 className="text-sm font-medium text-blue-600 mb-3 border-b pb-2">공급자</h3>
            <div className="grid grid-cols-2 gap-2 text-sm">
              <div><span className="text-gray-500">상호:</span> <span className="font-medium">(주)경동기업</span></div>
              <div><span className="text-gray-500">대표자:</span> <span className="font-medium">이 경 호</span></div>
              <div><span className="text-gray-500">등록번호:</span> <span className="font-medium">139-87-00333</span></div>
              <div><span className="text-gray-500">업태:</span> <span className="font-medium">제조업</span></div>
              <div><span className="text-gray-500">사업장주소:</span> <span className="font-medium">경기도 김포시 통진읍 용정로 45-22</span></div>
              <div><span className="text-gray-500">종목:</span> <span className="font-medium">방화셔터, 금속창호</span></div>
              <div><span className="text-gray-500">TEL:</span> <span className="font-medium">031-983-5130</span></div>
              <div><span className="text-gray-500">FAX:</span> <span className="font-medium">02-6911-6315</span></div>
            </div>
          </div>
        </div>

        {/* 총 금액 */}
        <div className="text-right mb-6">
          <span className="text-lg">( ￦ </span>
          <span className="text-2xl font-bold text-blue-600">{totalAmount.toLocaleString()}</span>
          <span className="text-lg"> ) </span>
          <span className="text-red-500 font-medium">(VAT 별도)</span>
        </div>

        {/* 제품 요약 */}
        <div className="border rounded-lg overflow-hidden mb-6">
          <table className="w-full text-sm">
            <thead className="bg-gray-100">
              <tr>
                <th className="px-3 py-2 text-center border-r">일련번호</th>
                <th className="px-3 py-2 text-center border-r">종류</th>
                <th className="px-3 py-2 text-center border-r">부호</th>
                <th className="px-3 py-2 text-center border-r">제품명</th>
                <th className="px-3 py-2 text-center border-r" colSpan={2}>오픈사이즈</th>
                <th className="px-3 py-2 text-center border-r">수량</th>
                <th className="px-3 py-2 text-center border-r">단위</th>
                <th className="px-3 py-2 text-center border-r">단가</th>
                <th className="px-3 py-2 text-center">합계금액</th>
              </tr>
              <tr className="bg-gray-50">
                <th className="px-3 py-1 border-r"></th>
                <th className="px-3 py-1 border-r"></th>
                <th className="px-3 py-1 border-r"></th>
                <th className="px-3 py-1 border-r"></th>
                <th className="px-3 py-1 text-center border-r text-blue-600">가로</th>
                <th className="px-3 py-1 text-center border-r text-blue-600">세로</th>
                <th className="px-3 py-1 border-r"></th>
                <th className="px-3 py-1 border-r"></th>
                <th className="px-3 py-1 border-r"></th>
                <th className="px-3 py-1"></th>
              </tr>
            </thead>
            <tbody>
              <tr className="border-t">
                <td className="px-3 py-2 text-center border-r">1</td>
                <td className="px-3 py-2 text-center border-r">철재</td>
                <td className="px-3 py-2 text-center border-r"></td>
                <td className="px-3 py-2 text-center border-r font-medium">KQTS01</td>
                <td className="px-3 py-2 text-center border-r">{firstItem?.width || 4300}</td>
                <td className="px-3 py-2 text-center border-r text-blue-600">{firstItem?.height || 3000}</td>
                <td className="px-3 py-2 text-center border-r text-blue-600">1</td>
                <td className="px-3 py-2 text-center border-r">SET</td>
                <td className="px-3 py-2 text-right border-r">{totalAmount.toLocaleString()}</td>
                <td className="px-3 py-2 text-right font-medium">{totalAmount.toLocaleString()}</td>
              </tr>
              <tr className="border-t bg-gray-50">
                <td colSpan={6} className="px-3 py-2 text-center border-r font-medium">소계</td>
                <td className="px-3 py-2 text-center border-r text-blue-600">1</td>
                <td colSpan={2} className="px-3 py-2 border-r"></td>
                <td className="px-3 py-2 text-right font-bold">{totalAmount.toLocaleString()}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </Card>

      {/* 세부 산출내역서 */}
      <Card title="세부 산출내역서">
        <div className="border rounded-lg overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-gray-100">
              <tr>
                <th className="px-3 py-2 text-center border-r w-16">일련번호</th>
                <th className="px-3 py-2 text-left border-r">항목</th>
                <th className="px-3 py-2 text-center border-r w-16">수량</th>
                <th className="px-3 py-2 text-center border-r w-16">단위</th>
                <th className="px-3 py-2 text-center border-r w-28">산출식</th>
                <th className="px-3 py-2 text-center border-r w-20">면적(m²)<br />길이(mm)</th>
                <th className="px-3 py-2 text-center border-r w-24">면적(m²)<br />길이(mm) 단가</th>
                <th className="px-3 py-2 text-center border-r w-24">단가</th>
                <th className="px-3 py-2 text-center w-28">합계</th>
              </tr>
            </thead>
            <tbody>
              {calculationItems.map((item, idx) => (
                <tr key={item.id} className="border-t hover:bg-gray-50">
                  <td className="px-3 py-2 text-center border-r">{idx === 0 ? '1' : ''}</td>
                  <td className="px-3 py-2 border-r">{item.name}</td>
                  <td className="px-3 py-2 text-center border-r">{item.qty}</td>
                  <td className="px-3 py-2 text-center border-r">{item.unit}</td>
                  <td className="px-3 py-2 text-center border-r text-gray-600">{item.formula}</td>
                  <td className="px-3 py-2 text-center border-r">{item.areaM2}</td>
                  <td className="px-3 py-2 text-right border-r">{item.areaMmPrice ? item.areaMmPrice.toLocaleString() : ''}</td>
                  <td className="px-3 py-2 text-right border-r">{item.unitPrice.toLocaleString()}</td>
                  <td className="px-3 py-2 text-right font-medium">{item.amount.toLocaleString()}</td>
                </tr>
              ))}
              <tr className="border-t bg-blue-50">
                <td colSpan={8} className="px-3 py-2 text-center border-r font-medium">소계</td>
                <td className="px-3 py-2 text-right font-bold text-blue-600">{totalAmount.toLocaleString()}</td>
              </tr>
              <tr className="border-t bg-blue-100">
                <td colSpan={8} className="px-3 py-2 text-center border-r font-bold">전체 합계</td>
                <td className="px-3 py-2 text-right font-bold text-blue-700">{totalAmount.toLocaleString()}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </Card>

      {/* 소요자재 내역 */}
      <Card title="소요자재 내역">
        {/* 2.1 본체 (철재스라트) */}
        <div className="mb-6">
          <h4 className="text-sm font-medium text-gray-700 mb-3 flex items-center gap-2">
            <span className="bg-blue-100 text-blue-700 px-2 py-0.5 rounded">2.1</span>
            본체(철재스라트)
          </h4>
          <div className="border rounded-lg overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-gray-100">
                <tr>
                  <th className="px-3 py-2 text-center border-r">마감유형</th>
                  <th className="px-3 py-2 text-center border-r">설치유형</th>
                  <th className="px-3 py-2 text-center border-r">가로</th>
                  <th className="px-3 py-2 text-center border-r">세로</th>
                  <th className="px-3 py-2 text-center border-r bg-yellow-100">가로</th>
                  <th className="px-3 py-2 text-center border-r bg-yellow-100">세로</th>
                  <th className="px-3 py-2 text-center border-r" colSpan={2}>제작사이즈</th>
                  <th className="px-3 py-2 text-center border-r">수량</th>
                  <th className="px-3 py-2 text-center bg-green-100">케이스</th>
                </tr>
              </thead>
              <tbody>
                <tr className="border-t">
                  <td className="px-3 py-2 text-center border-r text-blue-600">{materialSpecs.body.finishType}</td>
                  <td className="px-3 py-2 text-center border-r text-blue-600">{materialSpecs.body.installType}</td>
                  <td className="px-3 py-2 text-center border-r">{materialSpecs.body.guideRail}</td>
                  <td className="px-3 py-2 text-center border-r">{materialSpecs.body.openSize.width}</td>
                  <td className="px-3 py-2 text-center border-r bg-yellow-50">{materialSpecs.body.openSize.height}</td>
                  <td className="px-3 py-2 text-center border-r">{materialSpecs.body.makeSize.width}</td>
                  <td className="px-3 py-2 text-center border-r">{materialSpecs.body.makeSize.height}</td>
                  <td className="px-3 py-2 text-center border-r">{materialSpecs.body.qty}</td>
                  <td className="px-3 py-2 text-center border-r"></td>
                  <td className="px-3 py-2 text-center bg-green-50 font-medium">{materialSpecs.body.caseSize}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        {/* 2.2 모터 */}
        <div className="mb-6">
          <h4 className="text-sm font-medium text-gray-700 mb-3 flex items-center gap-2">
            <span className="bg-blue-100 text-blue-700 px-2 py-0.5 rounded">2.2</span>
            모터
          </h4>
          <div className="border rounded-lg overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-gray-100">
                <tr>
                  <th className="px-3 py-2 text-center border-r" colSpan={8}>모터종류(KG)</th>
                  <th className="px-3 py-2 text-center border-r" colSpan={3}>연동제어기</th>
                  <th className="px-3 py-2 text-center border-r">브라켓트</th>
                  <th className="px-3 py-2 text-center">앵글</th>
                </tr>
                <tr className="bg-gray-50">
                  <th className="px-2 py-1 text-center border-r text-xs">150</th>
                  <th className="px-2 py-1 text-center border-r text-xs">300</th>
                  <th className="px-2 py-1 text-center border-r text-xs">400</th>
                  <th className="px-2 py-1 text-center border-r text-xs">500</th>
                  <th className="px-2 py-1 text-center border-r text-xs">600</th>
                  <th className="px-2 py-1 text-center border-r text-xs">800</th>
                  <th className="px-2 py-1 text-center border-r text-xs">1000</th>
                  <th className="px-2 py-1 text-center border-r text-xs"></th>
                  <th className="px-2 py-1 text-center border-r text-xs">매립</th>
                  <th className="px-2 py-1 text-center border-r text-xs">노출</th>
                  <th className="px-2 py-1 text-center border-r text-xs">뒷박스</th>
                  <th className="px-2 py-1 text-center border-r text-xs">수량</th>
                  <th className="px-2 py-1 text-center text-xs">수량</th>
                </tr>
              </thead>
              <tbody>
                <tr className="border-t">
                  <td className="px-2 py-2 text-center border-r"></td>
                  <td className="px-2 py-2 text-center border-r"></td>
                  <td className="px-2 py-2 text-center border-r text-blue-600 font-medium">1</td>
                  <td className="px-2 py-2 text-center border-r"></td>
                  <td className="px-2 py-2 text-center border-r"></td>
                  <td className="px-2 py-2 text-center border-r"></td>
                  <td className="px-2 py-2 text-center border-r"></td>
                  <td className="px-2 py-2 text-center border-r"></td>
                  <td className="px-2 py-2 text-center border-r text-blue-600 font-medium">1</td>
                  <td className="px-2 py-2 text-center border-r"></td>
                  <td className="px-2 py-2 text-center border-r text-blue-600 font-medium">1</td>
                  <td className="px-2 py-2 text-center border-r text-blue-600 font-medium">1</td>
                  <td className="px-2 py-2 text-center text-blue-600 font-medium">4</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        {/* 2.3 절곡 */}
        <div className="mb-6">
          <h4 className="text-sm font-medium text-gray-700 mb-3 flex items-center gap-2">
            <span className="bg-blue-100 text-blue-700 px-2 py-0.5 rounded">2.3</span>
            절곡
          </h4>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {/* (1) 가이드레일 */}
            <div className="border rounded-lg overflow-hidden">
              <div className="bg-gray-100 px-3 py-2 text-sm font-medium text-center">(1) 가이드레일<br />(EGI 1.6T/ SUS 1.2T)</div>
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-2 py-1 text-center border-r">사이즈</th>
                    <th className="px-2 py-1 text-center">수량</th>
                  </tr>
                </thead>
                <tbody>
                  {materialSpecs.cutting.guideRail.map((item, idx) => (
                    <tr key={idx} className="border-t">
                      <td className="px-2 py-1 text-center border-r">{item.size}</td>
                      <td className="px-2 py-1 text-center text-blue-600 font-medium">{item.qty || ''}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* (2) 케이스 */}
            <div className="border rounded-lg overflow-hidden">
              <div className="bg-gray-100 px-3 py-2 text-sm font-medium text-center">(2) 케이스<br />(EGI 1.6T)</div>
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-2 py-1 text-center border-r">사이즈</th>
                    <th className="px-2 py-1 text-center">수량</th>
                  </tr>
                </thead>
                <tbody>
                  {materialSpecs.cutting.case.map((item, idx) => (
                    <tr key={idx} className="border-t">
                      <td className="px-2 py-1 text-center border-r">{item.size}</td>
                      <td className="px-2 py-1 text-center text-blue-600 font-medium">{item.qty || ''}</td>
                    </tr>
                  ))}
                  <tr className="border-t bg-gray-50">
                    <td className="px-2 py-1 text-center border-r">상부덮개</td>
                    <td className="px-2 py-1 text-center text-blue-600 font-medium">{materialSpecs.cutting.caseExtra.topCover}</td>
                  </tr>
                  <tr className="border-t bg-gray-50">
                    <td className="px-2 py-1 text-center border-r">마구리</td>
                    <td className="px-2 py-1 text-center text-blue-600 font-medium">{materialSpecs.cutting.caseExtra.end}</td>
                  </tr>
                </tbody>
              </table>
            </div>

            {/* (3) 하단마감재 */}
            <div className="border rounded-lg overflow-hidden">
              <div className="bg-gray-100 px-3 py-2 text-sm font-medium text-center">(3) 하단마감재<br />(SUS 1.2T)</div>
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-2 py-1 text-center border-r">분류</th>
                    <th className="px-2 py-1 text-center border-r">3000</th>
                    <th className="px-2 py-1 text-center">4000</th>
                  </tr>
                </thead>
                <tbody>
                  <tr className="border-t">
                    <td className="px-2 py-1 text-center border-r">하단마감재<br />(SUS 1.2T)</td>
                    <td className="px-2 py-1 text-center border-r text-blue-600 font-medium">{materialSpecs.cutting.bottomFinish.size3000}</td>
                    <td className="px-2 py-1 text-center text-blue-600 font-medium">{materialSpecs.cutting.bottomFinish.size4000 || ''}</td>
                  </tr>
                </tbody>
              </table>
            </div>

            {/* (4) 연기차단재 */}
            <div className="border rounded-lg overflow-hidden">
              <div className="bg-gray-100 px-3 py-2 text-sm font-medium text-center">(4) 연기차단재</div>
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-2 py-1 text-center border-r">분류</th>
                    <th className="px-2 py-1 text-center border-r">사이즈</th>
                    <th className="px-2 py-1 text-center">수량</th>
                  </tr>
                </thead>
                <tbody>
                  {materialSpecs.cutting.smokeBlock.rail.filter(r => r.qty > 0).map((item, idx) => (
                    <tr key={idx} className="border-t">
                      <td className="px-2 py-1 text-center border-r">레일용</td>
                      <td className="px-2 py-1 text-center border-r">{item.size}</td>
                      <td className="px-2 py-1 text-center text-blue-600 font-medium">{item.qty}</td>
                    </tr>
                  ))}
                  {materialSpecs.cutting.smokeBlock.case.map((item, idx) => (
                    <tr key={idx} className="border-t">
                      <td className="px-2 py-1 text-center border-r">케이스용</td>
                      <td className="px-2 py-1 text-center border-r">{item.size}</td>
                      <td className="px-2 py-1 text-center text-blue-600 font-medium">{item.qty}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        {/* 2.4 부자재 */}
        <div>
          <h4 className="text-sm font-medium text-gray-700 mb-3 flex items-center gap-2">
            <span className="bg-blue-100 text-blue-700 px-2 py-0.5 rounded">2.4</span>
            부자재
          </h4>
          <div className="border rounded-lg overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-gray-100">
                <tr>
                  <th className="px-3 py-2 text-center border-r" colSpan={7}>감기샤프트</th>
                </tr>
                <tr className="bg-gray-50">
                  <th className="px-2 py-1 text-center border-r" colSpan={2}>4인치</th>
                  <th className="px-2 py-1 text-center border-r" colSpan={3}>5인치</th>
                  <th className="px-2 py-1 text-center border-r" colSpan={4}>6인치</th>
                  <th className="px-2 py-1 text-center">8인치</th>
                </tr>
                <tr className="bg-gray-50 text-xs">
                  <th className="px-1 py-1 text-center border-r">3000</th>
                  <th className="px-1 py-1 text-center border-r">4500</th>
                  <th className="px-1 py-1 text-center border-r">6000</th>
                  <th className="px-1 py-1 text-center border-r">6000</th>
                  <th className="px-1 py-1 text-center border-r">7000</th>
                  <th className="px-1 py-1 text-center border-r">8200</th>
                  <th className="px-1 py-1 text-center border-r">3000</th>
                  <th className="px-1 py-1 text-center border-r">6000</th>
                  <th className="px-1 py-1 text-center border-r">7000</th>
                  <th className="px-1 py-1 text-center border-r">8000</th>
                  <th className="px-1 py-1 text-center">8200</th>
                </tr>
              </thead>
              <tbody>
                <tr className="border-t">
                  <td className="px-1 py-2 text-center border-r"></td>
                  <td className="px-1 py-2 text-center border-r text-blue-600 font-medium">1</td>
                  <td className="px-1 py-2 text-center border-r"></td>
                  <td className="px-1 py-2 text-center border-r"></td>
                  <td className="px-1 py-2 text-center border-r"></td>
                  <td className="px-1 py-2 text-center border-r"></td>
                  <td className="px-1 py-2 text-center border-r"></td>
                  <td className="px-1 py-2 text-center border-r"></td>
                  <td className="px-1 py-2 text-center border-r"></td>
                  <td className="px-1 py-2 text-center border-r"></td>
                  <td className="px-1 py-2 text-center"></td>
                </tr>
              </tbody>
            </table>
          </div>
          <div className="grid grid-cols-3 gap-4 mt-4">
            <div className="border rounded-lg overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-gray-100">
                  <tr>
                    <th className="px-3 py-2 text-center" colSpan={2}>조인트바</th>
                  </tr>
                  <tr className="bg-gray-50">
                    <th className="px-2 py-1 text-center border-r">300</th>
                    <th className="px-2 py-1 text-center"></th>
                  </tr>
                </thead>
                <tbody>
                  <tr className="border-t">
                    <td className="px-2 py-2 text-center border-r text-blue-600 font-medium">{materialSpecs.subMaterial.jointBar.qty}</td>
                    <td className="px-2 py-2 text-center"></td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div className="border rounded-lg overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-gray-100">
                  <tr>
                    <th className="px-3 py-2 text-center" colSpan={2}>각파이프</th>
                  </tr>
                  <tr className="bg-gray-50">
                    <th className="px-2 py-1 text-center border-r">3000</th>
                    <th className="px-2 py-1 text-center">6000</th>
                  </tr>
                </thead>
                <tbody>
                  <tr className="border-t">
                    <td className="px-2 py-2 text-center border-r"></td>
                    <td className="px-2 py-2 text-center text-blue-600 font-medium">{materialSpecs.subMaterial.squarePipe.qty}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div className="border rounded-lg overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-gray-100">
                  <tr>
                    <th className="px-3 py-2 text-center">앵글</th>
                  </tr>
                  <tr className="bg-gray-50">
                    <th className="px-2 py-1 text-center">2500</th>
                  </tr>
                </thead>
                <tbody>
                  <tr className="border-t">
                    <td className="px-2 py-2 text-center text-blue-600 font-medium">{materialSpecs.subMaterial.angle.qty || ''}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </Card>

      {/* 인쇄 버튼 */}
      <div className="flex justify-end gap-2">
        <Button variant="outline">
          <Download className="w-4 h-4" /> 엑셀 다운로드
        </Button>
        <Button variant="primary">
          <Printer className="w-4 h-4" /> 인쇄
        </Button>
      </div>
    </div>
  );
};

// ============================================================
// 발주서 컴포넌트
// ============================================================
const QuotePurchaseOrder = ({ quote }) => {
  return (
    <div className="space-y-6">
      <Card title="발주서">
        <div className="border rounded-lg p-6">
          <div className="text-center mb-6">
            <h2 className="text-2xl font-bold">발 주 서</h2>
            <p className="text-gray-500 mt-1">Purchase Order</p>
          </div>

          <div className="grid grid-cols-2 gap-6 mb-6">
            <div className="border rounded-lg p-4">
              <h3 className="text-sm font-medium text-gray-700 mb-3">발주처</h3>
              <div className="space-y-2 text-sm">
                <div className="flex"><span className="w-20 text-gray-500">업체명:</span> <span className="font-medium">(주)경동기업</span></div>
                <div className="flex"><span className="w-20 text-gray-500">담당자:</span> <span>판매부</span></div>
                <div className="flex"><span className="w-20 text-gray-500">연락처:</span> <span>031-983-5130</span></div>
                <div className="flex"><span className="w-20 text-gray-500">FAX:</span> <span>02-6911-6315</span></div>
              </div>
            </div>
            <div className="border rounded-lg p-4">
              <h3 className="text-sm font-medium text-gray-700 mb-3">수신처</h3>
              <div className="space-y-2 text-sm">
                <div className="flex"><span className="w-20 text-gray-500">업체명:</span> <span className="font-medium">{quote?.customerName || '성지금속 주식회사'}</span></div>
                <div className="flex"><span className="w-20 text-gray-500">담당자:</span> <span>{quote?.manager || '박성근'}</span></div>
                <div className="flex"><span className="w-20 text-gray-500">연락처:</span> <span>{quote?.contact || '02-2625-5600'}</span></div>
              </div>
            </div>
          </div>

          <div className="mb-6">
            <div className="grid grid-cols-3 gap-4 text-sm">
              <div className="flex"><span className="w-20 text-gray-500">발주번호:</span> <span className="font-mono">{quote?.quoteNo?.replace('PR', 'PO') || 'KD-PO-250717-02'}</span></div>
              <div className="flex"><span className="w-20 text-gray-500">발주일:</span> <span>{quote?.quoteDate || '2025-07-17'}</span></div>
              <div className="flex"><span className="w-20 text-gray-500">납기일:</span> <span className="text-red-600 font-medium">{quote?.dueDate || '2025-08-15'}</span></div>
            </div>
          </div>

          <div className="border rounded-lg overflow-hidden mb-6">
            <table className="w-full text-sm">
              <thead className="bg-gray-100">
                <tr>
                  <th className="px-3 py-2 text-center border-r">No</th>
                  <th className="px-3 py-2 text-left border-r">품목명</th>
                  <th className="px-3 py-2 text-center border-r">규격</th>
                  <th className="px-3 py-2 text-center border-r">수량</th>
                  <th className="px-3 py-2 text-center border-r">단위</th>
                  <th className="px-3 py-2 text-right border-r">단가</th>
                  <th className="px-3 py-2 text-right">금액</th>
                </tr>
              </thead>
              <tbody>
                {(quote?.items || [{ productName: '철재스라트 셔터', width: 4300, height: 3000, qty: 1, unitPrice: 2053623, amount: 2053623 }]).map((item, idx) => (
                  <tr key={idx} className="border-t">
                    <td className="px-3 py-2 text-center border-r">{idx + 1}</td>
                    <td className="px-3 py-2 border-r">{item.productName}</td>
                    <td className="px-3 py-2 text-center border-r">{item.width}×{item.height}</td>
                    <td className="px-3 py-2 text-center border-r">{item.qty}</td>
                    <td className="px-3 py-2 text-center border-r">SET</td>
                    <td className="px-3 py-2 text-right border-r">{(item.unitPrice || item.amount)?.toLocaleString()}</td>
                    <td className="px-3 py-2 text-right">{item.amount?.toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
              <tfoot className="bg-gray-50">
                <tr className="border-t">
                  <td colSpan={6} className="px-3 py-2 text-right font-medium border-r">합계</td>
                  <td className="px-3 py-2 text-right font-bold text-blue-600">
                    {(quote?.totalAmount || 2053623).toLocaleString()}원
                  </td>
                </tr>
                <tr className="border-t">
                  <td colSpan={6} className="px-3 py-2 text-right font-medium border-r">VAT (10%)</td>
                  <td className="px-3 py-2 text-right">
                    {Math.round((quote?.totalAmount || 2053623) * 0.1).toLocaleString()}원
                  </td>
                </tr>
                <tr className="border-t bg-blue-50">
                  <td colSpan={6} className="px-3 py-2 text-right font-bold border-r">총액</td>
                  <td className="px-3 py-2 text-right font-bold text-blue-700">
                    {Math.round((quote?.totalAmount || 2053623) * 1.1).toLocaleString()}원
                  </td>
                </tr>
              </tfoot>
            </table>
          </div>

          <div className="border rounded-lg p-4 mb-6 bg-yellow-50">
            <h4 className="text-sm font-medium text-gray-700 mb-2">특이사항</h4>
            <ul className="text-sm text-gray-600 space-y-1">
              <li>★ 해당 견적서의 유효기간은 <span className="text-red-600 font-medium underline">발행일 기준 1개월</span>입니다.</li>
              <li>★ 견적금액의 50%를 입금하시면 발주가 진행됩니다.</li>
            </ul>
          </div>

          <div className="grid grid-cols-4 gap-4 text-sm">
            <div className="flex"><span className="w-16 text-gray-500">결제방법:</span> <span>계좌이체</span></div>
            <div className="flex"><span className="w-16 text-gray-500">계좌정보:</span> <span>국민은행 796801-00-039630</span></div>
            <div className="flex"><span className="w-16 text-gray-500">담당자:</span> <span>손금주</span></div>
            <div className="flex"><span className="w-16 text-gray-500">연락처:</span> <span>070-4351-5275</span></div>
          </div>
        </div>
      </Card>

      <div className="flex justify-end gap-2">
        <Button variant="outline">
          <Download className="w-4 h-4" /> 엑셀 다운로드
        </Button>
        <Button variant="primary">
          <Printer className="w-4 h-4" /> 인쇄
        </Button>
      </div>
    </div>
  );
};

// 견적 상세
const QuoteDetail = ({ quote, orders = [], onNavigate, onBack, onConvertToOrder, onUpdateQuote, onCreateOrder }) => {
  // 문서 다이얼로그 상태
  const [showQuoteSheet, setShowQuoteSheet] = useState(false);
  const [showCalculationSheet, setShowCalculationSheet] = useState(false);
  const [showPurchaseOrder, setShowPurchaseOrder] = useState(false);

  const [showItemAddModal, setShowItemAddModal] = useState(false);
  const [showConvertModal, setShowConvertModal] = useState(false);
  const [newItem, setNewItem] = useState({
    category: '스크린',
    productName: '스크린 셔터 (표준형)',
    floor: '',
    location: '',
    width: '',
    height: '',
    qty: 1,
  });
  const [convertForm, setConvertForm] = useState({
    shipDate: '',
    shipDateUndecided: false,
    dueDate: '',
    dueDateUndecided: false,
    deliveryMethod: '상차',
    freightCost: '선불',
    receiverName: '',
    receiverPhone: '',
    deliveryAddress: '',
    deliveryAddressDetail: '',
    note: '',
  });

  // ★ 수주전환 완료 확인 다이얼로그 상태
  const [showConvertCompleteDialog, setShowConvertCompleteDialog] = useState(false);
  const [convertCompleteInfo, setConvertCompleteInfo] = useState({ orderNo: '', customerName: '', siteName: '', totalAmount: 0 });

  // 연관 수주 찾기
  const relatedOrders = orders.filter(o => o.quoteId === quote.id || o.quoteNo === quote.quoteNo);

  // 수주된 품목 / 미수주 품목 분리
  const orderedItems = quote.items?.filter(item => item.orderStatus === 'ordered') || [];
  const pendingItems = quote.items?.filter(item => item.orderStatus !== 'ordered') || [];

  const handleConvertToOrder = () => {
    if (quote.status === '수주전환' && pendingItems.length === 0) {
      alert('모든 품목이 이미 수주로 전환되었습니다.');
      return;
    }
    // 수주전환 모달 열기
    setConvertForm({
      shipDate: '',
      shipDateUndecided: false,
      dueDate: '',
      dueDateUndecided: false,
      deliveryMethod: '상차',
      freightCost: '선불',
      receiverName: '',
      receiverPhone: '',
      deliveryAddress: quote.deliveryAddress || '',
      deliveryAddressDetail: '',
      note: '',
    });
    setShowConvertModal(true);
  };

  // 수주전환 실행
  const handleConvertConfirm = () => {
    // 수주번호 생성 - 채번관리 규칙 적용
    const productType = quote.productType || quote.productName || '';
    const newOrderNo = generateNumber('수주번호', productType, []);

    // 새 수주 데이터 생성
    const newOrder = {
      id: Date.now(),
      orderNo: newOrderNo,
      quoteNo: quote.quoteNo,
      quoteId: quote.id,
      orderDate: new Date().toISOString().split('T')[0],
      customerName: quote.customerName,
      siteName: quote.siteName,
      siteAddress: quote.deliveryAddress || convertForm.deliveryAddress,
      manager: quote.manager,
      contact: quote.contact,
      productName: quote.productName,
      qty: quote.qty,
      totalAmount: quote.finalAmount || quote.totalAmount,
      status: '수주등록',
      dueDate: convertForm.dueDateUndecided ? '미정' : convertForm.dueDate,
      shipDate: convertForm.shipDateUndecided ? '미정' : convertForm.shipDate,
      deliveryMethod: convertForm.deliveryMethod,
      freightCost: convertForm.freightCost,
      receiverName: convertForm.receiverName,
      receiverPhone: convertForm.receiverPhone,
      deliveryAddress: convertForm.deliveryAddress,
      deliveryAddressDetail: convertForm.deliveryAddressDetail,
      note: convertForm.note,
      creditGrade: quote.creditGrade,
      items: quote.items || [],
      history: [{
        id: Date.now(),
        changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
        changeType: '수주등록',
        description: `견적(${quote.quoteNo})에서 수주전환`,
        changedBy: '현재 사용자',
      }],
    };

    // 수주 생성 콜백 호출
    if (onCreateOrder) {
      onCreateOrder(newOrder);
    }

    // 견적 상태 업데이트
    if (onUpdateQuote) {
      onUpdateQuote({
        ...quote,
        status: '수주전환',
        convertedOrderNo: newOrderNo,
      });
    }

    // ★ 확인 다이얼로그 표시 (alert 대신)
    setConvertCompleteInfo({
      orderNo: newOrderNo,
      customerName: quote.customerName,
      siteName: quote.siteName,
      totalAmount: quote.finalAmount || quote.totalAmount,
    });
    setShowConvertModal(false);
    setShowConvertCompleteDialog(true);
  };

  // 추가분 수주전환
  const handleConvertPendingItems = () => {
    if (pendingItems.length === 0) {
      alert('수주 대기 중인 품목이 없습니다.');
      return;
    }
    // 추가분만 선택해서 수주 생성
    onNavigate('order-create-additional', { quote, pendingItems, relatedOrders });
  };

  // 품목 추가
  const handleAddItem = () => {
    // 간단한 자동 계산 (실제로는 복잡한 로직)
    const unitPrice = newItem.category === '스크린'
      ? Math.round((newItem.width * newItem.height) / 1000 * 0.5)
      : 450000;
    const amount = unitPrice * newItem.qty;

    const addedItem = {
      id: Date.now(),
      ...newItem,
      width: parseInt(newItem.width) || 0,
      height: parseInt(newItem.height) || 0,
      unitPrice,
      amount,
      orderStatus: 'pending',
      orderId: null,
    };

    onUpdateQuote?.({
      ...quote,
      items: [...(quote.items || []), addedItem],
      totalAmount: (quote.totalAmount || 0) + amount,
    });

    setShowItemAddModal(false);
    setNewItem({
      category: '스크린',
      productName: '스크린 셔터 (표준형)',
      floor: '',
      location: '',
      width: '',
      height: '',
      qty: 1,
    });
  };

  return (
    <div className="space-y-6">
      {/* 상단 헤더 - 타이틀 위, 버튼 아래 */}
      <div className="space-y-3">
        {/* 타이틀 영역 */}
        <div className="flex items-center gap-4">
          <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
            <FileText className="w-6 h-6 text-blue-500" />
            견적 상세
          </h1>
          <div className="flex items-center gap-2 text-sm text-gray-500">
            <span className="font-mono">{quote.quoteNo}</span>
            <StatusBadge status={quote.status} />
          </div>
        </div>
        {/* 버튼 영역 - 좌측: 문서버튼 / 우측: 액션버튼 */}
        <div className="flex items-center justify-between">
          {/* 좌측: 문서 버튼 */}
          <div className="flex items-center gap-2">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-1 px-3 py-1.5 text-sm border rounded transition-colors ${activeTab === tab.id
                    ? 'border-blue-500 bg-blue-50 text-blue-600'
                    : 'border-gray-300 hover:bg-gray-50'
                  }`}
              >
                <tab.icon className="w-4 h-4" />
                {tab.label}
              </button>
            ))}
          </div>
          {/* 우측: 액션 버튼 */}
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={onBack}>
              목록
            </Button>
            {/* 최초작성 상태 → 최종확정 버튼 */}
            {(quote.status === '최초작성' || quote.status?.includes('수정')) && (
              <Button variant="primary" size="sm" onClick={() => onUpdateQuote?.({ ...quote, status: '최종확정' })}>
                <CheckCircle className="w-4 h-4" /> 최종확정
              </Button>
            )}
            {/* 최종확정 상태 → 수주전환 버튼 */}
            {quote.status === '최종확정' && relatedOrders.length === 0 && (
              <Button variant="primary" size="sm" onClick={handleConvertToOrder}>
                <ShoppingCart className="w-4 h-4" /> 수주전환
              </Button>
            )}
            {/* 추가분 수주전환 */}
            {relatedOrders.length > 0 && pendingItems.length > 0 && (
              <Button variant="primary" size="sm" onClick={handleConvertPendingItems}>
                <Plus className="w-4 h-4" /> 추가분 수주전환 ({pendingItems.length}건)
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* 산출내역서 탭 */}
      {activeTab === 'calculation' && (
        <QuoteCalculationSheet quote={quote} />
      )}

      {/* 발주서 탭 */}
      {activeTab === 'order' && (
        <QuotePurchaseOrder quote={quote} />
      )}

      {/* 견적서 탭 */}
      {activeTab === 'quote' && (
        <>
          {/* 기본 정보 */}
          <Card title="기본 정보">
            <div className="grid grid-cols-3 gap-6">
              <div>
                <label className="text-sm text-gray-500">견적번호</label>
                <p className="font-mono text-gray-900">{quote.quoteNo}</p>
              </div>
              <div>
                <label className="text-sm text-gray-500">작성자</label>
                <p className="text-gray-900">{quote.createdBy}</p>
              </div>
              <div>
                <label className="text-sm text-gray-500">발주처</label>
                <p className="text-gray-900">{quote.customerName}</p>
              </div>
              <div>
                <label className="text-sm text-gray-500">담당자</label>
                <p className="text-gray-900">{quote.manager}</p>
              </div>
              <div>
                <label className="text-sm text-gray-500">연락처</label>
                <p className="text-gray-900">{quote.contact}</p>
              </div>
              <div>
                <label className="text-sm text-gray-500">현장명</label>
                <p className="text-gray-900">{quote.siteName}</p>
              </div>
              <div>
                <label className="text-sm text-gray-500">현장코드</label>
                <p className="font-mono text-gray-900">{quote.siteCode}</p>
              </div>
              <div>
                <label className="text-sm text-gray-500">상태</label>
                <p><StatusBadge status={quote.status} /></p>
              </div>
              <div>
                <label className="text-sm text-gray-500">접수일</label>
                <p className="text-gray-900">{quote.quoteDate}</p>
              </div>
              <div>
                <label className="text-sm text-gray-500">납기일</label>
                <p className="text-gray-900">{quote.dueDate}</p>
              </div>
            </div>
            {quote.note && (
              <div className="mt-4 pt-4 border-t">
                <label className="text-sm text-gray-500">비고</label>
                <p className="text-gray-900">{quote.note}</p>
              </div>
            )}
          </Card>

          {/* 품목 내역 (수주 상태 포함) */}
          <Card title={
            <div className="flex items-center justify-between w-full">
              <span>품목 내역</span>
              <Button variant="outline" size="sm" onClick={() => setShowItemAddModal(true)}>
                <Plus className="w-4 h-4" /> 품목 추가
              </Button>
            </div>
          }>
            {quote.items && quote.items.length > 0 ? (
              <div className="space-y-4">
                {/* 수주 완료 품목 */}
                {orderedItems.length > 0 && (
                  <div>
                    <h4 className="text-sm font-medium text-green-700 mb-2 flex items-center gap-2">
                      <CheckCircle className="w-4 h-4" /> 수주 완료 ({orderedItems.length}건)
                    </h4>
                    <div className="space-y-2">
                      {orderedItems.map((item) => (
                        <div key={item.id} className="p-4 bg-green-50 rounded-lg border border-green-200">
                          <div className="grid grid-cols-6 gap-4 text-sm">
                            <div>
                              <label className="text-gray-500">제품</label>
                              <p className="font-medium">{item.productName}</p>
                            </div>
                            <div>
                              <label className="text-gray-500">층/부호</label>
                              <p className="font-medium">{item.floor}/{item.location}</p>
                            </div>
                            <div>
                              <label className="text-gray-500">사이즈</label>
                              <p className="font-medium">{item.width}×{item.height}</p>
                            </div>
                            <div>
                              <label className="text-gray-500">수량</label>
                              <p className="font-medium">{item.qty}</p>
                            </div>
                            <div>
                              <label className="text-gray-500">금액</label>
                              <p className="font-medium">{item.amount?.toLocaleString()}원</p>
                            </div>
                            <div>
                              <label className="text-gray-500">로트번호</label>
                              <p className="font-mono text-blue-600 text-xs">
                                {relatedOrders.find(o => o.id === item.orderId)?.orderNo || '-'}
                              </p>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* 미수주 품목 */}
                {pendingItems.length > 0 && (
                  <div>
                    <h4 className="text-sm font-medium text-yellow-700 mb-2 flex items-center gap-2">
                      <Clock className="w-4 h-4" /> 수주 대기 ({pendingItems.length}건)
                    </h4>
                    <div className="space-y-2">
                      {pendingItems.map((item) => (
                        <div key={item.id} className="p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                          <div className="grid grid-cols-5 gap-4 text-sm">
                            <div>
                              <label className="text-gray-500">제품</label>
                              <p className="font-medium">{item.productName}</p>
                            </div>
                            <div>
                              <label className="text-gray-500">층/부호</label>
                              <p className="font-medium">{item.floor || '-'}/{item.location || '-'}</p>
                            </div>
                            <div>
                              <label className="text-gray-500">사이즈</label>
                              <p className="font-medium">{item.width}×{item.height}</p>
                            </div>
                            <div>
                              <label className="text-gray-500">수량</label>
                              <p className="font-medium">{item.qty}</p>
                            </div>
                            <div>
                              <label className="text-gray-500">금액</label>
                              <p className="font-medium text-blue-600">{item.amount?.toLocaleString()}원</p>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <div className="flex justify-end pt-4 border-t">
                  <div className="text-right">
                    <span className="text-gray-500 mr-4">총 견적 금액</span>
                    <span className="text-xl font-bold text-blue-600">{quote.totalAmount?.toLocaleString()}원</span>
                  </div>
                </div>
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500">
                <Package className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                <p>등록된 품목이 없습니다.</p>
                <Button variant="outline" className="mt-4" onClick={() => setShowItemAddModal(true)}>
                  <Plus className="w-4 h-4" /> 품목 추가
                </Button>
              </div>
            )}
          </Card>
        </>
      )}

      {/* 수주이력 탭 */}
      {activeTab === 'orderHistory' && (
        <Card title="연관 수주">
          {relatedOrders.length > 0 ? (
            <div className="space-y-4">
              {/* 수주 목록 */}
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">로트번호</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">유형</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">수주일</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">금액</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
                    <th className="px-4 py-3 text-center text-xs font-medium text-gray-500"></th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {relatedOrders.map(order => (
                    <tr key={order.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3">
                        <span className="font-mono text-blue-600">{order.orderNo}</span>
                      </td>
                      <td className="px-4 py-3 text-center">
                        <StatusBadge status={order.orderType === 'initial' ? '최초' : order.orderType === 'additional' ? '추가' : '직접'} />
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-600">{order.orderDate}</td>
                      <td className="px-4 py-3 text-sm text-right font-medium">{order.totalAmount?.toLocaleString()}원</td>
                      <td className="px-4 py-3 text-center"><StatusBadge status={order.status} /></td>
                      <td className="px-4 py-3 text-center">
                        <Button variant="outline" size="sm" onClick={() => onNavigate('order-detail', order)}>
                          <Eye className="w-4 h-4" />
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
                <tfoot className="bg-gray-50">
                  <tr>
                    <td colSpan={3} className="px-4 py-3 text-sm font-medium text-right">합계</td>
                    <td className="px-4 py-3 text-sm text-right font-bold text-blue-600">
                      {relatedOrders.reduce((sum, o) => sum + (o.totalAmount || 0), 0).toLocaleString()}원
                    </td>
                    <td colSpan={2}></td>
                  </tr>
                </tfoot>
              </table>

              {/* 미수주 품목 안내 */}
              {pendingItems.length > 0 && (
                <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2 text-yellow-700">
                      <AlertCircle className="w-5 h-5" />
                      <span className="font-medium">미수주 품목 {pendingItems.length}건</span>
                      <span className="text-sm">({pendingItems.reduce((sum, i) => sum + (i.amount || 0), 0).toLocaleString()}원)</span>
                    </div>
                    <Button variant="primary" size="sm" onClick={handleConvertPendingItems}>
                      <Plus className="w-4 h-4" /> 추가분 수주전환
                    </Button>
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              <Package className="w-12 h-12 mx-auto mb-3 text-gray-300" />
              <p>연관된 수주가 없습니다.</p>
              {quote.status === '최종확정' && (
                <Button variant="primary" className="mt-4" onClick={handleConvertToOrder}>
                  <ShoppingCart className="w-4 h-4" /> 수주전환
                </Button>
              )}
            </div>
          )}
        </Card>
      )}

      {/* 품목 추가 모달 */}
      {showItemAddModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b sticky top-0 bg-white z-10">
              <h2 className="text-xl font-bold text-gray-900">품목 추가</h2>
              <p className="text-sm text-gray-500 mt-1">견적에 품목을 추가합니다.</p>
            </div>

            <div className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">제품 카테고리</label>
                  <select
                    value={newItem.category}
                    onChange={(e) => setNewItem(prev => ({ ...prev, category: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="스크린">스크린</option>
                    <option value="슬랫">슬랫</option>
                    <option value="절곡">절곡</option>
                    <option value="부자재">부자재</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">제품명</label>
                  <input
                    type="text"
                    value={newItem.productName}
                    onChange={(e) => setNewItem(prev => ({ ...prev, productName: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>

              {newItem.category !== '부자재' && (
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">가로 (mm)</label>
                    <input
                      type="number"
                      value={newItem.width}
                      onChange={(e) => setNewItem(prev => ({ ...prev, width: e.target.value }))}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="예: 2000"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">세로 (mm)</label>
                    <input
                      type="number"
                      value={newItem.height}
                      onChange={(e) => setNewItem(prev => ({ ...prev, height: e.target.value }))}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="예: 2500"
                    />
                  </div>
                </div>
              )}

              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">층</label>
                  <input
                    type="text"
                    value={newItem.floor}
                    onChange={(e) => setNewItem(prev => ({ ...prev, floor: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="예: 3층"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">부호</label>
                  <input
                    type="text"
                    value={newItem.location}
                    onChange={(e) => setNewItem(prev => ({ ...prev, location: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="예: C-01"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">수량</label>
                  <input
                    type="number"
                    value={newItem.qty}
                    onChange={(e) => setNewItem(prev => ({ ...prev, qty: parseInt(e.target.value) || 1 }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    min="1"
                  />
                </div>
              </div>
            </div>

            <div className="flex gap-2 p-4 border-t bg-gray-50 rounded-b-xl">
              <Button variant="outline" className="flex-1" onClick={() => setShowItemAddModal(false)}>
                취소
              </Button>
              <Button variant="primary" className="flex-1" onClick={handleAddItem}>
                <Plus className="w-4 h-4" /> 추가
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 수주전환 모달 */}
      {showConvertModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg mx-4">
            <div className="flex items-center justify-between p-4 border-b">
              <h3 className="text-lg font-bold text-gray-900">수주전환</h3>
              <button onClick={() => setShowConvertModal(false)} className="p-1 hover:bg-gray-100 rounded">
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-4 space-y-4 max-h-[70vh] overflow-y-auto">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">출하예정일</label>
                <div className="flex items-center gap-2">
                  <input
                    type="date"
                    value={convertForm.shipDate}
                    onChange={(e) => setConvertForm(prev => ({ ...prev, shipDate: e.target.value }))}
                    disabled={convertForm.shipDateUndecided}
                    className="flex-1 px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
                  />
                  <label className="flex items-center gap-1 text-sm text-gray-600">
                    <input
                      type="checkbox"
                      checked={convertForm.shipDateUndecided}
                      onChange={(e) => setConvertForm(prev => ({ ...prev, shipDateUndecided: e.target.checked, shipDate: '' }))}
                      className="rounded"
                    />
                    미정
                  </label>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">납기일</label>
                <div className="flex items-center gap-2">
                  <input
                    type="date"
                    value={convertForm.dueDate}
                    onChange={(e) => setConvertForm(prev => ({ ...prev, dueDate: e.target.value }))}
                    disabled={convertForm.dueDateUndecided}
                    className="flex-1 px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
                  />
                  <label className="flex items-center gap-1 text-sm text-gray-600">
                    <input
                      type="checkbox"
                      checked={convertForm.dueDateUndecided}
                      onChange={(e) => setConvertForm(prev => ({ ...prev, dueDateUndecided: e.target.checked, dueDate: '' }))}
                      className="rounded"
                    />
                    미정
                  </label>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">배송방법</label>
                  <select
                    value={convertForm.deliveryMethod}
                    onChange={(e) => setConvertForm(prev => ({ ...prev, deliveryMethod: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="상차">상차</option>
                    <option value="택배">택배</option>
                    <option value="직접배송">직접배송</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">운임비</label>
                  <select
                    value={convertForm.freightCost}
                    onChange={(e) => setConvertForm(prev => ({ ...prev, freightCost: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="선불">선불</option>
                    <option value="착불">착불</option>
                    <option value="무료">무료</option>
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">수령인</label>
                  <input
                    type="text"
                    value={convertForm.receiverName}
                    onChange={(e) => setConvertForm(prev => ({ ...prev, receiverName: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="수령인 이름"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">연락처</label>
                  <input
                    type="text"
                    value={convertForm.receiverPhone}
                    onChange={(e) => setConvertForm(prev => ({ ...prev, receiverPhone: e.target.value }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="010-0000-0000"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">배송지 주소</label>
                <input
                  type="text"
                  value={convertForm.deliveryAddress}
                  onChange={(e) => setConvertForm(prev => ({ ...prev, deliveryAddress: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 mb-2"
                  placeholder="기본 주소"
                />
                <input
                  type="text"
                  value={convertForm.deliveryAddressDetail}
                  onChange={(e) => setConvertForm(prev => ({ ...prev, deliveryAddressDetail: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="상세 주소"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <textarea
                  value={convertForm.note}
                  onChange={(e) => setConvertForm(prev => ({ ...prev, note: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  rows={2}
                  placeholder="특이사항 입력"
                />
              </div>
            </div>

            <div className="flex gap-2 p-4 border-t bg-gray-50 rounded-b-xl">
              <Button variant="outline" className="flex-1" onClick={() => setShowConvertModal(false)}>
                취소
              </Button>
              <Button variant="primary" className="flex-1" onClick={handleConvertConfirm}>
                <ShoppingCart className="w-4 h-4" /> 수주전환
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* ★ 수주전환 완료 확인 다이얼로그 */}
      {showConvertCompleteDialog && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[100]">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 overflow-hidden">
            {/* 헤더 */}
            <div className="bg-green-50 px-6 py-4 border-b border-green-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-green-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">수주전환 완료</h3>
                  <p className="text-sm text-gray-600">수주가 성공적으로 생성되었습니다.</p>
                </div>
              </div>
            </div>

            {/* 내용 */}
            <div className="px-6 py-4">
              <div className="bg-gray-50 rounded-lg p-4 space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">수주번호</span>
                  <span className="font-mono font-medium">{convertCompleteInfo.orderNo}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">발주처</span>
                  <span className="font-medium">{convertCompleteInfo.customerName}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">현장</span>
                  <span className="font-medium">{convertCompleteInfo.siteName}</span>
                </div>
                <div className="flex justify-between text-sm border-t pt-2 mt-2">
                  <span className="text-gray-500">금액</span>
                  <span className="font-bold text-blue-600">{convertCompleteInfo.totalAmount?.toLocaleString()}원</span>
                </div>
              </div>
            </div>

            {/* 버튼 */}
            <div className="px-6 py-4 bg-gray-50 border-t flex justify-end gap-2">
              <Button variant="outline" onClick={() => setShowConvertCompleteDialog(false)}>
                닫기
              </Button>
              <Button
                variant="primary"
                onClick={() => {
                  setShowConvertCompleteDialog(false);
                  onNavigate('orders');
                }}
              >
                <FileText className="w-4 h-4" /> 수주 목록 보기
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 견적 등록
const QuoteCreate = ({ onNavigate, onBack, onSave }) => {
  const [formData, setFormData] = useState({
    quoteDate: new Date().toISOString().split('T')[0],
    createdBy: '박판매',
    customerName: '',
    siteName: '',
    manager: '',
    contact: '',
    dueDate: '',
    wingIndex: 50,        // ★ 마구리 날개지수 (기본값 50)
    inspectionFee: 50000, // ★ 검사비 (기본값 50,000원)
    note: '',
  });

  // 유효성 검사 규칙
  const validationRules = {
    customerName: { required: true, label: '발주처', message: '발주처를 선택해주세요.' },
    siteName: { required: true, label: '현장명', message: '현장을 선택해주세요.' },
    dueDate: { required: true, label: '납기일', message: '납기일을 선택해주세요.' },
  };

  const { errors, touched, hasError, getFieldError, validateForm, handleBlur, clearFieldError } = useFormValidation(formData, validationRules);

  const [items, setItems] = useState([{
    id: Date.now(),
    floor: '',
    location: '',
    category: '',
    productName: '',
    width: '',
    height: '',
    guideType: '백면',
    motorPower: '220V',
    controller: '단독제어',
    qty: 1,
  }]);

  // 산출된 품목 리스트 (수식 기반)
  const [calculatedItems, setCalculatedItems] = useState([]);
  const [showCalculatedItems, setShowCalculatedItems] = useState(false);

  const categories = ['스크린', '슬랫', '철재'];
  const products = {
    '스크린': ['스크린 셔터 (표준형)', '스크린 셔터 (방풍형)', '스크린 셔터 (방충형)'],
    '슬랫': ['슬랫 셔터 (일반)', '슬랫 셔터 (단열)'],
    '철재': ['철재 셔터 (일반)', '철재 셔터 (강화)'],
  };
  const guideTypes = ['백면', '측면', '양측'];
  const motorPowers = ['220V', '380V'];
  const controllers = ['없음', '단독제어', '연동제어', '중앙제어'];

  // 샘플 발주처 데이터
  const sampleCustomers = [
    { id: 1, name: '오정건설주식회사', manager: '이담당', contact: '010-1111-2222' },
    { id: 2, name: '서울건축', manager: '김담당', contact: '010-2222-3333' },
    { id: 3, name: '인천건설', manager: '최담당', contact: '010-3333-4444' },
  ];

  // 단가 테이블 (품목코드별 단가)
  const priceTable = {
    'BP-GR-001': { name: '가이드레일', basePrice: 45000, pricePerMm: 15 },
    'BP-GB-001': { name: '하부베이스', basePrice: 25000, pricePerMm: 8 },
    'BP-CS-001': { name: '케이스', basePrice: 80000, pricePerMm: 25 },
    'BP-SC-001': { name: '측면덮개', basePrice: 15000, pricePerMm: 0 },
    'BP-TC-001': { name: '상부덮개', basePrice: 20000, pricePerMm: 0 },
    'BP-BF-001': { name: '하단마감재', basePrice: 30000, pricePerMm: 10 },
    'BP-BB-001': { name: '하단보강빔바', basePrice: 25000, pricePerMm: 8 },
    'BP-SH-001': { name: '샤프트', basePrice: 35000, pricePerMm: 12 },
    'BP-MT-001': { name: '모터', basePrice: 250000, pricePerMm: 0 },
    'BP-CT-001': { name: '제어기', basePrice: 150000, pricePerMm: 0 },
    'BP-SR-001': { name: '스크린 원단', basePrice: 0, pricePerSqm: 85000 },
    'BP-SB-001': { name: '연기차단재', basePrice: 20000, pricePerMm: 5 },
  };

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleCustomerSelect = (customer) => {
    setFormData(prev => ({
      ...prev,
      customerName: customer.name,
      manager: customer.manager,
      contact: customer.contact,
    }));
  };

  const handleItemChange = (itemId, field, value) => {
    setItems(prev => prev.map(item =>
      item.id === itemId ? { ...item, [field]: value } : item
    ));
    // 입력 변경 시 산출 결과 초기화
    setShowCalculatedItems(false);
  };

  const handleAddItem = () => {
    setItems(prev => [...prev, {
      id: Date.now(),
      floor: '',
      location: '',
      category: '',
      productName: '',
      width: '',
      height: '',
      guideType: '백면',
      motorPower: '220V',
      controller: '단독제어',
      qty: 1,
    }]);
  };

  const handleRemoveItem = (itemId) => {
    if (items.length === 1) {
      alert('최소 1개의 견적 항목이 필요합니다.');
      return;
    }
    setItems(prev => prev.filter(item => item.id !== itemId));
  };

  const handleDuplicateItem = (itemId) => {
    const item = items.find(i => i.id === itemId);
    if (item) {
      setItems(prev => [...prev, { ...item, id: Date.now() }]);
    }
  };

  // 수식 기반 자동 견적 산출
  const calculateQuote = () => {
    const allCalculatedItems = [];
    let totalProductAmount = 0;

    // 각 견적 항목에 대해 수식 실행
    const calculatedItemsDetails = items.map((item, itemIdx) => {
      const W0 = parseInt(item.width) || 2000;
      const H0 = parseInt(item.height) || 2500;
      const QTY = parseInt(item.qty) || 1;
      const GT = item.guideType || '백면';
      const PC = item.category || '스크린';

      // 계산된 변수들
      const W1_스크린 = W0 + 140;
      const H1_스크린 = H0 + 350;
      const W1_철재 = W0 + 110;
      const H1_철재 = H0 + 350;
      const AREA = (W1_스크린 * H1_스크린) / 1000000;
      const GR_L = H0 + 100;
      const GR_BASE = W0 + 60;
      const CASE_L = W0 + 100;
      const SHAFT_L = W0 + 200;
      const SHAFT_D = W0 > 3000 ? 60 : (W0 > 2000 ? 50 : 40);
      const BF_L = W0;

      // 품목 산출
      const outputItems = [];

      // 1. 스크린 원단 (스크린 카테고리인 경우)
      if (PC === '스크린' || PC === '슬랫') {
        const screenPrice = Math.round(AREA * priceTable['BP-SR-001'].pricePerSqm);
        outputItems.push({
          id: `${item.id}-SR`,
          itemCode: 'BP-SR-001',
          itemName: '스크린 원단',
          spec: `${W1_스크린} x ${H1_스크린}mm`,
          length: null,
          area: AREA,
          qty: QTY,
          unit: '㎡',
          unitPrice: priceTable['BP-SR-001'].pricePerSqm,
          amount: screenPrice * QTY,
          process: '스크린',
          floor: item.floor,
          location: item.location,
        });
      }

      // 2. 가이드레일 (절곡)
      const grPrice = priceTable['BP-GR-001'].basePrice + (GR_L * priceTable['BP-GR-001'].pricePerMm / 1000);
      outputItems.push({
        id: `${item.id}-GR`,
        itemCode: 'BP-GR-001',
        itemName: '가이드레일',
        spec: `${GR_L}mm`,
        length: GR_L,
        qty: QTY * 2,
        unit: 'EA',
        unitPrice: Math.round(grPrice),
        amount: Math.round(grPrice * QTY * 2),
        process: '절곡',
        floor: item.floor,
        location: item.location,
      });

      // 3. 하부베이스 (절곡)
      const gbPrice = priceTable['BP-GB-001'].basePrice + (GR_BASE * priceTable['BP-GB-001'].pricePerMm / 1000);
      outputItems.push({
        id: `${item.id}-GB`,
        itemCode: 'BP-GB-001',
        itemName: '하부베이스',
        spec: `${GR_BASE}mm`,
        length: GR_BASE,
        qty: QTY * 2,
        unit: 'EA',
        unitPrice: Math.round(gbPrice),
        amount: Math.round(gbPrice * QTY * 2),
        process: '절곡',
        floor: item.floor,
        location: item.location,
      });

      // 4. 케이스 (절곡)
      const csPrice = priceTable['BP-CS-001'].basePrice + (CASE_L * priceTable['BP-CS-001'].pricePerMm / 1000);
      outputItems.push({
        id: `${item.id}-CS`,
        itemCode: 'BP-CS-001',
        itemName: '케이스',
        spec: `${CASE_L}mm`,
        length: CASE_L,
        qty: QTY,
        unit: 'EA',
        unitPrice: Math.round(csPrice),
        amount: Math.round(csPrice * QTY),
        process: '절곡',
        floor: item.floor,
        location: item.location,
      });

      // 5. 측면덮개 (절곡)
      const sideCoverQty = GT === '백면' ? 2 : 4;
      outputItems.push({
        id: `${item.id}-SC`,
        itemCode: 'BP-SC-001',
        itemName: '측면덮개',
        spec: '-',
        length: null,
        qty: sideCoverQty * QTY,
        unit: 'EA',
        unitPrice: priceTable['BP-SC-001'].basePrice,
        amount: priceTable['BP-SC-001'].basePrice * sideCoverQty * QTY,
        process: '절곡',
        floor: item.floor,
        location: item.location,
      });

      // 6. 상부덮개 (절곡)
      outputItems.push({
        id: `${item.id}-TC`,
        itemCode: 'BP-TC-001',
        itemName: '상부덮개',
        spec: '-',
        length: null,
        qty: QTY,
        unit: 'EA',
        unitPrice: priceTable['BP-TC-001'].basePrice,
        amount: priceTable['BP-TC-001'].basePrice * QTY,
        process: '절곡',
        floor: item.floor,
        location: item.location,
      });

      // 7. 하단마감재 (절곡)
      const bfPrice = priceTable['BP-BF-001'].basePrice + (BF_L * priceTable['BP-BF-001'].pricePerMm / 1000);
      outputItems.push({
        id: `${item.id}-BF`,
        itemCode: 'BP-BF-001',
        itemName: '하단마감재',
        spec: `${BF_L}mm`,
        length: BF_L,
        qty: QTY,
        unit: 'EA',
        unitPrice: Math.round(bfPrice),
        amount: Math.round(bfPrice * QTY),
        process: '절곡',
        floor: item.floor,
        location: item.location,
      });

      // 8. 하단보강빔바 (절곡)
      const bbPrice = priceTable['BP-BB-001'].basePrice + (BF_L * priceTable['BP-BB-001'].pricePerMm / 1000);
      outputItems.push({
        id: `${item.id}-BB`,
        itemCode: 'BP-BB-001',
        itemName: '하단보강빔바',
        spec: `${BF_L}mm`,
        length: BF_L,
        qty: QTY * 2,
        unit: 'EA',
        unitPrice: Math.round(bbPrice),
        amount: Math.round(bbPrice * QTY * 2),
        process: '절곡',
        floor: item.floor,
        location: item.location,
      });

      // 9. 샤프트 (절곡)
      const shPrice = priceTable['BP-SH-001'].basePrice + (SHAFT_L * priceTable['BP-SH-001'].pricePerMm / 1000);
      outputItems.push({
        id: `${item.id}-SH`,
        itemCode: 'BP-SH-001',
        itemName: '샤프트',
        spec: `Ø${SHAFT_D} x ${SHAFT_L}mm`,
        length: SHAFT_L,
        diameter: SHAFT_D,
        qty: QTY,
        unit: 'EA',
        unitPrice: Math.round(shPrice),
        amount: Math.round(shPrice * QTY),
        process: '절곡',
        floor: item.floor,
        location: item.location,
      });

      // 10. 연기차단재 (스크린)
      const sbPrice = priceTable['BP-SB-001'].basePrice + (GR_L * priceTable['BP-SB-001'].pricePerMm / 1000);
      outputItems.push({
        id: `${item.id}-SB`,
        itemCode: 'BP-SB-001',
        itemName: '연기차단재',
        spec: `${GR_L}mm`,
        length: GR_L,
        qty: QTY * 2,
        unit: 'EA',
        unitPrice: Math.round(sbPrice),
        amount: Math.round(sbPrice * QTY * 2),
        process: '스크린',
        floor: item.floor,
        location: item.location,
      });

      // 11. 모터
      outputItems.push({
        id: `${item.id}-MT`,
        itemCode: 'BP-MT-001',
        itemName: '모터',
        spec: item.motorPower,
        length: null,
        qty: QTY,
        unit: 'EA',
        unitPrice: priceTable['BP-MT-001'].basePrice,
        amount: priceTable['BP-MT-001'].basePrice * QTY,
        process: '전기',
        floor: item.floor,
        location: item.location,
      });

      // 12. 제어기 (있는 경우만)
      if (item.controller && item.controller !== '없음') {
        outputItems.push({
          id: `${item.id}-CT`,
          itemCode: 'BP-CT-001',
          itemName: '제어기',
          spec: item.controller,
          length: null,
          qty: QTY,
          unit: 'EA',
          unitPrice: priceTable['BP-CT-001'].basePrice,
          amount: priceTable['BP-CT-001'].basePrice * QTY,
          process: '전기',
          floor: item.floor,
          location: item.location,
        });
      }

      // 항목별 합계
      const itemTotal = outputItems.reduce((sum, o) => sum + o.amount, 0);

      // 검사비는 기본정보에서 가져옴 (전체 견적에 1회 적용)
      const inspectionAmount = itemIdx === 0 ? (formData.inspectionFee || 0) : 0;

      allCalculatedItems.push(...outputItems);
      totalProductAmount += itemTotal;

      return {
        ...item,
        calculatedVariables: { W0, H0, W1_스크린, H1_스크린, W1_철재, H1_철재, AREA, GR_L, CASE_L, SHAFT_L, SHAFT_D },
        outputItems,
        itemTotal,
        inspectionAmount,
        wingIndex: formData.wingIndex, // 기본정보에서 가져옴
        totalAmount: itemTotal + inspectionAmount,
      };
    });

    // items 업데이트
    setItems(calculatedItemsDetails.map(d => ({
      ...d,
      unitPrice: d.itemTotal,
      amount: d.totalAmount,
    })));

    setCalculatedItems(allCalculatedItems);
    setShowCalculatedItems(true);
  };

  const handleSubmit = () => {
    // 유효성 검사 실행
    if (!validateForm()) {
      return;
    }

    if (!showCalculatedItems) {
      alert('먼저 견적을 산출해주세요.');
      return;
    }

    // 견적번호 생성 - 채번관리 규칙 적용
    const quoteNo = generateNumber('견적번호', null, [], new Date(formData.quoteDate));

    const totalAmount = items.reduce((sum, item) => sum + (item.amount || 0), 0);

    // BOM 데이터 생성 (기존 형식 유지)
    const bomData = generateBomData(items);

    const newQuote = {
      id: Date.now(),
      quoteNo,
      ...formData,
      status: '최초작성',
      totalAmount,
      qty: items.reduce((sum, item) => sum + (item.qty || 0), 0),
      productName: items[0]?.productName || '-',
      productCode: items[0]?.productCode || '-',
      items,
      // 수식 기반 산출 품목 리스트 추가
      calculatedItems,
      bomData,
    };

    onSave?.(newQuote);
    onBack();
  };

  // 공정별 품목 그룹화
  const groupedByProcess = calculatedItems.reduce((acc, item) => {
    const process = item.process || '기타';
    if (!acc[process]) acc[process] = [];
    acc[process].push(item);
    return acc;
  }, {});

  const processColors = {
    '스크린': 'bg-green-100 text-green-700',
    '절곡': 'bg-orange-100 text-orange-700',
    '전기': 'bg-blue-100 text-blue-700',
    '기타': 'bg-gray-100 text-gray-700',
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button onClick={onBack} className="p-2 hover:bg-gray-100 rounded-lg">
            <ArrowLeft className="w-5 h-5 text-gray-500" />
          </button>
          <FileText className="w-6 h-6 text-blue-500" />
          <h1 className="text-xl font-bold text-gray-900">견적 등록</h1>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={onBack}>취소</Button>
          <Button variant="primary" onClick={handleSubmit}>
            <Check className="w-4 h-4" /> 저장
          </Button>
        </div>
      </div>

      {/* 기본 정보 */}
      <Card title="기본 정보">
        <div className="grid grid-cols-3 gap-4">
          <FormField label="등록일">
            <input
              type="date"
              value={formData.quoteDate}
              onChange={(e) => handleChange('quoteDate', e.target.value)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50"
              readOnly
            />
          </FormField>
          <FormField label="작성자">
            <input
              type="text"
              value={formData.createdBy}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50"
              readOnly
            />
          </FormField>
          <FormField label="발주처 선택" required error={hasError('customerName')} errorMessage={getFieldError('customerName')}>
            <select
              value={formData.customerName}
              onChange={(e) => {
                const customer = sampleCustomers.find(c => c.name === e.target.value);
                if (customer) {
                  handleCustomerSelect(customer);
                  clearFieldError('customerName');
                }
              }}
              onBlur={() => handleBlur('customerName')}
              className={getInputClassName(hasError('customerName'))}
            >
              <option value="">발주처를 선택하세요</option>
              {sampleCustomers.map(c => (
                <option key={c.id} value={c.name}>{c.name} - {c.manager}</option>
              ))}
            </select>
          </FormField>
          <FormField label="현장명" required error={hasError('siteName')} errorMessage={getFieldError('siteName')}>
            <select
              value={formData.siteName}
              onChange={(e) => {
                handleChange('siteName', e.target.value);
                clearFieldError('siteName');
              }}
              onBlur={() => handleBlur('siteName')}
              className={getInputClassName(hasError('siteName'))}
            >
              <option value="">현장을 선택하세요</option>
              <option value="강남 오피스텔 현장">강남 오피스텔 현장</option>
              <option value="송도 아파트 현장">송도 아파트 현장</option>
              <option value="판교 빌딩 현장">판교 빌딩 현장</option>
            </select>
          </FormField>
          <FormField label="발주 담당자">
            <TextInput
              value={formData.manager}
              onChange={(val) => handleChange('manager', val)}
              placeholder="담당자명"
            />
          </FormField>
          <FormField label="연락처">
            <TextInput
              value={formData.contact}
              onChange={(val) => handleChange('contact', val)}
              placeholder="010-0000-0000"
            />
          </FormField>
          <FormField label="납기일" required error={hasError('dueDate')} errorMessage={getFieldError('dueDate')}>
            <input
              type="date"
              value={formData.dueDate}
              onChange={(e) => {
                handleChange('dueDate', e.target.value);
                clearFieldError('dueDate');
              }}
              onBlur={() => handleBlur('dueDate')}
              className={getInputClassName(hasError('dueDate'))}
            />
          </FormField>
          <div className="col-span-3">
            <FormField label="비고">
              <TextInput
                value={formData.note}
                onChange={(val) => handleChange('note', val)}
                placeholder="특이사항을 입력하세요"
              />
            </FormField>
          </div>
        </div>
      </Card>

      {/* 자동 견적 산출 - 입력 */}
      <Card
        title="자동 견적 산출"
        subtitle="입력값을 기반으로 견적을 자동으로 산출합니다"
      >
        <div className="space-y-4">
          {items.map((item, idx) => (
            <div key={item.id} className="p-4 border rounded-lg bg-gray-50">
              {/* 모바일/태블릿: 견적번호+버튼 상단, 필드 아래 / 데스크탑: 한 줄 */}

              {/* 견적번호 + 버튼 (모바일/태블릿에서만 표시) */}
              <div className="flex items-center justify-between mb-3 xl:hidden">
                <span className="px-3 py-2 bg-blue-100 text-blue-700 rounded-lg text-sm font-medium">
                  견적 {idx + 1}
                </span>
                <div className="flex items-center gap-1">
                  <button
                    onClick={() => handleDuplicateItem(item.id)}
                    className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
                    title="복사"
                  >
                    <Copy className="w-4 h-4 text-gray-500" />
                  </button>
                  <button
                    onClick={() => handleRemoveItem(item.id)}
                    className="p-2 hover:bg-red-100 rounded-lg transition-colors"
                    title="삭제"
                  >
                    <Trash2 className="w-4 h-4 text-red-500" />
                  </button>
                </div>
              </div>

              {/* 입력 필드들 - 반응형 그리드 */}
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 xl:grid-cols-12 gap-2">
                {/* 견적 번호 (데스크탑에서만 표시) */}
                <div className="hidden xl:flex items-end pb-1">
                  <span className="px-3 py-2 bg-blue-100 text-blue-700 rounded-lg text-sm font-medium whitespace-nowrap">
                    견적 {idx + 1}
                  </span>
                </div>
                <FormField label="층수">
                  <TextInput
                    value={item.floor}
                    onChange={(val) => handleItemChange(item.id, 'floor', val)}
                    placeholder="1층"
                  />
                </FormField>
                <FormField label="부호">
                  <TextInput
                    value={item.location}
                    onChange={(val) => handleItemChange(item.id, 'location', val)}
                    placeholder="A"
                  />
                </FormField>
                <FormField label="제품카테고리(PC)" required>
                  <select
                    value={item.category}
                    onChange={(e) => handleItemChange(item.id, 'category', e.target.value)}
                    className="w-full px-2 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  >
                    <option value="">선택</option>
                    {categories.map(c => (
                      <option key={c} value={c}>{c}</option>
                    ))}
                  </select>
                </FormField>
                <FormField label="제품명" required>
                  <select
                    value={item.productName}
                    onChange={(e) => handleItemChange(item.id, 'productName', e.target.value)}
                    className="w-full px-2 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                    disabled={!item.category}
                  >
                    <option value="">선택</option>
                    {item.category && products[item.category]?.map(p => (
                      <option key={p} value={p}>{p}</option>
                    ))}
                  </select>
                </FormField>
                <FormField label="가로(W0)" required>
                  <TextInput
                    type="number"
                    value={item.width}
                    onChange={(val) => handleItemChange(item.id, 'width', val)}
                    placeholder="2000"
                  />
                </FormField>
                <FormField label="세로(H0)" required>
                  <TextInput
                    type="number"
                    value={item.height}
                    onChange={(val) => handleItemChange(item.id, 'height', val)}
                    placeholder="2500"
                  />
                </FormField>
                <FormField label="설치유형(GT)" required>
                  <select
                    value={item.guideType}
                    onChange={(e) => handleItemChange(item.id, 'guideType', e.target.value)}
                    className="w-full px-2 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  >
                    <option value="">선택</option>
                    {guideTypes.map(g => (
                      <option key={g} value={g}>{g}</option>
                    ))}
                  </select>
                </FormField>
                <FormField label="모터전원(MP)" required>
                  <select
                    value={item.motorPower}
                    onChange={(e) => handleItemChange(item.id, 'motorPower', e.target.value)}
                    className="w-full px-2 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  >
                    <option value="">선택</option>
                    {motorPowers.map(m => (
                      <option key={m} value={m}>{m}</option>
                    ))}
                  </select>
                </FormField>
                <FormField label="제어기(CT)" required>
                  <select
                    value={item.controller}
                    onChange={(e) => handleItemChange(item.id, 'controller', e.target.value)}
                    className="w-full px-2 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  >
                    <option value="">선택</option>
                    {controllers.map(c => (
                      <option key={c} value={c}>{c}</option>
                    ))}
                  </select>
                </FormField>
                <FormField label="수량(QTY)" required>
                  <input
                    type="number"
                    value={item.qty}
                    onChange={(e) => handleItemChange(item.id, 'qty', parseInt(e.target.value) || 1)}
                    min="1"
                    className="w-full px-2 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  />
                </FormField>
                {/* 복사/삭제 버튼 (데스크탑에서만 표시) */}
                <div className="hidden xl:flex items-end gap-1 justify-end pb-1">
                  <button
                    onClick={() => handleDuplicateItem(item.id)}
                    className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
                    title="복사"
                  >
                    <Copy className="w-4 h-4 text-gray-500" />
                  </button>
                  <button
                    onClick={() => handleRemoveItem(item.id)}
                    className="p-2 hover:bg-red-100 rounded-lg transition-colors"
                    title="삭제"
                  >
                    <Trash2 className="w-4 h-4 text-red-500" />
                  </button>
                </div>
              </div>

              {item.amount && (
                <div className="mt-4 pt-4 border-t flex justify-between items-center">
                  <span className="text-sm text-gray-500">
                    산출 품목: {item.outputItems?.length || 0}개
                  </span>
                  <span className="text-lg font-bold text-blue-600">
                    {item.amount.toLocaleString()}원
                  </span>
                </div>
              )}
            </div>
          ))}

          <button
            onClick={handleAddItem}
            className="w-full py-3 border-2 border-dashed border-gray-300 rounded-lg text-gray-500 hover:border-blue-400 hover:text-blue-500 transition-colors flex items-center justify-center gap-2"
          >
            <Plus className="w-5 h-5" /> 견적 추가
          </button>
        </div>
      </Card>

      {/* 자동 견적 산출 버튼 */}
      <Button
        variant="primary"
        className="w-full py-4"
        onClick={calculateQuote}
      >
        <Calculator className="w-5 h-5" />
        자동 견적 산출 ({items.length}개 항목)
      </Button>

      {/* 산출 결과 - 공정별 품목 리스트 */}
      {showCalculatedItems && calculatedItems.length > 0 && (
        <Card
          title="산출 결과"
          subtitle={`총 ${calculatedItems.length}개 품목이 산출되었습니다`}
        >
          <div className="space-y-6">
            {/* 공정별 그룹 */}
            {Object.entries(groupedByProcess).map(([process, processItems]) => (
              <div key={process} className="border rounded-lg overflow-hidden">
                <div className={`px-4 py-2 flex items-center justify-between ${processColors[process] || 'bg-gray-100'}`}>
                  <div className="flex items-center gap-2">
                    <span className="font-medium">{process} 공정</span>
                    <span className="text-xs">({processItems.length}개 품목)</span>
                  </div>
                  <span className="font-bold">
                    {processItems.reduce((sum, i) => sum + i.amount, 0).toLocaleString()}원
                  </span>
                </div>
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">품목</th>
                      <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">규격</th>
                      <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">수량</th>
                      <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">단가</th>
                      <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">금액</th>
                      <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">위치</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {processItems.map(item => (
                      <tr key={item.id} className="hover:bg-gray-50">
                        <td className="px-3 py-2 text-sm">{item.itemName}</td>
                        <td className="px-3 py-2 text-sm font-mono">{item.spec}</td>
                        <td className="px-3 py-2 text-sm text-right">{item.qty} {item.unit}</td>
                        <td className="px-3 py-2 text-sm text-right">{item.unitPrice.toLocaleString()}</td>
                        <td className="px-3 py-2 text-sm text-right font-medium">{item.amount.toLocaleString()}</td>
                        <td className="px-3 py-2 text-sm text-gray-500">{item.floor} {item.location}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ))}

            {/* 합계 */}
            <div className="flex items-center justify-between p-4 bg-blue-50 rounded-lg">
              <div>
                <span className="text-gray-600">총 견적금액</span>
                <p className="text-xs text-gray-500">({calculatedItems.length}개 품목)</p>
              </div>
              <span className="text-2xl font-bold text-blue-600">
                {items.reduce((sum, item) => sum + (item.amount || 0), 0).toLocaleString()}원
              </span>
            </div>
          </div>
        </Card>
      )}
    </div>
  );
};

// ============ 수주 관리 ============

// 수주 목록
const OrderList = ({ orders, shipments = [], workOrders = [], onNavigate, onCreateWorkOrders, onDeleteOrders, onCancelOrder }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [showWOCreateModal, setShowWOCreateModal] = useState(false);
  const [selectedOrderForWO, setSelectedOrderForWO] = useState(null);
  const { isMobile, isTablet, isDesktop } = useResponsive();

  // 체크박스 선택 상태
  const [selectedIds, setSelectedIds] = useState([]);
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  // 수주 취소 모달 상태
  const [showCancelModal, setShowCancelModal] = useState(false);
  const [cancelTargetOrder, setCancelTargetOrder] = useState(null);
  const [cancelReason, setCancelReason] = useState('');
  const [cancelReasonDetail, setCancelReasonDetail] = useState('');

  // 전체 선택/해제
  const handleSelectAll = (e) => {
    if (e.target.checked) {
      setSelectedIds(filtered.map(o => o.id));
    } else {
      setSelectedIds([]);
    }
  };

  // 개별 선택
  const handleSelectOne = (id, e) => {
    e.stopPropagation();
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  };

  // 삭제 확인
  const handleDeleteConfirm = () => {
    if (onDeleteOrders && selectedIds.length > 0) {
      onDeleteOrders(selectedIds);
    }
    setSelectedIds([]);
    setShowDeleteModal(false);
  };

  // 수주에 연결된 작업지시 찾기
  const getWorkOrdersByOrder = (order) => {
    return workOrders.filter(wo => wo.orderNo === order.orderNo);
  };

  // 작업지시 클릭 핸들러 (수주 -> 바로 작업지시)
  const handleWorkOrderClick = (e, order) => {
    e.stopPropagation();
    const existingWOs = getWorkOrdersByOrder(order);
    if (existingWOs.length > 0) {
      // 이미 작업지시가 있으면 작업지시 관리 페이지로 이동
      onNavigate('work-order-list');
    } else if (order.status === '수주확정') {
      // 수주확정 상태이면 작업지시 생성 모달 표시
      setSelectedOrderForWO(order);
      setShowWOCreateModal(true);
    }
  };

  // 작업지시 생성 확인 (공정별 자동 생성)
  const handleConfirmCreateWO = () => {
    if (selectedOrderForWO && onCreateWorkOrders) {
      onCreateWorkOrders(selectedOrderForWO);
    }
    setShowWOCreateModal(false);
    setSelectedOrderForWO(null);
  };

  const tabs = [
    { id: 'all', label: '전체', count: orders.length },
    { id: 'registered', label: '수주등록', count: orders.filter(o => o.status === '수주등록').length },
    { id: 'confirmed', label: '수주확정', count: orders.filter(o => o.status === '수주확정').length },
    { id: 'production-complete', label: '생산지시완료', count: orders.filter(o => o.status === '생산지시완료').length },
    { id: 'cancelled', label: '취소', count: orders.filter(o => o.status === '취소').length },
  ];

  const statusFilter = {
    all: () => true,
    registered: (o) => o.status === '수주등록',
    confirmed: (o) => o.status === '수주확정',
    'production-complete': (o) => o.status === '생산지시완료',
    cancelled: (o) => o.status === '취소',
  };

  // 취소 가능 여부 확인 (생산지시완료 전까지만 취소 가능)
  const canCancelOrder = (order) => {
    const nonCancellableStatuses = ['생산지시완료', '출하대기', '출하완료', '취소'];
    return !nonCancellableStatuses.includes(order.status);
  };

  // 취소 버튼 클릭 핸들러
  const handleCancelClick = (e, order) => {
    e.stopPropagation();
    if (!canCancelOrder(order)) {
      alert('생산지시 완료 후에는 취소할 수 없습니다.');
      return;
    }
    setCancelTargetOrder(order);
    setCancelReason('');
    setCancelReasonDetail('');
    setShowCancelModal(true);
  };

  // 취소 확인 핸들러
  const handleCancelConfirm = () => {
    if (!cancelReason) {
      alert('취소 사유를 선택해주세요.');
      return;
    }
    if (cancelTargetOrder && onCancelOrder) {
      onCancelOrder(cancelTargetOrder.id, {
        reason: cancelReason,
        reasonDetail: cancelReasonDetail,
        cancelledAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
        cancelledBy: '현재 사용자',
      });
    }
    setShowCancelModal(false);
    setCancelTargetOrder(null);
    setCancelReason('');
    setCancelReasonDetail('');
  };

  const filtered = orders
    .filter(statusFilter[activeTab])
    .filter(o =>
      o.orderNo.toLowerCase().includes(search.toLowerCase()) ||
      o.customerName.includes(search) ||
      o.siteName.includes(search)
    )
    .sort((a, b) => b.id - a.id); // ID 기준 내림차순 (최신 등록 최상단)

  // 출하진행률 계산 헬퍼 (출하 데이터에서 직접 조회)
  const getShipmentPercentByOrder = (order) => {
    if (!order.splits || order.splits.length === 0) {
      return order.status === '출하완료' ? 100 : 0;
    }

    const completed = order.splits.filter(split => {
      // 해당 분할의 출하 상태를 shipments에서 찾아서 확인
      const shipment = shipments.find(s => s.splitNo === split.splitNo);
      return shipment?.status === '배송완료';
    }).length;

    return Math.round((completed / order.splits.length) * 100);
  };

  // 수주관리 핵심 통계
  const thisMonthAmount = orders.reduce((sum, o) => sum + o.totalAmount, 0);
  // 생산지시 대기: 분할 완료됐는데 생산지시 안 된 건
  const productionPending = orders.filter(o =>
    o.splits?.length > 0 &&
    o.splits.some(s => !s.productionStatus || s.productionStatus === '미지시')
  ).length;
  // 출하 대기: 출하진행 0% 건수 (shipments 데이터 기준)
  const shipmentPending = orders.filter(o => {
    if (o.status === '출하완료') return false;
    if (!o.splits || o.splits.length === 0) return false;
    return getShipmentPercentByOrder(o) === 0;
  }).length;
  const needSplit = orders.filter(o =>
    (!o.splits || o.splits.length === 0) && o.status === '수주확정'
  ).length;

  // 분할 정보 표시 헬퍼
  const getSplitInfo = (order) => {
    if (!order.splits || order.splits.length === 0) return '-';
    return `${order.splits.length}차분할`;
  };

  // 출하진행 표시 헬퍼 (텍스트용)
  const getShipmentProgress = (order) => {
    if (!order.splits || order.splits.length === 0) {
      return order.status === '출하완료' ? '완료' : '-';
    }
    const completed = order.splits.filter(split => {
      const shipment = shipments.find(s => s.splitNo === split.splitNo);
      return shipment?.status === '배송완료';
    }).length;
    const total = order.splits.length;
    if (completed === 0) return '-';
    if (completed === total) return '완료';
    return `${completed}/${total}`;
  };

  // 생산지시 상태 표시 헬퍼
  const getProductionStatus = (order) => {
    if (!order.splits || order.splits.length === 0) {
      return order.status === '수주확정' ? '대기' : '-';
    }
    const instructed = order.splits.filter(s => s.productionStatus && s.productionStatus !== '미지시').length;
    const total = order.splits.length;
    if (instructed === 0) return '대기';
    if (instructed === total) return '완료';
    return `${instructed}/${total}`;
  };

  // 주문과 연결된 출하 정보 가져오기 (출고예정일, 배송방식, 출하상태)
  const getShipmentInfoByOrder = (order) => {
    // 분할이 있으면 첫 번째 분할의 출하 정보 반환
    if (order.splits && order.splits.length > 0) {
      const shipment = shipments.find(s => s.splitNo === order.splits[0].splitNo || s.lotNo === order.orderNo);
      if (shipment) {
        return {
          shipmentDate: shipment.shipmentDate,
          deliveryMethod: shipment.deliveryMethod,
          status: shipment.status
        };
      }
    }
    // 분할이 없으면 로트번호로 직접 조회
    const shipment = shipments.find(s => s.lotNo === order.orderNo);
    if (shipment) {
      return {
        shipmentDate: shipment.shipmentDate,
        deliveryMethod: shipment.deliveryMethod,
        status: shipment.status
      };
    }
    // 출하 데이터가 없으면 수주 데이터의 scheduledShipDate, deliveryMethod 사용
    return {
      shipmentDate: order.scheduledShipDate || null,
      deliveryMethod: order.deliveryMethod || null,
      status: null
    };
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <PageHeader
        icon={Package}
        title="수주 목록"
        actions={
          <Button variant="primary" onClick={() => onNavigate('order-create')}>
            <Plus className="w-4 h-4" /> 수주 등록
          </Button>
        }
      />

      {/* 리포트 카드 (4개, 한 줄) */}
      <div className="grid grid-cols-4 gap-4">
        <DashboardCard
          icon={DollarSign}
          title="이번 달 수주"
          value={`${thisMonthAmount.toLocaleString()}원`}
          color="blue"
        />
        <DashboardCard
          icon={GitBranch}
          title="분할 대기"
          value={`${needSplit}건`}
          color="orange"
        />
        <DashboardCard
          icon={Factory}
          title="생산지시 대기"
          value={`${productionPending}건`}
          color="green"
        />
        <DashboardCard
          icon={Truck}
          title="출하 대기"
          value={`${shipmentPending}건`}
          color="purple"
        />
      </div>

      {/* 검색바 (전체 너비, 한 줄) */}
      <SearchInput
        placeholder="로트번호, 견적번호, 발주처, 현장명 검색..."
        value={search}
        onChange={setSearch}
      />

      {/* 탭 필터 - 모바일에서는 스크롤 */}
      {!isMobile && (
        <TabFilter tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />
      )}

      {/* 데스크탑: 테이블 뷰 */}
      {isDesktop && (
        <div className="bg-white rounded-xl border overflow-hidden">
          {/* 선택 삭제 버튼 (2개 이상 선택 시) */}
          {selectedIds.length >= 2 && (
            <div className="px-4 py-3 bg-gray-50 border-b flex items-center justify-between">
              <span className="text-sm text-gray-600">
                {selectedIds.length}개 항목 선택됨
              </span>
              <button
                onClick={() => setShowDeleteModal(true)}
                className="px-4 py-2 bg-red-600 text-white text-sm rounded-lg hover:bg-red-700 flex items-center gap-2"
              >
                <Trash2 className="w-4 h-4" />
                선택 삭제({selectedIds.length})
              </button>
            </div>
          )}
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500 w-12">
                  <input
                    type="checkbox"
                    className="rounded"
                    checked={filtered.length > 0 && selectedIds.length === filtered.length}
                    onChange={handleSelectAll}
                  />
                </th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">번호</th>
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">로트번호</th>
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">견적번호</th>
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">발주처</th>
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">현장명</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">상태</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">출고예정일</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">배송방식</th>
                {/* 작업 컬럼 (1개 선택 시에만 헤더 표시) */}
                {selectedIds.length === 1 && (
                  <th className="px-3 py-3 text-center text-xs font-medium text-gray-500 w-24">작업</th>
                )}
              </tr>
            </thead>
            <tbody className="divide-y">
              {filtered.map((order, idx) => {
                // 분할 표시
                const hasSplit = order.splits?.length > 0;

                // 작업지시 상태 (workOrders에서 직접 확인)
                const existingWOs = getWorkOrdersByOrder(order);
                const hasWorkOrder = existingWOs.length > 0;
                const productionStatus = getProductionStatus(order);
                const isProductionComplete = productionStatus === '완료';

                // 출하 정보 (출고예정일, 배송방식, 출하상태)
                const shipmentInfo = getShipmentInfoByOrder(order);

                const isSelected = selectedIds.includes(order.id);
                const isOnlySelected = selectedIds.length === 1 && isSelected;

                return (
                  <tr
                    key={order.id}
                    className={`hover:bg-gray-50 cursor-pointer ${isSelected ? 'bg-blue-50' : ''}`}
                    onClick={() => onNavigate('order-detail', order)}
                  >
                    <td className="px-3 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                      <input
                        type="checkbox"
                        className="rounded"
                        checked={isSelected}
                        onChange={(e) => handleSelectOne(order.id, e)}
                      />
                    </td>
                    <td className="px-3 py-3 text-center text-sm text-gray-500">
                      {filtered.length - idx}
                    </td>
                    <td className="px-3 py-3">
                      <span className="text-sm font-mono text-blue-600">{order.orderNo}</span>
                      {order.parentLotNo && (
                        <span className="block text-xs text-gray-400">← {order.parentLotNo}</span>
                      )}
                    </td>
                    <td className="px-3 py-3 text-sm">
                      {order.quoteNo ? (
                        <span className="text-blue-600 cursor-pointer hover:underline">{order.quoteNo}</span>
                      ) : (
                        <span className="text-gray-400">-</span>
                      )}
                    </td>
                    <td className="px-3 py-3 text-sm text-gray-900">{order.customerName}</td>
                    <td className="px-3 py-3 text-sm text-gray-900 max-w-[180px] truncate">{order.siteName}</td>
                    <td className="px-3 py-3 text-center"><StatusBadge status={order.status} /></td>
                    {/* 출고예정일 */}
                    <td className="px-3 py-3 text-center text-sm">
                      {shipmentInfo.shipmentDate ? (
                        <span className="text-gray-700">{shipmentInfo.shipmentDate}</span>
                      ) : (
                        <span className="text-gray-400">-</span>
                      )}
                    </td>
                    {/* 배송방식 */}
                    <td className="px-3 py-3 text-center text-sm">
                      {shipmentInfo.deliveryMethod ? (
                        <span className="px-2 py-1 rounded bg-gray-100 text-gray-700 text-xs">{shipmentInfo.deliveryMethod}</span>
                      ) : (
                        <span className="text-gray-400">-</span>
                      )}
                    </td>
                    {/* 작업 컬럼 (1개만 선택된 경우에만 표시) */}
                    {selectedIds.length === 1 && (
                      <td className="px-3 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                        {isOnlySelected && (
                          <div className="flex items-center justify-center gap-1">
                            <button
                              onClick={() => onNavigate('order-edit', order)}
                              className="p-1.5 text-blue-600 hover:bg-blue-50 rounded transition-colors"
                              title="수정"
                            >
                              <Edit2 className="w-4 h-4" />
                            </button>
                            {/* 취소 버튼 - 취소 가능한 상태에서만 표시 */}
                            {canCancelOrder(order) && (
                              <button
                                onClick={(e) => handleCancelClick(e, order)}
                                className="p-1.5 text-orange-600 hover:bg-orange-50 rounded transition-colors"
                                title="취소"
                              >
                                <XCircle className="w-4 h-4" />
                              </button>
                            )}
                            <button
                              onClick={() => setShowDeleteModal(true)}
                              className="p-1.5 text-red-600 hover:bg-red-50 rounded transition-colors"
                              title="삭제"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        )}
                      </td>
                    )}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {/* 태블릿: 카드 그리드 (3열) */}
      {isTablet && (
        <div className="grid grid-cols-3 gap-4">
          {filtered.map((order) => (
            <OrderCard
              key={order.id}
              order={{
                ...order,
                productionOrdered: getProductionStatus(order) === '완료',
              }}
              onClick={() => onNavigate('order-detail', order)}
            />
          ))}
        </div>
      )}

      {/* 모바일: 카드 리스트 (1열) */}
      {isMobile && (
        <div className="space-y-4">
          {filtered.map((order) => (
            <OrderCard
              key={order.id}
              order={{
                ...order,
                productionOrdered: getProductionStatus(order) === '완료',
              }}
              onClick={() => onNavigate('order-detail', order)}
            />
          ))}
        </div>
      )}

      {/* 검색 결과 없음 */}
      {filtered.length === 0 && (
        <div className="text-center py-12 text-gray-500">
          <Package className="w-12 h-12 mx-auto mb-3 text-gray-300" />
          <p>검색 결과가 없습니다.</p>
        </div>
      )}

      {/* 작업지시 생성 모달 */}
      {showWOCreateModal && selectedOrderForWO && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-lg w-full">
            <div className="p-6 border-b">
              <h3 className="text-lg font-bold flex items-center gap-2">
                <ClipboardList className="w-5 h-5 text-blue-600" />
                작업지시 자동 생성
              </h3>
            </div>
            <div className="p-6">
              <div className="mb-4 p-3 bg-gray-50 rounded-lg">
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div className="text-gray-500">수주번호</div>
                  <div className="font-mono font-medium">{selectedOrderForWO.orderNo}</div>
                  <div className="text-gray-500">발주처</div>
                  <div className="font-medium">{selectedOrderForWO.customerName}</div>
                  <div className="text-gray-500">현장명</div>
                  <div className="font-medium">{selectedOrderForWO.siteName}</div>
                  <div className="text-gray-500">납기일</div>
                  <div className="font-medium text-red-600">{selectedOrderForWO.dueDate}</div>
                </div>
              </div>
              <p className="text-sm text-gray-600 mb-4">
                이 수주에 대한 작업지시서를 공정별로 자동 생성합니다.<br />
                BOM 품목 기준으로 각 공정(스크린, 절곡, 샤프트, 조립, 검사)에 맞는 작업지시서가 생성됩니다.
              </p>
              <div className="flex items-center gap-2 text-sm text-green-600 bg-green-50 p-3 rounded-lg">
                <Factory className="w-4 h-4" />
                <span>생성 완료 후 작업지시 관리 페이지로 자동 이동합니다.</span>
              </div>
            </div>
            <div className="p-4 border-t bg-gray-50 flex justify-end gap-2">
              <button
                onClick={() => { setShowWOCreateModal(false); setSelectedOrderForWO(null); }}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg"
              >
                취소
              </button>
              <button
                onClick={handleConfirmCreateWO}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
              >
                <ClipboardList className="w-4 h-4" />
                작업지시 생성
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full">
            <div className="p-6 border-b">
              <h3 className="text-lg font-bold flex items-center gap-2 text-red-600">
                <AlertTriangle className="w-5 h-5" />
                삭제 확인
              </h3>
            </div>
            <div className="p-6">
              <p className="text-gray-700 mb-4">
                선택한 <span className="font-bold text-red-600">{selectedIds.length}개</span>의 수주를 삭제하시겠습니까?
              </p>
              <div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700">
                <p className="font-medium mb-1">⚠️ 주의</p>
                <p>삭제된 수주는 복구할 수 없습니다. 관련된 작업지시, 출하정보도 함께 삭제될 수 있습니다.</p>
              </div>
            </div>
            <div className="p-4 border-t bg-gray-50 flex justify-end gap-2">
              <button
                onClick={() => { setShowDeleteModal(false); }}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg"
              >
                취소
              </button>
              <button
                onClick={handleDeleteConfirm}
                className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 flex items-center gap-2"
              >
                <Trash2 className="w-4 h-4" />
                삭제
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 수주 취소 모달 */}
      {showCancelModal && cancelTargetOrder && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full">
            <div className="p-6 border-b">
              <h3 className="text-lg font-bold flex items-center gap-2 text-orange-600">
                <XCircle className="w-5 h-5" />
                수주 취소
              </h3>
            </div>
            <div className="p-6">
              {/* 취소 대상 정보 */}
              <div className="mb-4 p-3 bg-gray-50 rounded-lg">
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div className="text-gray-500">수주번호</div>
                  <div className="font-mono font-medium">{cancelTargetOrder.orderNo}</div>
                  <div className="text-gray-500">발주처</div>
                  <div className="font-medium">{cancelTargetOrder.customerName}</div>
                  <div className="text-gray-500">현장명</div>
                  <div className="font-medium">{cancelTargetOrder.siteName}</div>
                  <div className="text-gray-500">현재 상태</div>
                  <div><StatusBadge status={cancelTargetOrder.status} /></div>
                </div>
              </div>

              {/* 취소 사유 선택 */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  취소 사유 <span className="text-red-500">*</span>
                </label>
                <select
                  value={cancelReason}
                  onChange={(e) => setCancelReason(e.target.value)}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500"
                >
                  <option value="">취소 사유를 선택하세요</option>
                  <option value="고객요청">고객 요청</option>
                  <option value="계약무산">계약 무산</option>
                  <option value="프로젝트연기">프로젝트 연기</option>
                  <option value="중복등록">중복 등록</option>
                  <option value="단가변경">단가 변경으로 인한 재등록</option>
                  <option value="기타">기타</option>
                </select>
              </div>

              {/* 상세 사유 입력 */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  상세 사유
                </label>
                <textarea
                  value={cancelReasonDetail}
                  onChange={(e) => setCancelReasonDetail(e.target.value)}
                  placeholder="취소 사유에 대한 상세 내용을 입력하세요"
                  rows={3}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500"
                />
              </div>

              {/* 경고 메시지 */}
              <div className="bg-orange-50 border border-orange-200 rounded-lg p-3 text-sm text-orange-700">
                <p className="font-medium mb-1">취소 시 유의사항</p>
                <ul className="list-disc list-inside space-y-1">
                  <li>취소된 수주는 목록에서 '취소' 상태로 표시됩니다</li>
                  <li>취소 후에는 수정이 불가능합니다</li>
                  <li>관련된 생산지시가 있는 경우 먼저 생산지시를 취소해야 합니다</li>
                </ul>
              </div>
            </div>
            <div className="p-4 border-t bg-gray-50 flex justify-end gap-2">
              <button
                onClick={() => { setShowCancelModal(false); setCancelTargetOrder(null); }}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg"
              >
                닫기
              </button>
              <button
                onClick={handleCancelConfirm}
                disabled={!cancelReason}
                className={`px-4 py-2 rounded-lg flex items-center gap-2 ${cancelReason
                    ? 'bg-orange-600 text-white hover:bg-orange-700'
                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                  }`}
              >
                <XCircle className="w-4 h-4" />
                취소 확정
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 문서 발송 섹션 컴포넌트
const DocumentSendSection = ({ order }) => {
  const [showSendModal, setShowSendModal] = useState(false);
  const [selectedDocType, setSelectedDocType] = useState('');
  const [sendMethod, setSendMethod] = useState('이메일');
  const [recipient, setRecipient] = useState(order.contact || '');
  const [recipientName, setRecipientName] = useState(order.manager || '');

  const documentTypes = [
    { id: 'contract', name: '수주계약서', description: '로트번호, 현장명, 주문품목 상세내역(개소별 사이즈&품목별 금액)' },
    { id: 'statement', name: '거래명세서', description: '로트번호, 현장명, 개소별 금액(할인율/금액 적용)' },
    { id: 'taxInvoice', name: '세금계산서', description: '전자세금계산서 발행용' },
  ];

  const sendMethods = [
    { id: '이메일', icon: '📧', placeholder: 'example@company.com' },
    { id: '팩스', icon: '📠', placeholder: '02-1234-5678' },
    { id: '카카오톡', icon: '💬', placeholder: '010-1234-5678' },
  ];

  const handleOpenSendModal = (docType) => {
    setSelectedDocType(docType);
    setShowSendModal(true);
  };

  const handleSend = () => {
    alert(`${selectedDocType} 문서가 ${sendMethod}로 발송되었습니다.\n수신: ${recipientName} (${recipient})`);
    setShowSendModal(false);
  };

  return (
    <div className="space-y-6">
      {/* 문서 발송 버튼 */}
      <Card title="문서 발송">
        <div className="grid grid-cols-3 gap-4">
          {documentTypes.map(doc => (
            <div
              key={doc.id}
              className="p-4 border rounded-lg hover:border-blue-300 hover:bg-blue-50 cursor-pointer transition-all"
              onClick={() => handleOpenSendModal(doc.name)}
            >
              <div className="flex items-center justify-between mb-2">
                <span className="font-medium">{doc.name}</span>
                <Send className="w-4 h-4 text-gray-400" />
              </div>
              <p className="text-xs text-gray-500">{doc.description}</p>
              <div className="flex gap-2 mt-3">
                <button
                  className="text-xs px-2 py-1 bg-gray-100 rounded hover:bg-gray-200"
                  onClick={(e) => { e.stopPropagation(); alert('미리보기 기능 준비 중'); }}
                >
                  미리보기
                </button>
                <button
                  className="text-xs px-2 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200"
                  onClick={(e) => { e.stopPropagation(); handleOpenSendModal(doc.name); }}
                >
                  발송
                </button>
              </div>
            </div>
          ))}
        </div>
        <p className="text-sm text-gray-500 mt-4">
          * PDF 형식으로 이메일 / 팩스 / 카카오톡(이미지) 발송
        </p>
      </Card>

      {/* 발송 이력 */}
      <Card title="발송 이력">
        {order.documentHistory?.length > 0 ? (
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">발송일시</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">문서종류</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">발송방법</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">수신자</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">발송자</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">상태</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {order.documentHistory.map(doc => (
                <tr key={doc.id}>
                  <td className="px-4 py-3 text-sm">{doc.sentAt}</td>
                  <td className="px-4 py-3 text-sm font-medium">{doc.docType}</td>
                  <td className="px-4 py-3 text-sm">
                    <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium
                      ${doc.sentMethod === '이메일' ? 'bg-blue-100 text-blue-700' : ''}
                      ${doc.sentMethod === '카카오톡' ? 'bg-yellow-100 text-yellow-700' : ''}
                      ${doc.sentMethod === '팩스' ? 'bg-gray-100 text-gray-700' : ''}
                    `}>
                      {doc.sentMethod}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-sm">{doc.recipient}</td>
                  <td className="px-4 py-3 text-sm text-gray-500">{doc.sentBy}</td>
                  <td className="px-4 py-3">
                    <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-700">
                      {doc.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="text-center py-8 text-gray-500">
            <Send className="w-12 h-12 mx-auto mb-3 text-gray-300" />
            <p>발송된 문서가 없습니다.</p>
          </div>
        )}
      </Card>

      {/* 발송 모달 */}
      {showSendModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-4 border-b sticky top-0 bg-white z-10">
              <h3 className="font-bold text-gray-900">{selectedDocType} 발송</h3>
              <button onClick={() => setShowSendModal(false)} className="p-2 hover:bg-gray-100 rounded-lg">
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            <div className="p-4 space-y-4">
              {/* 문서 정보 */}
              <div className="p-3 bg-gray-50 rounded-lg">
                <p className="text-sm text-gray-600">
                  로트번호: <span className="font-mono">{order.orderNo}</span>
                </p>
                <p className="text-sm text-gray-600">
                  현장: {order.siteName}
                </p>
              </div>

              {/* 발송 방법 선택 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">발송 방법</label>
                <div className="flex gap-2">
                  {sendMethods.map(method => (
                    <button
                      key={method.id}
                      onClick={() => setSendMethod(method.id)}
                      className={`flex-1 p-3 rounded-lg border text-center transition-all ${sendMethod === method.id
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 hover:border-gray-300'
                        }`}
                    >
                      <span className="text-xl">{method.icon}</span>
                      <p className="text-sm mt-1">{method.id}</p>
                    </button>
                  ))}
                </div>
              </div>

              {/* 수신자 정보 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">수신자명</label>
                <input
                  type="text"
                  value={recipientName}
                  onChange={(e) => setRecipientName(e.target.value)}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
                  placeholder="담당자명"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {sendMethod === '이메일' ? '이메일 주소' : sendMethod === '팩스' ? '팩스 번호' : '휴대폰 번호'}
                </label>
                <input
                  type="text"
                  value={recipient}
                  onChange={(e) => setRecipient(e.target.value)}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
                  placeholder={sendMethods.find(m => m.id === sendMethod)?.placeholder}
                />
              </div>

              {/* 미리보기 버튼 */}
              <button className="w-full py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 flex items-center justify-center gap-2">
                <Eye className="w-4 h-4" /> 문서 미리보기
              </button>
            </div>

            <div className="flex gap-2 p-4 border-t bg-gray-50 rounded-b-xl">
              <Button variant="outline" className="flex-1" onClick={() => setShowSendModal(false)}>취소</Button>
              <Button variant="primary" className="flex-1" onClick={handleSend}>
                <Send className="w-4 h-4" /> 발송
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 수주 상세
const OrderDetail = ({ order, productionOrders = [], customers = [], onNavigate, onBack, onUpdate, onCreateWorkOrder, onCreateProductionOrder, onCancelOrder }) => {
  const [activeDocTab, setActiveDocTab] = useState('contract'); // 계약서, 거래명세서, 발주서
  const [showSplitModal, setShowSplitModal] = useState(false);
  const [showProductionModal, setShowProductionModal] = useState(false);
  const [showPOCreateModal, setShowPOCreateModal] = useState(false);
  // ★ 문서 출력 모달 상태
  const [showDocumentModal, setShowDocumentModal] = useState(false);
  const [documentType, setDocumentType] = useState('contract'); // contract, statement, purchaseOrder
  const [showProductionSheet, setShowProductionSheet] = useState(false);
  const [sheetTitle, setSheetTitle] = useState('수주서');
  // ★ 생산지시 완료 확인 다이얼로그 상태
  const [showProductionCompleteDialog, setShowProductionCompleteDialog] = useState(false);
  const [productionCompleteInfo, setProductionCompleteInfo] = useState({ workOrders: [], splitNo: null });
  const [splitForm, setSplitForm] = useState({
    splitType: '개소별',
    dueDate: '',
    selectedItems: [],
  });
  // ★ 수주 취소 모달 상태
  const [showCancelModal, setShowCancelModal] = useState(false);
  const [cancelReason, setCancelReason] = useState('');
  const [cancelReasonDetail, setCancelReasonDetail] = useState('');

  // order가 없으면 early return (모든 hooks 이후에 배치)
  if (!order) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-gray-500">수주 정보를 불러오는 중...</div>
      </div>
    );
  }

  // 해당 수주의 생산지시 조회
  const relatedPO = productionOrders.find(po => po.orderNo === order.orderNo);

  // ★ 거래처 정보 조회 (결제조건 확인용)
  const customer = customers.find(c => c.name === order?.customerName) || {};
  const paymentTerms = customer.paymentTerms || '월말마감익월25일';
  const isPrePayment = paymentTerms === '입금후출고';
  const isPaid = order?.paymentStatus === '입금완료' || order?.accountingStatus === '입금확인';

  // ★ 문서 발행 가능 여부 체크
  const canIssueStatement = () => {
    // 입금후출고 조건이면 입금 확인 후에만 거래명세서 발행 가능
    if (isPrePayment && !isPaid) {
      return { allowed: false, reason: '입금 확인 후 발행 가능합니다.' };
    }
    return { allowed: true, reason: '' };
  };

  const canIssueTaxInvoice = () => {
    // 입금후출고 조건이면 입금 확인 후에만 세금계산서 발행 가능
    if (isPrePayment && !isPaid) {
      return { allowed: false, reason: '입금 확인 후 발행 가능합니다.' };
    }
    return { allowed: true, reason: '' };
  };

  // ★ 문서 탭 클릭 핸들러
  const handleDocTabClick = (tabId) => {
    setActiveDocTab(tabId);
    setDocumentType(tabId);
    setShowDocumentModal(true);
  };

  // 문서 탭 (계약서, 거래명세서, 발주서)
  const docTabs = [
    { id: 'contract', label: '계약서' },
    { id: 'statement', label: '거래명세서' },
    { id: 'purchaseOrder', label: '발주서' },
  ];

  // 분할에 포함된 아이템 정보 연결
  const getSplitItems = (split) => {
    return (order.items || []).filter(item => split.itemIds?.includes(item.id));
  };

  // 잔여수량 계산 (분할되지 않은 품목)
  const getUnassignedItems = () => {
    const assignedIds = (order.splits || []).flatMap(s => s.itemIds || []);
    return (order.items || []).filter(item => !assignedIds.includes(item.id));
  };

  // 분할 추가 핸들러
  const handleAddSplit = () => {
    if (splitForm.selectedItems.length === 0) {
      alert('분할할 품목을 선택해주세요.');
      return;
    }
    if (!splitForm.dueDate) {
      alert('출고예정일을 입력해주세요.');
      return;
    }

    const newSplitOrder = (order.splits?.length || 0) + 1;
    const newSplit = {
      id: Date.now(),
      splitNo: `${order.orderNo}-${String(newSplitOrder).padStart(2, '0')}`,
      splitOrder: newSplitOrder,
      splitType: splitForm.splitType,
      dueDate: splitForm.dueDate,
      itemIds: splitForm.selectedItems,
      productionStatus: '작업대기',
      shipmentStatus: '출고대기',
      productionOrderNo: null,
      totalQty: splitForm.selectedItems.length,
      completedQty: 0,
      remainingQty: splitForm.selectedItems.length,
    };

    onUpdate?.({
      ...order,
      splits: [...(order.splits || []), newSplit],
    });

    setShowSplitModal(false);
    setSplitForm({ splitType: '개소별', dueDate: '', selectedItems: [] });
  };

  // 품목 선택 토글
  const toggleItemSelection = (itemId) => {
    setSplitForm(prev => ({
      ...prev,
      selectedItems: prev.selectedItems.includes(itemId)
        ? prev.selectedItems.filter(id => id !== itemId)
        : [...prev.selectedItems, itemId]
    }));
  };

  // 분할단위 생산지시
  const handleProductionOrder = (split) => {
    // ※ C등급 경리승인 체크는 출하 시점에서 진행 (생산은 허용)

    // 분할에 포함된 품목 가져오기
    const splitItems = (order.items || []).filter(item => (split.itemIds || []).includes(item.id));
    const splitItemCount = splitItems.length;

    // 품목 카테고리 분석
    const inferCategory = (item) => {
      if (item.category) return item.category;
      const name = (item.productName || '').toLowerCase();
      if (name.includes('슬랫') || name.includes('slat')) return '슬랫';
      if (name.includes('철재') || name.includes('steel')) return '철재';
      return '스크린';
    };

    const categories = [...new Set(splitItems.map(item => inferCategory(item)))];
    const hasScreen = categories.includes('스크린');
    const hasSlat = categories.includes('슬랫') || categories.includes('철재');

    // 공정별 stepStatus 생성
    const getStepStatus = (processType) => {
      const steps = {
        '스크린': ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'],
        '슬랫': ['코일절단', '중간검사', '미미작업', '포장'],
        '절곡': ['절단', '절곡', '중간검사', '포장'],
      };
      const stepStatus = {};
      (steps[processType] || []).forEach(step => {
        stepStatus[step] = { status: '대기' };
      });
      return stepStatus;
    };

    // ★ 공정별 기본 담당자 배정 (팀 단위 배정 지원)
    const getDefaultAssignee = (processType) => {
      const processTeams = {
        '스크린': { assignee: '스크린팀', assignees: ['김스크린', '이스크린', '박스크린'] },
        '슬랫': { assignee: '슬랫팀', assignees: ['김슬랫', '이슬랫', '박슬랫'] },
        '절곡': { assignee: '절곡팀', assignees: ['김절곡', '이절곡'] },
        '재고생산': { assignee: '김생산', assignees: ['김생산'] },
      };
      return processTeams[processType] || { assignee: '김생산', assignees: ['김생산'] };
    };

    const dateCode = new Date().toISOString().slice(2, 10).replace(/-/g, '');
    const workOrders = [];
    const workOrderNos = [];
    let seqNum = 1;

    // 1. 스크린 공정 작업지시
    if (hasScreen) {
      const screenItems = splitItems.filter(item => inferCategory(item) === '스크린');
      const screenWoNo = `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`;
      workOrderNos.push(screenWoNo);

      const screenAssignee = getDefaultAssignee('스크린');
      workOrders.push({
        id: Date.now(),
        workOrderNo: screenWoNo,
        orderNo: order.orderNo,
        splitNo: split.splitNo,
        orderDate: new Date().toISOString().split('T')[0],
        processType: '스크린',
        customerName: order.customerName,
        siteName: order.siteName,
        dueDate: split.dueDate || order.dueDate,
        status: '작업대기',
        priority: '일반',
        assignee: screenAssignee.assignees.join(', '), // 팀 전체 자동 배정
        assignees: screenAssignee.assignees, // 배열로도 저장
        totalQty: screenItems.reduce((sum, item) => sum + (item.qty || 1), 0),
        completedQty: 0,
        currentStep: null,
        stepStatus: getStepStatus('스크린'),
        movedToShippingArea: false,
        items: screenItems.map(item => ({ ...item, category: inferCategory(item), lotNo: null, materialLotNo: null })),
        issues: [],
        createdAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
        createdBy: '현재 사용자',
      });
    }

    // 2. 슬랫 공정 작업지시
    if (hasSlat) {
      const slatItems = splitItems.filter(item => {
        const cat = inferCategory(item);
        return cat === '슬랫' || cat === '철재';
      });
      const slatWoNo = `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`;
      workOrderNos.push(slatWoNo);

      const slatAssignee = getDefaultAssignee('슬랫');
      workOrders.push({
        id: Date.now() + 1,
        workOrderNo: slatWoNo,
        orderNo: order.orderNo,
        splitNo: split.splitNo,
        orderDate: new Date().toISOString().split('T')[0],
        processType: '슬랫',
        customerName: order.customerName,
        siteName: order.siteName,
        dueDate: split.dueDate || order.dueDate,
        status: '작업대기',
        priority: '일반',
        assignee: slatAssignee.assignees.join(', '), // 팀 전체 자동 배정
        assignees: slatAssignee.assignees, // 배열로도 저장
        totalQty: slatItems.reduce((sum, item) => sum + (item.qty || 1), 0),
        completedQty: 0,
        currentStep: null,
        stepStatus: getStepStatus('슬랫'),
        movedToShippingArea: false,
        items: slatItems.map(item => ({ ...item, category: inferCategory(item), lotNo: null, materialLotNo: null })),
        issues: [],
        createdAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
        createdBy: '현재 사용자',
      });
    }

    // 3. 절곡 공정 작업지시 - bomData 활용 (분할 품목 수 비율로 계산)
    const bendWoNo = `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`;
    workOrderNos.push(bendWoNo);

    // 분할 비율 계산 (전체 품목 대비 분할 품목 비율)
    const totalItemCount = (order.items || []).length;
    const splitRatio = splitItemCount / totalItemCount;

    // BOM 데이터에서 절곡물 품목 추출 (분할 비율 적용)
    const bomData = order.bomData || {};
    const bendingItems = [];

    // 가이드레일
    if (bomData.guideRails?.items) {
      bomData.guideRails.items.forEach(rail => {
        rail.lengths?.forEach(len => {
          const adjustedQty = Math.ceil(len.qty * splitRatio);
          if (adjustedQty > 0) {
            bendingItems.push({
              id: Date.now() + bendingItems.length,
              partType: '가이드레일',
              partName: `가이드레일 ${rail.type} ${rail.spec}`,
              partCode: rail.code || '',
              spec: `${len.length}mm`,
              length: len.length,
              qty: adjustedQty,
              unit: 'EA',
              material: 'EGI 1.55T',
              status: '대기',
            });
          }
        });
      });
    }

    // 케이스
    if (bomData.cases?.items) {
      bomData.cases.items.forEach(caseItem => {
        const adjustedQty = Math.ceil(caseItem.qty * splitRatio);
        if (adjustedQty > 0) {
          bendingItems.push({
            id: Date.now() + bendingItems.length,
            partType: '케이스',
            partName: `케이스 ${bomData.cases.mainSpec}`,
            spec: `${caseItem.length}mm`,
            length: caseItem.length,
            qty: adjustedQty,
            unit: 'EA',
            material: 'EGI 1.55T',
            status: '대기',
          });
        }
      });
    }

    // 하단마감재
    if (bomData.bottomFinish?.items) {
      bomData.bottomFinish.items.forEach(finish => {
        finish.lengths?.forEach(len => {
          const adjustedQty = Math.ceil(len.qty * splitRatio);
          if (adjustedQty > 0) {
            bendingItems.push({
              id: Date.now() + bendingItems.length,
              partType: '하단마감재',
              partName: `${finish.name} ${finish.spec}`,
              spec: `${len.length}mm`,
              length: len.length,
              qty: adjustedQty,
              unit: 'EA',
              material: 'EGI 1.55T',
              status: '대기',
            });
          }
        });
      });
    }

    const bendAssignee = getDefaultAssignee('절곡');
    workOrders.push({
      id: Date.now() + 2,
      workOrderNo: bendWoNo,
      orderNo: order.orderNo,
      splitNo: split.splitNo,
      orderDate: new Date().toISOString().split('T')[0],
      processType: '절곡',
      customerName: order.customerName,
      siteName: order.siteName,
      dueDate: split.dueDate || order.dueDate,
      status: '작업대기',
      priority: '일반',
      assignee: bendAssignee.assignees.join(', '), // 팀 전체 자동 배정
      assignees: bendAssignee.assignees, // 배열로도 저장
      totalQty: bendingItems.length,
      completedQty: 0,
      currentStep: null,
      stepStatus: getStepStatus('절곡'),
      movedToShippingArea: false,
      items: splitItems.map(item => ({ ...item, category: inferCategory(item), lotNo: null, materialLotNo: null })),
      bendingItems: bendingItems,
      bomData: bomData,
      issues: [],
      createdAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
      createdBy: '현재 사용자',
    });

    // 모든 작업지시 생성
    workOrders.forEach(wo => {
      onCreateWorkOrder?.(wo);
    });

    // 분할 상태 업데이트
    const updatedSplits = (order.splits || []).map(s =>
      s.id === split.id
        ? { ...s, productionOrderNo: workOrderNos.join(', '), productionStatus: '작업지시' }
        : s
    );

    // 변경 이력 추가
    const newHistory = {
      id: Date.now(),
      changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
      changeType: '생산지시',
      description: `분할 ${split.splitNo} 생산지시 (${workOrders.map(wo => `${wo.processType}:${wo.workOrderNo}`).join(', ')})`,
      changedBy: '현재 사용자',
    };

    onUpdate?.({
      ...order,
      splits: updatedSplits,
      status: order.status === '수주확정' ? '생산중' : order.status,
      changeHistory: [...(order.changeHistory || []), newHistory],
    });

    // ★ 확인 다이얼로그 표시 (alert 대신)
    setProductionCompleteInfo({ workOrders, splitNo: split.splitNo, itemCount: splitItems.length });
    setShowProductionCompleteDialog(true);
  };

  // 전체 생산지시 (분할 없이 전체 품목 한번에) - 공정별 자동 분리
  const handleFullProductionOrder = () => {
    // ※ C등급 경리승인 체크는 출하 시점에서 진행 (생산은 허용)

    const dateCode = new Date().toISOString().slice(2, 10).replace(/-/g, '');
    const items = order.items || [];
    const calculatedItems = order.calculatedItems || [];

    // 품목명에서 카테고리 추정 함수
    const inferCategory = (item) => {
      if (item.category) return item.category;
      const name = (item.productName || '').toLowerCase();
      if (name.includes('슬랫') || name.includes('slat')) return '슬랫';
      if (name.includes('철재') || name.includes('steel')) return '철재';
      return '스크린';  // 기본값
    };

    // 품목 카테고리 분석
    const categories = [...new Set(items.map(item => inferCategory(item)))];
    const hasScreen = categories.includes('스크린');
    const hasSlat = categories.includes('슬랫') || categories.includes('철재');

    // 공정별 stepStatus 생성 함수
    const getStepStatus = (processType) => {
      const steps = {
        '스크린': ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'],
        '슬랫': ['코일절단', '중간검사', '미미작업', '포장'],
        '절곡': ['절단', '절곡', '중간검사', '포장'],
        '전기': ['배선', '검사', '포장'],
      };
      const stepStatus = {};
      (steps[processType] || []).forEach(step => {
        stepStatus[step] = { status: '대기' };
      });
      return stepStatus;
    };

    // 생성할 작업지시 목록
    const workOrders = [];
    const workOrderNos = [];
    let seqNum = 1;

    // ★ calculatedItems가 있는 경우 공정별로 분류하여 작업지시 생성
    if (calculatedItems.length > 0) {
      // 공정별 품목 그룹화
      const itemsByProcess = calculatedItems.reduce((acc, item) => {
        const process = item.process || '기타';
        if (!acc[process]) acc[process] = [];
        acc[process].push(item);
        return acc;
      }, {});

      // 각 공정별 작업지시 생성
      Object.entries(itemsByProcess).forEach(([process, processItems]) => {
        const woNo = `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`;
        workOrderNos.push(woNo);

        const processAssignee = getDefaultAssignee(process);
        workOrders.push({
          id: Date.now() + workOrders.length,
          workOrderNo: woNo,
          orderNo: order.orderNo,
          splitNo: null,
          orderDate: new Date().toISOString().split('T')[0],
          processType: process,
          customerName: order.customerName,
          siteName: order.siteName,
          dueDate: order.dueDate,
          status: '작업대기',
          priority: '일반',
          assignee: processAssignee.assignees.join(', '), // 공정별 팀 자동 배정
          assignees: processAssignee.assignees, // 배열로도 저장
          totalQty: processItems.reduce((sum, item) => sum + (item.qty || 1), 0),
          completedQty: 0,
          currentStep: null,
          stepStatus: getStepStatus(process),
          movedToShippingArea: false,
          // 완제품 정보 (참조용)
          items: items.map(item => ({ ...item, category: inferCategory(item), lotNo: null, materialLotNo: null })),
          // ★ 견적에서 산출된 품목 리스트 (작업자가 실제로 만들어야 할 부품)
          calculatedItems: processItems.map(item => ({
            ...item,
            status: '대기',
            completedQty: 0,
          })),
          // 절곡 공정인 경우 bendingItems 형식으로도 제공
          bendingItems: process === '절곡' ? processItems.map(item => ({
            id: item.id,
            partType: item.itemName,
            partName: item.itemName,
            partCode: item.itemCode,
            spec: item.spec,
            length: item.length,
            qty: item.qty,
            unit: item.unit,
            material: 'EGI 1.55T',
            status: '대기',
            floor: item.floor,
            location: item.location,
          })) : undefined,
          issues: [],
          createdAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
          createdBy: '현재 사용자',
        });
      });
    } else {
      // 기존 로직: calculatedItems가 없는 경우 bomData 활용

      // 1. 메인 공정 작업지시 (스크린 또는 슬랫)
      if (hasScreen) {
        const screenItems = items.filter(item => inferCategory(item) === '스크린');
        const screenWoNo = `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`;
        workOrderNos.push(screenWoNo);

        const screenAssignee2 = getDefaultAssignee('스크린');
        workOrders.push({
          id: Date.now(),
          workOrderNo: screenWoNo,
          orderNo: order.orderNo,
          splitNo: null,
          orderDate: new Date().toISOString().split('T')[0],
          processType: '스크린',
          customerName: order.customerName,
          siteName: order.siteName,
          dueDate: order.dueDate,
          status: '작업대기',
          priority: '일반',
          assignee: screenAssignee2.assignees.join(', '), // 팀 자동 배정
          assignees: screenAssignee2.assignees,
          totalQty: screenItems.reduce((sum, item) => sum + (item.qty || 1), 0),
          completedQty: 0,
          currentStep: null,
          stepStatus: getStepStatus('스크린'),
          movedToShippingArea: false,
          items: screenItems.map(item => ({ ...item, category: inferCategory(item), lotNo: null, materialLotNo: null })),
          issues: [],
          createdAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
          createdBy: '현재 사용자',
        });
      }

      if (hasSlat) {
        const slatItems = items.filter(item => {
          const cat = inferCategory(item);
          return cat === '슬랫' || cat === '철재';
        });
        const slatWoNo = `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`;
        workOrderNos.push(slatWoNo);

        const slatAssignee2 = getDefaultAssignee('슬랫');
        workOrders.push({
          id: Date.now() + 1,
          workOrderNo: slatWoNo,
          orderNo: order.orderNo,
          splitNo: null,
          orderDate: new Date().toISOString().split('T')[0],
          processType: '슬랫',
          customerName: order.customerName,
          siteName: order.siteName,
          dueDate: order.dueDate,
          status: '작업대기',
          priority: '일반',
          assignee: slatAssignee2.assignees.join(', '), // 팀 자동 배정
          assignees: slatAssignee2.assignees,
          totalQty: slatItems.reduce((sum, item) => sum + (item.qty || 1), 0),
          completedQty: 0,
          currentStep: null,
          stepStatus: getStepStatus('슬랫'),
          movedToShippingArea: false,
          items: slatItems.map(item => ({ ...item, category: inferCategory(item), lotNo: null, materialLotNo: null })),
          issues: [],
          createdAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
          createdBy: '현재 사용자',
        });
      }

      // 2. 절곡 공정 작업지시 (모든 제품에 필요) - bomData 활용
      const bendWoNo = `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`;
      workOrderNos.push(bendWoNo);

      // BOM 데이터에서 절곡물 품목 추출
      const bomData = order.bomData || {};
      const bendingItems = [];

      // 가이드레일
      if (bomData.guideRails?.items) {
        bomData.guideRails.items.forEach(rail => {
          rail.lengths?.forEach(len => {
            if (len.qty > 0) {
              bendingItems.push({
                id: Date.now() + bendingItems.length,
                partType: '가이드레일',
                partName: `가이드레일 ${rail.type} ${rail.spec}`,
                partCode: rail.code || '',
                spec: `${len.length}mm`,
                length: len.length,
                qty: len.qty,
                unit: 'EA',
                material: 'EGI 1.55T',
                status: '대기',
              });
            }
          });
        });
        // 연기차단재
        if (bomData.guideRails.smokeBarrier?.lengths) {
          bomData.guideRails.smokeBarrier.lengths.forEach(len => {
            if (len.qty > 0) {
              bendingItems.push({
                id: Date.now() + bendingItems.length,
                partType: '연기차단재',
                partName: `연기차단재 ${bomData.guideRails.smokeBarrier.spec}`,
                spec: `${len.length}mm`,
                length: len.length,
                qty: len.qty,
                unit: 'EA',
                material: bomData.guideRails.smokeBarrier.material,
                status: '대기',
              });
            }
          });
        }
      }

      // 케이스
      if (bomData.cases?.items) {
        bomData.cases.items.forEach(caseItem => {
          if (caseItem.qty > 0) {
            bendingItems.push({
              id: Date.now() + bendingItems.length,
              partType: '케이스',
              partName: `케이스 ${bomData.cases.mainSpec}`,
              spec: `${caseItem.length}mm`,
              length: caseItem.length,
              qty: caseItem.qty,
              unit: 'EA',
              material: 'EGI 1.55T',
              status: '대기',
            });
          }
        });
        // 측면덮개
        if (bomData.cases.sideCover?.qty > 0) {
          bendingItems.push({
            id: Date.now() + bendingItems.length,
            partType: '케이스',
            partName: `측면덮개 ${bomData.cases.sideCover.spec}`,
            spec: '',
            qty: bomData.cases.sideCover.qty,
            unit: 'EA',
            material: 'EGI 1.55T',
            status: '대기',
          });
        }
        // 상부덮개
        if (bomData.cases.topCover?.qty > 0) {
          bendingItems.push({
            id: Date.now() + bendingItems.length,
            partType: '케이스',
            partName: '상부덮개',
            spec: '',
            qty: bomData.cases.topCover.qty,
            unit: 'EA',
            material: 'EGI 1.55T',
            status: '대기',
          });
        }
      }

      // 하단마감재
      if (bomData.bottomFinish?.items) {
        bomData.bottomFinish.items.forEach(finish => {
          finish.lengths?.forEach(len => {
            if (len.qty > 0) {
              bendingItems.push({
                id: Date.now() + bendingItems.length,
                partType: '하단마감재',
                partName: `${finish.name} ${finish.spec}`,
                spec: `${len.length}mm`,
                length: len.length,
                qty: len.qty,
                unit: 'EA',
                material: 'EGI 1.55T',
                status: '대기',
              });
            }
          });
        });
      }

      const bendAssignee2 = getDefaultAssignee('절곡');
      workOrders.push({
        id: Date.now() + 2,
        workOrderNo: bendWoNo,
        orderNo: order.orderNo,
        splitNo: null,
        orderDate: new Date().toISOString().split('T')[0],
        processType: '절곡',
        customerName: order.customerName,
        siteName: order.siteName,
        dueDate: order.dueDate,
        status: '작업대기',
        priority: '일반',
        assignee: bendAssignee2.assignees.join(', '), // 팀 자동 배정
        assignees: bendAssignee2.assignees,
        totalQty: bendingItems.length,
        completedQty: 0,
        currentStep: null,
        stepStatus: getStepStatus('절곡'),
        movedToShippingArea: false,
        items: items.map(item => ({ ...item, category: inferCategory(item), lotNo: null, materialLotNo: null })),
        bendingItems: bendingItems,
        bomData: bomData,
        issues: [],
        createdAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
        createdBy: '현재 사용자',
      });
    }

    // 변경 이력 추가
    const newHistory = {
      id: Date.now(),
      changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
      changeType: '생산지시',
      description: `전체 생산지시 완료 (작업지시: ${workOrders.map(wo => `${wo.processType}(${wo.workOrderNo})`).join(', ')})`,
      changedBy: '현재 사용자',
    };

    // 모든 작업지시 생성
    workOrders.forEach(wo => {
      onCreateWorkOrder?.(wo);
    });

    // 수주 상태 업데이트
    onUpdate?.({
      ...order,
      status: '생산중',
      workOrderNo: workOrderNos.join(', '),
      productionOrderedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
      productionOrderedBy: '현재 사용자',
      changeHistory: [...(order.changeHistory || []), newHistory],
    });

    setShowProductionModal(false);

    // ★ 확인 다이얼로그 표시 (alert 대신)
    setProductionCompleteInfo({ workOrders, splitNo: null, itemCount: (order.items || []).length });
    setShowProductionCompleteDialog(true);
  };

  // 금액 계산
  const subtotal = order.items?.reduce((sum, item) => sum + (item.amount || 0), 0) || order.totalAmount || 0;
  const discountRate = order.discountRate || 0;
  const discountAmount = Math.round(subtotal * discountRate / 100);
  const finalTotal = subtotal - discountAmount;

  return (
    <div className="space-y-6">
      {/* 상단 헤더 - 타이틀 아래에 버튼 영역 */}
      <div className="space-y-3">
        {/* 타이틀 */}
        <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
          <FileText className="w-6 h-6 text-blue-500" />
          수주 상세
        </h1>
        {/* 버튼 영역 - 좌측: 문서버튼 / 우측: 액션버튼 */}
        <div className="flex items-center justify-between">
          {/* 좌측: 문서 버튼 */}
          <div className="flex items-center gap-2">
            {docTabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => handleDocTabClick(tab.id)}
                className="flex items-center gap-1 px-3 py-1.5 text-sm border border-gray-300 rounded hover:bg-gray-50 transition-colors"
              >
                <FileText className="w-4 h-4" />
                {tab.label}
              </button>
            ))}
          </div>
          {/* 우측: 액션 버튼 */}
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={onBack}>
              <List className="w-4 h-4" /> 목록
            </Button>
            {order.status !== '출하완료' && order.status !== '취소' && (
              <Button variant="outline" size="sm" onClick={() => onNavigate('order-edit', order)}>
                <Edit className="w-4 h-4" /> 수정
              </Button>
            )}
            {/* 생산지시 생성 버튼 (생산지시가 없는 경우) - 출하완료/취소/완료 제외, 생산지시 없으면 표시 */}
            {!relatedPO && !order.workOrderNo && !['출하완료', '취소', '완료'].includes(order.status) && (
              <Button variant="primary" size="sm" onClick={() => onNavigate('production-order-create', order)}>
                <FileText className="w-4 h-4" /> 생산지시 생성
              </Button>
            )}
            {/* 생산지시 보기 버튼 (생산지시가 있는 경우) */}
            {relatedPO && (
              <Button variant="outline" size="sm" onClick={() => onNavigate('production-order-detail', relatedPO)}>
                <Eye className="w-4 h-4" /> 생산지시 보기
              </Button>
            )}
            {/* 분할 생산지시 버튼 (생산지시 없고 분할도 없는 경우) */}
            {!relatedPO && !order.workOrderNo && !['출하완료', '취소', '완료'].includes(order.status) && (order.splits?.length || 0) === 0 && (
              <Button variant="outline" size="sm" onClick={() => setShowProductionModal(true)}>
                <Factory className="w-4 h-4" /> 분할 생산지시
              </Button>
            )}
            {/* 취소 버튼 - 취소 가능한 상태에서만 표시 (생산지시완료 전까지) */}
            {!['생산지시완료', '출하대기', '출하완료', '취소'].includes(order.status) && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => setShowCancelModal(true)}
                className="text-orange-600 border-orange-300 hover:bg-orange-50"
              >
                <XCircle className="w-4 h-4" /> 취소
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* 기본 정보 섹션 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="px-4 py-3 bg-gray-50 border-b">
          <h3 className="text-sm font-semibold text-gray-700">기본 정보</h3>
        </div>
        <div className="p-4">
          <div className="grid grid-cols-4 gap-x-8 gap-y-3">
            <div className="flex items-center">
              <span className="text-sm text-gray-500 w-16 flex-shrink-0">발주처</span>
              <span className="text-sm font-medium text-gray-900">{order.customerName}</span>
            </div>
            <div className="flex items-center">
              <span className="text-sm text-gray-500 w-16 flex-shrink-0">현장명</span>
              <span className="text-sm font-medium text-gray-900">{order.siteName}</span>
            </div>
            <div className="flex items-center">
              <span className="text-sm text-gray-500 w-16 flex-shrink-0">담당자</span>
              <span className="text-sm font-medium text-gray-900">{order.manager || '-'}</span>
            </div>
            <div className="flex items-center">
              <span className="text-sm text-gray-500 w-16 flex-shrink-0">연락처</span>
              <span className="text-sm font-medium text-gray-900">{order.contact || '-'}</span>
            </div>
          </div>
        </div>
      </div>

      {/* 수주/배송 정보 섹션 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="px-4 py-3 bg-gray-50 border-b">
          <h3 className="text-sm font-semibold text-gray-700">수주/배송 정보</h3>
        </div>
        <div className="p-4">
          <div className="grid grid-cols-5 gap-x-6 gap-y-3">
            <div className="flex items-center">
              <span className="text-sm text-gray-500 w-20 flex-shrink-0">수주일자</span>
              <span className="text-sm font-medium text-gray-900">{order.orderDate || order.createdAt?.split(' ')[0] || '-'}</span>
            </div>
            <div className="flex items-center">
              <span className="text-sm text-gray-500 w-24 flex-shrink-0">출고예정일</span>
              <span className="text-sm font-medium text-gray-900">{order.shippingDate || order.dueDate || '-'}</span>
            </div>
            <div className="flex items-center">
              <span className="text-sm text-gray-500 w-24 flex-shrink-0">납품요청일</span>
              <span className="text-sm font-medium text-gray-900">{order.deliveryRequestDate || order.dueDate || '-'}</span>
            </div>
            <div className="flex items-center">
              <span className="text-sm text-gray-500 w-20 flex-shrink-0">배송방식</span>
              <span className="text-sm font-medium text-gray-900">{order.deliveryMethod || '-'}</span>
            </div>
            <div className="flex items-center">
              <span className="text-sm text-gray-500 w-20 flex-shrink-0">운임비용</span>
              <span className="text-sm font-medium text-gray-900">{order.freightCost || '-'}</span>
            </div>
            <div className="flex items-center">
              <span className="text-sm text-gray-500 w-28 flex-shrink-0">수신(반장/업체)</span>
              <span className="text-sm font-medium text-gray-900">{order.receiverName || '-'}</span>
            </div>
            <div className="flex items-center">
              <span className="text-sm text-gray-500 w-24 flex-shrink-0">수신처 연락처</span>
              <span className="text-sm font-medium text-gray-900">{order.receiverPhone || '-'}</span>
            </div>
            <div className="flex items-center col-span-3">
              <span className="text-sm text-gray-500 w-24 flex-shrink-0">수신처 주소</span>
              <span className="text-sm font-medium text-gray-900">
                {order.deliveryAddress || (order.deliveryZipcode ? `(${order.deliveryZipcode}) ${order.deliveryAddressBase || ''} ${order.deliveryAddressDetail || ''}` : '-')}
              </span>
            </div>
            <div className="flex items-start col-span-5">
              <span className="text-sm text-gray-500 w-20 flex-shrink-0">비고</span>
              <span className="text-sm font-medium text-gray-900">{order.deliveryNote || order.note || '-'}</span>
            </div>
          </div>
        </div>
      </div>

      {/* 제품 내역 섹션 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="px-4 py-3 bg-gray-50 border-b">
          <h3 className="text-sm font-semibold text-gray-700">제품 내역</h3>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 border-b">
              <tr>
                <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 w-12">순번</th>
                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 w-28">품목코드</th>
                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">품목명</th>
                <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 w-16">층</th>
                <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 w-16">부호</th>
                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 w-32">규격</th>
                <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 w-16">수량</th>
                <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 w-14">단위</th>
                <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 w-24">단가</th>
                <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 w-28">금액</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {(order.items || []).map((item, idx) => (
                <tr key={item.id || idx} className="hover:bg-gray-50">
                  <td className="px-3 py-2 text-sm text-gray-500 text-center">{idx + 1}</td>
                  <td className="px-3 py-2 text-sm font-mono text-gray-900">{item.productCode}</td>
                  <td className="px-3 py-2 text-sm text-gray-900">{item.productName}</td>
                  <td className="px-3 py-2 text-sm text-gray-900 text-center">{item.floor || '-'}</td>
                  <td className="px-3 py-2 text-sm text-gray-900 text-center">{item.location || '-'}</td>
                  <td className="px-3 py-2 text-sm text-gray-900">{item.spec}</td>
                  <td className="px-3 py-2 text-sm text-gray-900 text-right">{item.qty}</td>
                  <td className="px-3 py-2 text-sm text-gray-900 text-center">{item.unit}</td>
                  <td className="px-3 py-2 text-sm text-gray-900 text-right">{(item.unitPrice || 0).toLocaleString()}</td>
                  <td className="px-3 py-2 text-sm font-medium text-gray-900 text-right">{(item.amount || 0).toLocaleString()}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* 합계 영역 */}
        <div className="border-t bg-gray-50 px-4 py-3">
          <div className="flex justify-end">
            <div className="w-72 space-y-2">
              <div className="flex items-center justify-between text-sm">
                <span className="text-gray-600">소계</span>
                <span className="font-medium text-gray-900">{subtotal.toLocaleString()}원</span>
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="text-gray-600">할인율</span>
                <span className="font-medium text-gray-900">{discountRate}%</span>
              </div>
              <div className="flex items-center justify-between text-sm pt-2 border-t border-gray-200">
                <span className="font-semibold text-gray-700">총금액</span>
                <span className="font-bold text-lg text-blue-600">{finalTotal.toLocaleString()}원</span>
              </div>
            </div>
          </div>
        </div>
      </div>


      {/* 분할 추가 모달 */}
      {showSplitModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden">
            <div className="p-6 border-b">
              <h2 className="text-xl font-bold text-gray-900">분할 추가</h2>
              <p className="text-sm text-gray-500 mt-1">{(order.splits || []).length + 1}차 분할을 생성합니다.</p>
            </div>

            <div className="p-6 space-y-6 max-h-[60vh] overflow-y-auto">
              {/* 분할 유형 선택 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">분할 유형</label>
                <div className="flex gap-3">
                  {['개소별', '층별', '자재별'].map(type => (
                    <button
                      key={type}
                      onClick={() => setSplitForm(prev => ({ ...prev, splitType: type }))}
                      className={`px-4 py-2 rounded-lg border text-sm font-medium transition-colors
                        ${splitForm.splitType === type
                          ? 'bg-blue-50 border-blue-500 text-blue-700'
                          : 'border-gray-200 text-gray-600 hover:bg-gray-50'
                        }`}
                    >
                      {type}
                    </button>
                  ))}
                </div>
              </div>

              {/* 출고예정일 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">출고예정일 *</label>
                <input
                  type="date"
                  value={splitForm.dueDate}
                  onChange={(e) => setSplitForm(prev => ({ ...prev, dueDate: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* 품목 선택 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  품목 선택 * <span className="text-gray-400 font-normal">({splitForm.selectedItems.length}개 선택)</span>
                </label>
                <div className="border rounded-lg overflow-hidden">
                  <table className="w-full">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-4 py-2 text-center text-xs font-medium text-gray-500 w-12">선택</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500">품목코드</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500">품목명</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500">층/부호</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500">규격</th>
                        <th className="px-4 py-2 text-right text-xs font-medium text-gray-500">수량</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {getUnassignedItems().map(item => (
                        <tr
                          key={item.id}
                          className={`cursor-pointer transition-colors ${splitForm.selectedItems.includes(item.id) ? 'bg-blue-50' : 'hover:bg-gray-50'
                            }`}
                          onClick={() => toggleItemSelection(item.id)}
                        >
                          <td className="px-4 py-2 text-center">
                            <input
                              type="checkbox"
                              checked={splitForm.selectedItems.includes(item.id)}
                              onChange={() => toggleItemSelection(item.id)}
                              className="rounded"
                            />
                          </td>
                          <td className="px-4 py-2 text-sm font-mono">{item.productCode}</td>
                          <td className="px-4 py-2 text-sm">{item.productName}</td>
                          <td className="px-4 py-2 text-sm">{item.floor}/{item.location}</td>
                          <td className="px-4 py-2 text-sm">{item.spec}</td>
                          <td className="px-4 py-2 text-sm text-right">{item.qty}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  {getUnassignedItems().length === 0 && (
                    <div className="text-center py-8 text-gray-500">
                      <p>모든 품목이 이미 분할되었습니다.</p>
                    </div>
                  )}
                </div>
              </div>

              {/* 분할 정보 요약 */}
              {splitForm.selectedItems.length > 0 && (
                <div className="p-4 bg-blue-50 rounded-lg">
                  <h4 className="font-medium text-blue-900 mb-2">분할 정보 요약</h4>
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div>
                      <span className="text-blue-600">분할번호</span>
                      <p className="font-mono font-medium">{order.orderNo}-{String((order.splits || []).length + 1).padStart(2, '0')}</p>
                    </div>
                    <div>
                      <span className="text-blue-600">분할 유형</span>
                      <p className="font-medium">{splitForm.splitType}</p>
                    </div>
                    <div>
                      <span className="text-blue-600">선택 품목</span>
                      <p className="font-medium">{splitForm.selectedItems.length}건</p>
                    </div>
                  </div>
                </div>
              )}
            </div>

            <div className="flex gap-2 p-4 border-t bg-gray-50">
              <Button variant="outline" className="flex-1" onClick={() => {
                setShowSplitModal(false);
                setSplitForm({ splitType: '개소별', dueDate: '', selectedItems: [] });
              }}>
                취소
              </Button>
              <Button variant="primary" className="flex-1" onClick={handleAddSplit}>
                <Plus className="w-4 h-4" /> 분할 생성
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 수주서/생산지시서 출력 모달 */}
      {showProductionSheet && (
        <ProductionOrderSheet
          order={order}
          title={sheetTitle}
          onClose={() => setShowProductionSheet(false)}
        />
      )}

      {/* 생산지시 상세 모달 (탭 기반) */}
      {showProductionModal && (
        <ProductionOrderModal
          order={order}
          onClose={() => setShowProductionModal(false)}
          onConfirm={handleFullProductionOrder}
          onPreview={() => {
            setShowProductionModal(false);
            setSheetTitle('생산지시서');
            setShowProductionSheet(true);
          }}
        />
      )}

      {/* 새로운 생산지시 생성 모달 */}
      {showPOCreateModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-lg w-full">
            <div className="p-6 border-b">
              <h3 className="text-lg font-bold flex items-center gap-2">
                <FileText className="w-5 h-5 text-blue-600" />
                생산지시 생성
              </h3>
              <p className="text-sm text-gray-500 mt-1">수주를 생산지시로 전환합니다</p>
            </div>
            <div className="p-6">
              <div className="bg-blue-50 rounded-lg p-4 mb-4">
                <div className="text-sm space-y-2">
                  <div className="flex justify-between">
                    <span className="text-gray-600">수주번호</span>
                    <span className="font-medium">{order.orderNo}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">현장명</span>
                    <span className="font-medium">{order.siteName}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">수량</span>
                    <span className="font-medium">{order.qty || order.items?.length || 0}개</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">납기</span>
                    <span className="font-medium text-red-600">{order.dueDate}</span>
                  </div>
                </div>
              </div>

              <div className="bg-gray-50 rounded-lg p-4">
                <h4 className="font-medium mb-2 flex items-center gap-2">
                  <GitBranch className="w-4 h-4 text-blue-600" />
                  BOM 기반 공정 분류
                </h4>
                <p className="text-sm text-gray-600 mb-3">
                  수주 품목이 아래 공정으로 자동 분류됩니다:
                </p>
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm">
                    <span className="w-6 h-6 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center text-xs font-bold">1</span>
                    <span>스크린 공정</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <span className="w-6 h-6 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center text-xs font-bold">2</span>
                    <span>절곡 공정</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <span className="w-6 h-6 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center text-xs font-bold">3</span>
                    <span>샤프트 공정</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <span className="w-6 h-6 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center text-xs font-bold">4</span>
                    <span>조립 공정</span>
                  </div>
                </div>
              </div>

              <p className="text-sm text-gray-500 mt-4">
                생산지시 생성 후, 생산관리에서 작업지시서를 발행하여 생산팀에 전달할 수 있습니다.
              </p>
            </div>
            <div className="p-4 border-t bg-gray-50 flex justify-end gap-2">
              <button
                onClick={() => setShowPOCreateModal(false)}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg"
              >
                취소
              </button>
              <button
                onClick={() => {
                  setShowPOCreateModal(false);
                  onCreateProductionOrder?.(order);
                }}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
              >
                <FileText className="w-4 h-4" />
                생산지시 생성
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ★ 문서 출력 모달 (계약서/거래명세서/발주서) */}
      {showDocumentModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-4xl max-h-[95vh] flex flex-col">
            {/* 모달 헤더 */}
            <div className="flex items-center justify-between px-6 py-4 border-b bg-gray-900 text-white rounded-t-xl">
              <h2 className="text-lg font-bold">
                {documentType === 'contract' && '계약서'}
                {documentType === 'statement' && '거래명세서'}
                {documentType === 'purchaseOrder' && '발주서'}
              </h2>
              <button onClick={() => setShowDocumentModal(false)} className="text-gray-300 hover:text-white">
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* 액션 버튼 */}
            <div className="flex items-center gap-2 px-6 py-3 border-b bg-gray-50">
              <button className="flex items-center gap-1.5 px-3 py-1.5 bg-red-500 text-white text-sm rounded-lg hover:bg-red-600">
                <Download className="w-4 h-4" /> PDF
              </button>
              <button className="flex items-center gap-1.5 px-3 py-1.5 bg-blue-500 text-white text-sm rounded-lg hover:bg-blue-600">
                <Mail className="w-4 h-4" /> 이메일
              </button>
              {(documentType === 'contract' || documentType === 'purchaseOrder') && (
                <>
                  <button className="flex items-center gap-1.5 px-3 py-1.5 bg-green-500 text-white text-sm rounded-lg hover:bg-green-600">
                    <Printer className="w-4 h-4" /> 팩스
                  </button>
                  <button className="flex items-center gap-1.5 px-3 py-1.5 bg-yellow-500 text-white text-sm rounded-lg hover:bg-yellow-600">
                    <MessageCircle className="w-4 h-4" /> 카카오톡
                  </button>
                </>
              )}
              <button className="flex items-center gap-1.5 px-3 py-1.5 bg-gray-100 text-gray-700 text-sm rounded-lg hover:bg-gray-200 border">
                <Printer className="w-4 h-4" /> 인쇄
              </button>
              <div className="flex-1" />
              <button
                onClick={() => setShowDocumentModal(false)}
                className="flex items-center gap-1.5 px-3 py-1.5 text-gray-600 text-sm hover:bg-gray-100 rounded-lg"
              >
                <X className="w-4 h-4" /> 닫기
              </button>
            </div>

            {/* 결제조건 안내 (입금후출고 조건일 때) */}
            {isPrePayment && documentType === 'statement' && !isPaid && (
              <div className="mx-6 mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                <div className="flex items-center gap-2 text-yellow-800">
                  <AlertCircle className="w-5 h-5" />
                  <span className="font-medium">결제조건: {paymentTerms}</span>
                </div>
                <p className="text-sm text-yellow-700 mt-1">
                  이 거래처는 입금 확인 후 거래명세서를 발행해야 합니다. 현재 입금 상태를 확인해주세요.
                </p>
              </div>
            )}

            {/* 문서 미리보기 영역 */}
            <div className="flex-1 overflow-y-auto p-6 bg-gray-100">
              <div className="bg-white rounded-lg shadow-lg p-8 max-w-3xl mx-auto">
                {/* ========== 계약서 ========== */}
                {documentType === 'contract' && (
                  <div className="space-y-6">
                    {/* 제목 */}
                    <div className="text-center border-b-2 border-gray-900 pb-4">
                      <h1 className="text-3xl font-bold tracking-widest">계 약 서</h1>
                      <p className="text-sm text-gray-600 mt-2">
                        수주번호: {order.orderNo} | 계약일자: {order.orderDate || order.createdAt?.split(' ')[0]}
                      </p>
                    </div>

                    {/* 제품명 */}
                    <div className="border border-gray-300 rounded">
                      <div className="bg-gray-900 text-white text-center py-2 font-medium">제품명</div>
                      <div className="text-center py-3 font-medium">{order.items?.[0]?.productName || '방화문 세트'}</div>
                    </div>

                    {/* 수주물목 (개소별 사이즈) */}
                    <div>
                      <div className="bg-gray-900 text-white text-center py-2 font-medium rounded-t">수주물목 (개소별 사이즈)</div>
                      <table className="w-full border border-gray-300">
                        <thead className="bg-gray-50">
                          <tr>
                            <th className="border px-3 py-2 text-sm">품목코드</th>
                            <th className="border px-3 py-2 text-sm">품명</th>
                            <th className="border px-3 py-2 text-sm">규격</th>
                            <th className="border px-3 py-2 text-sm">수량</th>
                            <th className="border px-3 py-2 text-sm">단위</th>
                          </tr>
                        </thead>
                        <tbody>
                          {(order.items || []).slice(0, 5).map((item, idx) => (
                            <tr key={idx}>
                              <td className="border px-3 py-2 text-sm text-center">{item.productCode}</td>
                              <td className="border px-3 py-2 text-sm">{item.productName}</td>
                              <td className="border px-3 py-2 text-sm text-center">{item.spec}</td>
                              <td className="border px-3 py-2 text-sm text-center">{item.qty}</td>
                              <td className="border px-3 py-2 text-sm text-center">{item.unit}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>

                    {/* 발주처 정보 / 당사 정보 */}
                    <div className="grid grid-cols-2 gap-4">
                      <div className="border border-gray-300 rounded">
                        <div className="bg-gray-900 text-white text-center py-2 font-medium">발주처정보</div>
                        <div className="p-3 space-y-2 text-sm">
                          <div className="flex"><span className="w-16 text-gray-500">업체명</span><span>{order.customerName}</span></div>
                          <div className="flex"><span className="w-16 text-gray-500">현장명</span><span>{order.siteName}</span></div>
                          <div className="flex"><span className="w-16 text-gray-500">담당자</span><span>{order.manager || '-'}</span></div>
                          <div className="flex"><span className="w-16 text-gray-500">연락처</span><span>{order.contact || '-'}</span></div>
                        </div>
                      </div>
                      <div className="border border-gray-300 rounded">
                        <div className="bg-gray-900 text-white text-center py-2 font-medium">당사정보</div>
                        <div className="p-3 space-y-2 text-sm">
                          <div className="flex"><span className="w-20 text-gray-500">업체명</span><span>한국방화문(주)</span></div>
                          <div className="flex"><span className="w-20 text-gray-500">대표자</span><span>홍길동</span></div>
                          <div className="flex"><span className="w-20 text-gray-500">사업자번호</span><span>123-45-67890</span></div>
                          <div className="flex"><span className="w-20 text-gray-500">연락처</span><span>02-1234-5678</span></div>
                          <div className="flex"><span className="w-20 text-gray-500">주소</span><span>서울특별시 강남구 테헤란로 123</span></div>
                        </div>
                      </div>
                    </div>

                    {/* 총 계약 금액 */}
                    <div className="border-2 border-gray-900 rounded-lg p-6 text-center">
                      <p className="text-gray-600 mb-2">총 계약 금액</p>
                      <p className="text-4xl font-bold">₩ {finalTotal.toLocaleString()}</p>
                      <p className="text-sm text-gray-500 mt-1">(부가세 포함)</p>
                    </div>

                    {/* 금액 상세 */}
                    <table className="w-full border border-gray-300 text-sm">
                      <tbody>
                        <tr>
                          <td className="border px-3 py-2 bg-gray-50">공급가액</td>
                          <td className="border px-3 py-2 text-center">{subtotal.toLocaleString()}원</td>
                          <td className="border px-3 py-2 bg-gray-50">할인율</td>
                          <td className="border px-3 py-2 text-center text-red-500">{discountRate}%</td>
                        </tr>
                        <tr>
                          <td className="border px-3 py-2 bg-gray-50">할인액</td>
                          <td className="border px-3 py-2 text-center text-red-500">-{Math.round(subtotal * discountRate / 100).toLocaleString()}원</td>
                          <td className="border px-3 py-2 bg-gray-50">할인 후 공급가액</td>
                          <td className="border px-3 py-2 text-center">{Math.round(subtotal * (1 - discountRate / 100)).toLocaleString()}원</td>
                        </tr>
                        <tr>
                          <td className="border px-3 py-2 bg-gray-50">부가세(10%)</td>
                          <td className="border px-3 py-2 text-center">{Math.round(subtotal * (1 - discountRate / 100) * 0.1).toLocaleString()}원</td>
                          <td className="border px-3 py-2 bg-gray-50 font-bold">합계</td>
                          <td className="border px-3 py-2 text-center font-bold">{finalTotal.toLocaleString()}원</td>
                        </tr>
                      </tbody>
                    </table>

                    {/* 특이사항 */}
                    <div className="border border-gray-300 rounded">
                      <div className="bg-gray-900 text-white text-center py-2 font-medium">특이사항</div>
                      <div className="p-3 min-h-[60px] text-sm">{order.note || '-'}</div>
                    </div>
                  </div>
                )}

                {/* ========== 거래명세서 ========== */}
                {documentType === 'statement' && (
                  <div className="space-y-6">
                    {/* 제목 */}
                    <div className="text-center border-b-2 border-gray-900 pb-4">
                      <h1 className="text-3xl font-bold tracking-widest">거 래 명 세 서</h1>
                      <p className="text-sm text-gray-600 mt-2">
                        수주번호: {order.orderNo} | 발행일: {new Date().toISOString().split('T')[0]}
                      </p>
                    </div>

                    {/* 공급자 / 공급받는자 */}
                    <div className="grid grid-cols-2 gap-4">
                      <div className="border border-gray-300 rounded">
                        <div className="bg-gray-900 text-white text-center py-2 font-medium">공급자</div>
                        <div className="p-3 space-y-2 text-sm">
                          <div className="flex"><span className="w-20 text-gray-500">상호</span><span>한국방화문(주)</span></div>
                          <div className="flex"><span className="w-20 text-gray-500">대표자</span><span>홍길동</span></div>
                          <div className="flex"><span className="w-20 text-gray-500">사업자번호</span><span>123-45-67890</span></div>
                          <div className="flex"><span className="w-20 text-gray-500">주소</span><span>서울 강남구 테헤란로 123</span></div>
                        </div>
                      </div>
                      <div className="border border-gray-300 rounded">
                        <div className="bg-gray-900 text-white text-center py-2 font-medium">공급받는자</div>
                        <div className="p-3 space-y-2 text-sm">
                          <div className="flex"><span className="w-16 text-gray-500">상호</span><span>{order.customerName}</span></div>
                          <div className="flex"><span className="w-16 text-gray-500">담당자</span><span>{order.manager || '-'}</span></div>
                          <div className="flex"><span className="w-16 text-gray-500">연락처</span><span>{order.contact || '-'}</span></div>
                          <div className="flex"><span className="w-16 text-gray-500">현장명</span><span>{order.siteName}</span></div>
                        </div>
                      </div>
                    </div>

                    {/* 품목 내역 */}
                    <div>
                      <div className="bg-gray-900 text-white text-center py-2 font-medium rounded-t">품목내역</div>
                      <table className="w-full border border-gray-300">
                        <thead className="bg-gray-50">
                          <tr>
                            <th className="border px-2 py-2 text-xs">순번</th>
                            <th className="border px-2 py-2 text-xs">품목코드</th>
                            <th className="border px-2 py-2 text-xs">품명</th>
                            <th className="border px-2 py-2 text-xs">규격</th>
                            <th className="border px-2 py-2 text-xs">수량</th>
                            <th className="border px-2 py-2 text-xs">단위</th>
                            <th className="border px-2 py-2 text-xs">단가</th>
                            <th className="border px-2 py-2 text-xs">공급가액</th>
                          </tr>
                        </thead>
                        <tbody>
                          {(order.items || []).map((item, idx) => (
                            <tr key={idx}>
                              <td className="border px-2 py-2 text-xs text-center">{idx + 1}</td>
                              <td className="border px-2 py-2 text-xs text-center">{item.productCode}</td>
                              <td className="border px-2 py-2 text-xs">{item.productName}</td>
                              <td className="border px-2 py-2 text-xs text-center">{item.spec}</td>
                              <td className="border px-2 py-2 text-xs text-center">{item.qty}</td>
                              <td className="border px-2 py-2 text-xs text-center">{item.unit}</td>
                              <td className="border px-2 py-2 text-xs text-right">{(item.unitPrice || 0).toLocaleString()}</td>
                              <td className="border px-2 py-2 text-xs text-right">{(item.amount || 0).toLocaleString()}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>

                    {/* 금액 상세 */}
                    <div className="border border-gray-300 rounded p-4 space-y-2">
                      <div className="flex justify-between text-sm"><span>공급가액</span><span>{subtotal.toLocaleString()}원</span></div>
                      <div className="flex justify-between text-sm"><span>할인율</span><span className="text-red-500">{discountRate}%</span></div>
                      <div className="flex justify-between text-sm"><span>할인액</span><span className="text-red-500">-{Math.round(subtotal * discountRate / 100).toLocaleString()}원</span></div>
                      <div className="flex justify-between text-sm"><span>할인 후 공급가액</span><span>{Math.round(subtotal * (1 - discountRate / 100)).toLocaleString()}원</span></div>
                      <div className="flex justify-between text-sm"><span>부가세 (10%)</span><span>{Math.round(subtotal * (1 - discountRate / 100) * 0.1).toLocaleString()}원</span></div>
                      <div className="flex justify-between text-base font-bold border-t pt-2 mt-2">
                        <span>합계 금액</span>
                        <span className="text-red-600">₩ {finalTotal.toLocaleString()}</span>
                      </div>
                    </div>

                    {/* 증명 문구 */}
                    <div className="text-center space-y-4 pt-4">
                      <p>위 금액을 거래하였음을 증명합니다.</p>
                      <p>{new Date().toISOString().split('T')[0]}</p>
                      <div className="flex justify-end">
                        <div className="w-24 h-24 border border-gray-300 flex items-center justify-center text-gray-400">
                          인
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {/* ========== 발주서 ========== */}
                {documentType === 'purchaseOrder' && (
                  <div className="space-y-6">
                    {/* 헤더 */}
                    <div className="flex justify-between items-start">
                      <h1 className="text-3xl font-bold tracking-widest">발 주 서</h1>
                      <div className="border border-gray-300">
                        <table className="text-sm">
                          <tbody>
                            <tr>
                              <td className="border px-3 py-1 bg-gray-50">로트번호</td>
                              <td className="border px-3 py-1 font-mono">{order.orderNo}</td>
                            </tr>
                            <tr>
                              <td rowSpan="2" className="border px-3 py-1 bg-gray-50">결재</td>
                              <td className="border">
                                <div className="grid grid-cols-3 text-xs text-center">
                                  <span className="border-r px-2 py-1">작성</span>
                                  <span className="border-r px-2 py-1">검토</span>
                                  <span className="px-2 py-1">승인</span>
                                </div>
                              </td>
                            </tr>
                            <tr>
                              <td className="border">
                                <div className="grid grid-cols-3 text-xs text-center">
                                  <span className="border-r px-2 py-1">전진</span>
                                  <span className="border-r px-2 py-1">회계</span>
                                  <span className="px-2 py-1">생산</span>
                                </div>
                              </td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </div>

                    {/* 신청업체 / 신청내용 */}
                    <div className="space-y-4">
                      <table className="w-full border border-gray-300 text-sm">
                        <tbody>
                          <tr>
                            <td rowSpan="3" className="border px-3 py-2 bg-gray-50 w-24 text-center font-medium">신청업체</td>
                            <td className="border px-3 py-2 bg-gray-50 w-20">발주처</td>
                            <td className="border px-3 py-2">{order.customerName}</td>
                            <td className="border px-3 py-2 bg-gray-50 w-20">발주일</td>
                            <td className="border px-3 py-2">{order.orderDate || order.createdAt?.split(' ')[0]}</td>
                          </tr>
                          <tr>
                            <td className="border px-3 py-2 bg-gray-50">담당자</td>
                            <td className="border px-3 py-2">{order.manager || '-'}</td>
                            <td className="border px-3 py-2 bg-gray-50">연락처</td>
                            <td className="border px-3 py-2">{order.contact || '-'}</td>
                          </tr>
                          <tr>
                            <td className="border px-3 py-2 bg-gray-50">FAX</td>
                            <td className="border px-3 py-2">-</td>
                            <td className="border px-3 py-2 bg-gray-50">설치개소(총)</td>
                            <td className="border px-3 py-2">{order.items?.length || 0}개소</td>
                          </tr>
                        </tbody>
                      </table>

                      <table className="w-full border border-gray-300 text-sm">
                        <tbody>
                          <tr>
                            <td rowSpan="4" className="border px-3 py-2 bg-gray-50 w-24 text-center font-medium">신청내용</td>
                            <td className="border px-3 py-2 bg-gray-50 w-20">현장명</td>
                            <td colSpan="3" className="border px-3 py-2">{order.siteName}</td>
                          </tr>
                          <tr>
                            <td className="border px-3 py-2 bg-gray-50">납기요청일</td>
                            <td colSpan="3" className="border px-3 py-2">{order.dueDate}</td>
                          </tr>
                          <tr>
                            <td className="border px-3 py-2 bg-gray-50">출고일</td>
                            <td className="border px-3 py-2">{order.shippingDate || '-'}</td>
                            <td className="border px-3 py-2 bg-gray-50 w-20">배송방법</td>
                            <td className="border px-3 py-2">{order.deliveryMethod || '상차'}</td>
                          </tr>
                          <tr>
                            <td className="border px-3 py-2 bg-gray-50">납품주소</td>
                            <td colSpan="3" className="border px-3 py-2">{order.deliveryAddress || '-'}</td>
                          </tr>
                        </tbody>
                      </table>
                    </div>

                    {/* 부자재 목록 */}
                    <div>
                      <p className="font-medium mb-2">■ 부자재</p>
                      <table className="w-full border border-gray-300 text-sm">
                        <thead className="bg-gray-50">
                          <tr>
                            <th className="border px-2 py-2 w-12">구분</th>
                            <th className="border px-2 py-2">품명</th>
                            <th className="border px-2 py-2">규격</th>
                            <th className="border px-2 py-2 w-20">길이(mm)</th>
                            <th className="border px-2 py-2 w-16">수량</th>
                            <th className="border px-2 py-2">비고</th>
                          </tr>
                        </thead>
                        <tbody>
                          {(order.items || []).slice(0, 5).map((item, idx) => (
                            <tr key={idx}>
                              <td className="border px-2 py-2 text-center">{idx + 1}</td>
                              <td className="border px-2 py-2">{item.productName}</td>
                              <td className="border px-2 py-2">{item.floor || '-'}</td>
                              <td className="border px-2 py-2 text-center">{item.spec?.split('×')[0] || '-'}</td>
                              <td className="border px-2 py-2 text-center">{item.qty}</td>
                              <td className="border px-2 py-2">-</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>

                    {/* 특이사항 / 유의사항 */}
                    <div className="space-y-3">
                      <div className="border border-gray-300 rounded p-3">
                        <p className="font-medium mb-1">【특이사항】</p>
                        <p className="text-sm text-gray-600">{order.note || '-'}</p>
                      </div>
                      <div className="border border-gray-300 rounded p-3 bg-gray-50">
                        <p className="font-medium mb-2">【 유의사항 】</p>
                        <ul className="text-sm text-gray-600 space-y-1">
                          <li>• 발주서 승인 완료 후 작업을 진행해주시기 바랍니다.</li>
                          <li>• 납기 엄수 부탁드리며, 품질 기준에 맞춰 납품해주시기 바랍니다.</li>
                          <li>• 기타 문의사항은 담당자에게 연락 부탁드립니다.</li>
                        </ul>
                        <p className="text-sm text-center mt-3">문의: 홍길동 | 010-1234-5678</p>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ★ 생산지시 완료 확인 다이얼로그 */}
      {showProductionCompleteDialog && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[100]">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 overflow-hidden">
            {/* 헤더 */}
            <div className="bg-green-50 px-6 py-4 border-b border-green-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-green-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">생산지시 완료</h3>
                  <p className="text-sm text-gray-600">작업지시가 성공적으로 생성되었습니다.</p>
                </div>
              </div>
            </div>

            {/* 내용 */}
            <div className="px-6 py-4">
              {productionCompleteInfo.splitNo && (
                <p className="text-sm text-gray-500 mb-3">
                  분할번호: <span className="font-medium text-gray-900">{productionCompleteInfo.splitNo}</span>
                </p>
              )}

              <div className="bg-gray-50 rounded-lg p-4 mb-4">
                <p className="text-sm font-medium text-gray-700 mb-2">
                  생성된 작업지시 ({productionCompleteInfo.workOrders?.length || 0}건)
                </p>
                <div className="space-y-2">
                  {productionCompleteInfo.workOrders?.map((wo, idx) => (
                    <div key={idx} className="flex items-center gap-2 text-sm">
                      <span className={`w-2 h-2 rounded-full ${wo.processType === '스크린' ? 'bg-blue-500' :
                          wo.processType === '슬랫' ? 'bg-green-500' :
                            wo.processType === '절곡' ? 'bg-orange-500' : 'bg-gray-500'
                        }`}></span>
                      <span className="text-gray-600">{wo.processType}:</span>
                      <span className="font-mono font-medium text-gray-900">{wo.workOrderNo}</span>
                    </div>
                  ))}
                </div>
              </div>

              {productionCompleteInfo.itemCount && (
                <p className="text-sm text-gray-500">
                  품목 수: <span className="font-medium">{productionCompleteInfo.itemCount}건</span>
                </p>
              )}
            </div>

            {/* 버튼 */}
            <div className="px-6 py-4 bg-gray-50 border-t flex justify-end gap-2">
              <Button
                variant="outline"
                onClick={() => setShowProductionCompleteDialog(false)}
              >
                닫기
              </Button>
              <Button
                variant="primary"
                onClick={() => {
                  setShowProductionCompleteDialog(false);
                  onNavigate('work-order-list');
                }}
              >
                <ClipboardList className="w-4 h-4" />
                작업지시 목록 보기
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 수주 취소 모달 */}
      {showCancelModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full">
            <div className="p-6 border-b">
              <h3 className="text-lg font-bold flex items-center gap-2 text-orange-600">
                <XCircle className="w-5 h-5" />
                수주 취소
              </h3>
            </div>
            <div className="p-6">
              {/* 취소 대상 정보 */}
              <div className="mb-4 p-3 bg-gray-50 rounded-lg">
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div className="text-gray-500">수주번호</div>
                  <div className="font-mono font-medium">{order.orderNo}</div>
                  <div className="text-gray-500">발주처</div>
                  <div className="font-medium">{order.customerName}</div>
                  <div className="text-gray-500">현장명</div>
                  <div className="font-medium">{order.siteName}</div>
                  <div className="text-gray-500">현재 상태</div>
                  <div><StatusBadge status={order.status} /></div>
                </div>
              </div>

              {/* 취소 사유 선택 */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  취소 사유 <span className="text-red-500">*</span>
                </label>
                <select
                  value={cancelReason}
                  onChange={(e) => setCancelReason(e.target.value)}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500"
                >
                  <option value="">취소 사유를 선택하세요</option>
                  <option value="고객요청">고객 요청</option>
                  <option value="계약무산">계약 무산</option>
                  <option value="프로젝트연기">프로젝트 연기</option>
                  <option value="중복등록">중복 등록</option>
                  <option value="단가변경">단가 변경으로 인한 재등록</option>
                  <option value="기타">기타</option>
                </select>
              </div>

              {/* 상세 사유 입력 */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  상세 사유
                </label>
                <textarea
                  value={cancelReasonDetail}
                  onChange={(e) => setCancelReasonDetail(e.target.value)}
                  placeholder="취소 사유에 대한 상세 내용을 입력하세요"
                  rows={3}
                  className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500"
                />
              </div>

              {/* 경고 메시지 */}
              <div className="bg-orange-50 border border-orange-200 rounded-lg p-3 text-sm text-orange-700">
                <p className="font-medium mb-1">취소 시 유의사항</p>
                <ul className="list-disc list-inside space-y-1">
                  <li>취소된 수주는 목록에서 '취소' 상태로 표시됩니다</li>
                  <li>취소 후에는 수정이 불가능합니다</li>
                  <li>관련된 생산지시가 있는 경우 먼저 생산지시를 취소해야 합니다</li>
                </ul>
              </div>
            </div>
            <div className="p-4 border-t bg-gray-50 flex justify-end gap-2">
              <button
                onClick={() => { setShowCancelModal(false); setCancelReason(''); setCancelReasonDetail(''); }}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg"
              >
                닫기
              </button>
              <button
                onClick={() => {
                  if (!cancelReason) {
                    alert('취소 사유를 선택해주세요.');
                    return;
                  }
                  if (onCancelOrder) {
                    onCancelOrder(order.id, {
                      reason: cancelReason,
                      reasonDetail: cancelReasonDetail,
                      cancelledAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
                      cancelledBy: '현재 사용자',
                    });
                  }
                  setShowCancelModal(false);
                  setCancelReason('');
                  setCancelReasonDetail('');
                  onBack?.();
                }}
                disabled={!cancelReason}
                className={`px-4 py-2 rounded-lg flex items-center gap-2 ${cancelReason
                    ? 'bg-orange-600 text-white hover:bg-orange-700'
                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                  }`}
              >
                <XCircle className="w-4 h-4" />
                취소 확정
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 견적 선택 모달
const QuoteSelectModal = ({ isOpen, onClose, onSelect, quotes }) => {
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const itemsPerPage = 10;

  // 샘플 견적 데이터 (실제로는 props로 받음)
  const sampleQuotes = [
    {
      id: 1, quoteNo: 'KD-PR-250110-01', customerName: '서울건축', siteName: '강남 오피스텔 A동', totalAmount: 52000000, status: '최종확정', dueDate: '2025-02-28', deliveryAddress: '서울시 강남구 테헤란로 123', manager: '이담당', contact: '010-1234-5678', items: [
        { id: 1, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'A-01', spec: '7660×2550', qty: 1, unit: 'EA', unitPrice: 9000000, amount: 9000000 },
        { id: 2, productCode: 'SCR-001', productName: '스크린 셔터 (표준형)', floor: '1층', location: 'A-02', spec: '6500×2400', qty: 1, unit: 'EA', unitPrice: 8500000, amount: 8500000 },
      ]
    },
    { id: 2, quoteNo: 'KD-PR-250115-01', customerName: '인천건설', siteName: '송도 오피스텔 B동', totalAmount: 28000000, status: '최종확정', dueDate: '2025-03-15', deliveryAddress: '인천시 연수구 송도동 45', manager: '최담당', contact: '010-2345-6789', items: [] },
    { id: 3, quoteNo: 'KD-PR-250118-01', customerName: '(주)서울인테리어', siteName: '해운대 주상복합', totalAmount: 75000000, status: '최종확정', dueDate: '2025-04-01', deliveryAddress: '부산시 해운대구 우동 123', manager: '박담당', contact: '010-3456-7890', items: [] },
    { id: 4, quoteNo: 'KD-PR-250120-01', customerName: '대전건설', siteName: '유성 오피스텔', totalAmount: 32000000, status: '견적발송', dueDate: '2025-04-15', deliveryAddress: '대전시 유성구 봉명동 56', manager: '김담당', contact: '010-4567-8901', items: [] },
    { id: 5, quoteNo: 'KD-PR-250122-01', customerName: '광주건설', siteName: '상무 주상복합', totalAmount: 45000000, status: '최종확정', dueDate: '2025-05-01', deliveryAddress: '광주시 서구 치평동 78', manager: '정담당', contact: '010-5678-9012', items: [] },
    { id: 6, quoteNo: 'KD-PR-250125-01', customerName: '울산건설', siteName: '삼산 오피스텔', totalAmount: 38000000, status: '최종확정', dueDate: '2025-05-15', deliveryAddress: '울산시 남구 삼산동 90', manager: '조담당', contact: '010-6789-0123', items: [] },
    { id: 7, quoteNo: 'KD-PR-250128-01', customerName: '제주건설', siteName: '연동 주상복합', totalAmount: 55000000, status: '최종확정', dueDate: '2025-06-01', deliveryAddress: '제주시 연동 123', manager: '한담당', contact: '010-7890-1234', items: [] },
    { id: 8, quoteNo: 'KD-PR-250130-01', customerName: '세종건설', siteName: '세종 아파트', totalAmount: 62000000, status: '최종확정', dueDate: '2025-06-15', deliveryAddress: '세종시 보람동 123', manager: '강담당', contact: '010-8901-2345', items: [] },
  ];

  const allQuotes = quotes?.length > 0 ? quotes : sampleQuotes;

  // 최종확정 상태만 필터링
  const filteredQuotes = allQuotes
    .filter(q => q.status === '최종확정')
    .filter(q =>
      search === '' ||
      q.quoteNo.toLowerCase().includes(search.toLowerCase()) ||
      q.customerName.includes(search) ||
      q.siteName.includes(search)
    )
    .sort((a, b) => new Date(b.quoteDate) - new Date(a.quoteDate)); // 최신순 정렬

  // 페이지네이션
  const totalPages = Math.ceil(filteredQuotes.length / itemsPerPage);
  const paginatedQuotes = filteredQuotes.slice(
    (page - 1) * itemsPerPage,
    page * itemsPerPage
  );

  const handleSelect = (quote) => {
    onSelect(quote);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl w-full max-w-4xl max-h-[85vh] overflow-hidden flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b">
          <div className="flex items-center gap-3">
            <FileText className="w-6 h-6 text-blue-500" />
            <div>
              <h2 className="text-lg font-bold text-gray-900">견적 선택</h2>
              <p className="text-sm text-gray-500">확정된 견적 중 선택하세요</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg">
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* 검색 */}
        <div className="p-4 border-b">
          <SearchInput
            placeholder="견적번호, 발주처, 현장명 검색..."
            value={search}
            onChange={(val) => { setSearch(val); setPage(1); }}
          />
          <div className="text-sm text-gray-500 mt-2">
            확정된 견적 {filteredQuotes.length}건
          </div>
        </div>

        {/* 목록 */}
        <div className="flex-1 overflow-y-auto p-4">
          {paginatedQuotes.length === 0 ? (
            <div className="text-center py-12 text-gray-500">
              <FileText className="w-16 h-16 mx-auto mb-4 text-gray-300" />
              <p className="text-lg font-medium">확정된 견적이 없습니다</p>
              <p className="text-sm mt-1">견적관리에서 견적을 확정해주세요.</p>
            </div>
          ) : (
            <table className="w-full">
              <thead className="bg-gray-50 sticky top-0">
                <tr>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">견적번호</th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">발주처</th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">현장명</th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">담당자</th>
                  <th className="px-3 py-3 text-right text-xs font-medium text-gray-500">금액</th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">납기일</th>
                  <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">선택</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {paginatedQuotes.map(quote => (
                  <tr key={quote.id} className="hover:bg-gray-50">
                    <td className="px-3 py-3">
                      <span className="font-mono text-blue-600 text-sm">{quote.quoteNo}</span>
                    </td>
                    <td className="px-3 py-3 text-sm text-gray-900">{quote.customerName}</td>
                    <td className="px-3 py-3 text-sm text-gray-700 max-w-[200px] truncate">{quote.siteName}</td>
                    <td className="px-3 py-3 text-sm text-gray-600">{quote.manager}</td>
                    <td className="px-3 py-3 text-sm text-gray-900 text-right font-medium">
                      {(quote.totalAmount / 10000).toLocaleString()}만원
                    </td>
                    <td className="px-3 py-3 text-sm text-gray-600">{quote.dueDate}</td>
                    <td className="px-3 py-3 text-center">
                      <Button variant="outline" size="sm" onClick={() => handleSelect(quote)}>
                        선택
                      </Button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {/* 페이지네이션 */}
        {totalPages > 1 && (
          <div className="flex items-center justify-center gap-2 p-4 border-t">
            <button
              onClick={() => setPage(p => Math.max(1, p - 1))}
              disabled={page === 1}
              className="px-3 py-1.5 text-sm rounded-lg border hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              이전
            </button>
            <span className="text-sm text-gray-600">
              {page} / {totalPages}
            </span>
            <button
              onClick={() => setPage(p => Math.min(totalPages, p + 1))}
              disabled={page === totalPages}
              className="px-3 py-1.5 text-sm rounded-lg border hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              다음
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

// 수주 등록
const OrderCreate = ({ quotes = [], fromQuote = null, additionalItems = null, relatedOrders = [], isAdditional = false, onNavigate, onBack, onSave }) => {
  const [selectedQuote, setSelectedQuote] = useState(fromQuote);
  const [showQuotePanel, setShowQuotePanel] = useState(false);
  const [quoteSearch, setQuoteSearch] = useState('');

  // 직접 입력용 품목 상태
  const [directItems, setDirectItems] = useState([]);

  // fromQuote가 있을 때 초기 품목 자동 설정
  useEffect(() => {
    if (fromQuote?.items?.length > 0 && directItems.length === 0) {
      setDirectItems(fromQuote.items.map(item => ({
        id: item.id,
        productCode: `PRD-${item.id}`,
        productName: item.productName,
        category: item.category || '스크린',  // 카테고리 유지 (생산지시 공정 분리에 필요)
        floor: item.floor || '',
        location: item.location || '',
        spec: item.width && item.height ? `${item.width}×${item.height}` : (item.spec || ''),
        width: item.width || 0,
        height: item.height || 0,
        qty: item.qty || 1,
        unit: 'EA',
        unitPrice: item.unitPrice || 0,
        amount: item.amount || 0,
      })));
    }
  }, [fromQuote]);

  // 추가분인 경우 초기 데이터 설정
  const initialDueDate = fromQuote?.dueDate || '';
  const initialAmount = isAdditional && additionalItems
    ? additionalItems.reduce((sum, item) => sum + (item.amount || 0), 0)
    : fromQuote?.totalAmount || 0;

  const [formData, setFormData] = useState({
    orderDate: new Date().toISOString().split('T')[0],
    dueDate: initialDueDate,
    deliveryMethod: '직접배차',
    receiverName: fromQuote?.manager || '',
    receiverPhone: fromQuote?.contact || '',
    deliveryAddress: fromQuote?.deliveryAddress || '',
    note: isAdditional ? '추가 발주' : (fromQuote?.note || ''),
    // 기본 정보
    customerName: fromQuote?.customerName || '',
    customerId: fromQuote?.customerId || '',
    siteName: fromQuote?.siteName || '',
    manager: fromQuote?.manager || '',
    contact: fromQuote?.contact || '',
    totalAmount: initialAmount,
  });

  // 유효성 검사 규칙
  const validationRules = {
    customerName: { required: true, label: '발주처', message: '발주처를 입력해주세요.' },
    siteName: { required: true, label: '현장명', message: '현장명을 입력해주세요.' },
    dueDate: { required: true, label: '납기일', message: '납기일을 선택해주세요.' },
  };

  const { errors, touched, hasError, getFieldError, validateForm, handleBlur, clearFieldError } = useFormValidation(formData, validationRules);

  // 견적 필터링
  const availableQuotes = sampleQuotesData.filter(q => q.status === '최종확정');
  const filteredQuotes = availableQuotes
    .filter(q =>
      q.quoteNo.toLowerCase().includes(quoteSearch.toLowerCase()) ||
      q.customerName.includes(quoteSearch) ||
      q.siteName.includes(quoteSearch)
    )
    .sort((a, b) => new Date(b.quoteDate) - new Date(a.quoteDate)); // 최신순 정렬

  // 배송방식 옵션 (선불/착불 구분)
  const deliveryMethodOptions = [
    { id: 'pickup-prepaid', label: '상차(선불)', category: '상차' },
    { id: 'pickup-collect', label: '상차(착불)', category: '상차' },
    { id: 'direct', label: '직접배차', category: '직접' },
    { id: 'self', label: '직접수령', category: '직접' },
    { id: 'kyungdong-prepaid', label: '경동화물(선불)', category: '화물' },
    { id: 'kyungdong-collect', label: '경동화물(착불)', category: '화물' },
    { id: 'kyungdong-parcel-prepaid', label: '경동택배(선불)', category: '택배' },
    { id: 'kyungdong-parcel-collect', label: '경동택배(착불)', category: '택배' },
    { id: 'daesin-prepaid', label: '대신화물(선불)', category: '화물' },
    { id: 'daesin-collect', label: '대신화물(착불)', category: '화물' },
    { id: 'daesin-parcel-prepaid', label: '대신택배(선불)', category: '택배' },
    { id: 'daesin-parcel-collect', label: '대신택배(착불)', category: '택배' },
  ];

  // 추가분 수주번호 생성
  const generateAdditionalOrderNo = () => {
    if (isAdditional && relatedOrders.length > 0) {
      const baseOrderNo = relatedOrders[0].orderNo;
      const existingAdditionals = relatedOrders.filter(o => o.orderType === 'additional');
      const suffix = String.fromCharCode(65 + existingAdditionals.length); // A, B, C...
      return `${baseOrderNo}-${suffix}`;
    }
    return null;
  };

  // 견적 선택 시 폼 데이터 채우기
  const handleQuoteSelect = (quote) => {
    setSelectedQuote(quote);
    setShowQuotePanel(false);
    // 폼 데이터 자동 채우기
    setFormData(prev => ({
      ...prev,
      dueDate: quote.dueDate || prev.dueDate,
      deliveryAddress: quote.deliveryAddress || prev.deliveryAddress,
      receiverName: quote.manager || prev.receiverName,
      receiverPhone: quote.contact || prev.receiverPhone,
      customerName: quote.customerName,
      customerId: quote.customerId,
      siteName: quote.siteName,
      manager: quote.manager,
      contact: quote.contact,
      totalAmount: quote.totalAmount,
    }));
    // 품목도 채우기
    if (quote.items?.length > 0) {
      setDirectItems(quote.items.map(item => ({
        id: item.id,
        productCode: `PRD-${item.id}`,
        productName: item.productName,
        category: item.category || '스크린',  // 카테고리 유지 (생산지시 공정 분리에 필요)
        floor: item.floor || '',
        location: item.location || '',
        spec: item.width && item.height ? `${item.width}×${item.height}` : (item.spec || ''),
        width: item.width || 0,
        height: item.height || 0,
        qty: item.qty || 1,
        unit: 'EA',
        unitPrice: item.unitPrice || 0,
        amount: item.amount || 0,
      })));
    }
  };

  // 견적 연결 해제
  const handleClearQuote = () => {
    setSelectedQuote(null);
  };

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 품목 상세 편집 모달 상태
  const [showItemModal, setShowItemModal] = useState(false);
  const [editingItem, setEditingItem] = useState(null);
  const [itemForm, setItemForm] = useState({
    productCode: '',
    productName: '국민방화스크린셔터',
    floor: '',
    location: '',
    openWidth: '',
    openHeight: '',
    qty: 1,
    unitPrice: 8000000,
    guideRailType: '백면형',
    guideRailSpec: '120-70',
    finish: 'SUS마감',
  });

  // 품목 추가 모달 열기
  const handleAddItem = () => {
    setEditingItem(null);
    setItemForm({
      productCode: '',
      productName: '국민방화스크린셔터',
      floor: '',
      location: '',
      openWidth: '',
      openHeight: '',
      qty: 1,
      unitPrice: 8000000,
      guideRailType: '백면형',
      guideRailSpec: '120-70',
      finish: 'SUS마감',
    });
    setShowItemModal(true);
  };

  // 품목 수정 모달 열기
  const handleEditItem = (item) => {
    setEditingItem(item);
    const spec = item.productionSpec || {};
    setItemForm({
      productCode: item.productCode || '',
      productName: item.productName || '국민방화스크린셔터',
      floor: item.floor || '',
      location: item.location || '',
      openWidth: spec.openWidth || item.spec?.split('×')[0] || '',
      openHeight: spec.openHeight || item.spec?.split('×')[1] || '',
      qty: item.qty || 1,
      unitPrice: item.unitPrice || 8000000,
      guideRailType: spec.guideRailType || '백면형',
      guideRailSpec: spec.guideRailSpec || '120-70',
      finish: spec.finish || 'SUS마감',
    });
    setShowItemModal(true);
  };

  // 품목 저장 (추가/수정)
  const handleSaveItem = () => {
    const openW = parseInt(itemForm.openWidth) || 0;
    const openH = parseInt(itemForm.openHeight) || 0;

    // 제작사이즈 자동 계산
    const prodWidth = openW + 140;
    const prodHeight = Math.max(openH + 400, 2950);
    const shaft = openW > 6000 ? 5 : 4;
    const capacity = openW > 6000 ? 300 : 160;

    const newItem = {
      id: editingItem?.id || Date.now(),
      productCode: itemForm.productCode || `SCR-${Date.now()}`,
      productName: itemForm.productName,
      floor: itemForm.floor,
      location: itemForm.location,
      spec: `${openW}×${openH}`,
      qty: parseInt(itemForm.qty) || 1,
      unit: 'EA',
      unitPrice: parseInt(itemForm.unitPrice) || 0,
      amount: (parseInt(itemForm.qty) || 1) * (parseInt(itemForm.unitPrice) || 0),
      productionSpec: {
        type: '와이어',
        drawingNo: `${itemForm.floor} ${itemForm.location}`,
        openWidth: openW,
        openHeight: openH,
        prodWidth,
        prodHeight,
        guideRailType: itemForm.guideRailType,
        guideRailSpec: itemForm.guideRailSpec,
        shaft,
        caseSpec: '500-330',
        motorBracket: '380-180',
        capacity,
        finish: itemForm.finish,
      },
    };

    if (editingItem) {
      setDirectItems(prev => prev.map(item => item.id === editingItem.id ? newItem : item));
    } else {
      setDirectItems(prev => [...prev, newItem]);
    }

    setShowItemModal(false);
  };

  // 품목 삭제
  const handleRemoveItem = (itemId) => {
    setDirectItems(prev => prev.filter(item => item.id !== itemId));
  };

  // 기존 handleItemChange는 간단한 필드용으로 유지
  const handleItemChange = (itemId, field, value) => {
    setDirectItems(prev => prev.map(item => {
      if (item.id === itemId) {
        const updated = { ...item, [field]: value };
        if (field === 'qty' || field === 'unitPrice') {
          updated.amount = (updated.qty || 0) * (updated.unitPrice || 0);
        }
        return updated;
      }
      return item;
    }));
  };

  // 총액 계산
  const calculateTotal = () => {
    return directItems.reduce((sum, item) => sum + (item.amount || 0), 0);
  };

  // 날짜를 YYMMDD 형식으로 변환
  const formatDateCode = (date) => {
    const d = new Date(date);
    const yy = String(d.getFullYear()).slice(-2);
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const dd = String(d.getDate()).padStart(2, '0');
    return `${yy}${mm}${dd}`;
  };

  const handleSubmit = () => {
    // 유효성 검사 실행
    if (!validateForm()) {
      return;
    }

    // 수주번호 생성
    let orderNo;
    if (isAdditional && relatedOrders.length > 0) {
      // 추가분 수주번호: 원 수주번호-A, B, C...
      orderNo = generateAdditionalOrderNo();
    } else {
      // 신규 수주번호: KD-SO-YYMMDD-순번
      const dateCode = formatDateCode(formData.orderDate);
      const seq = String(Math.floor(Math.random() * 99) + 1).padStart(2, '0');
      orderNo = `KD-SO-${dateCode}-${seq}`;
    }

    // 품목 결정 (제작 스펙 자동 생성 포함)
    let orderItems;
    if (isAdditional && additionalItems) {
      orderItems = additionalItems.map((item, idx) => {
        const spec = item.width && item.height ? `${item.width}×${item.height}` : '-';
        const newItem = {
          id: item.id,
          productCode: item.productCode || `PRD-${item.id}`,
          productName: item.productName,
          category: item.category || '스크린',  // 카테고리 유지 (생산지시 공정 분리에 필요)
          floor: item.floor || '-',
          location: item.location || '-',
          spec,
          width: item.width || 0,
          height: item.height || 0,
          qty: item.qty,
          unit: 'EA',
          unitPrice: item.unitPrice || 0,
          amount: item.amount || 0,
        };
        // 제작 스펙 자동 생성
        newItem.productionSpec = generateProductionSpec(newItem, idx);
        return newItem;
      });
    } else {
      orderItems = directItems.map((item, idx) => ({
        ...item,
        category: item.category || '스크린',  // 카테고리 유지
        productionSpec: generateProductionSpec(item, idx),
      }));
    }

    // 모터 스펙 및 BOM 자동 생성
    const motorSpec = generateMotorSpec(orderItems);
    const bomData = generateBomData(orderItems);

    // 견적에서 산출된 품목 리스트 (있으면 사용)
    const calculatedItems = selectedQuote?.calculatedItems || fromQuote?.calculatedItems || [];

    const newOrder = {
      id: Date.now(),
      orderNo,
      orderDate: formData.orderDate,
      quoteId: selectedQuote?.id || fromQuote?.id || null,
      quoteNo: selectedQuote?.quoteNo || fromQuote?.quoteNo || null,
      orderType: isAdditional ? 'additional' : (selectedQuote ? 'from-quote' : 'direct'),
      parentOrderNo: isAdditional ? relatedOrders[0]?.orderNo : null,
      customerId: formData.customerId || null,
      customerName: formData.customerName,
      creditGrade: selectedQuote?.creditGrade || fromQuote?.creditGrade || initialCustomers.find(c => c.id === formData.customerId)?.creditGrade || 'B',
      siteName: formData.siteName,
      siteCode: `PJ-${String(new Date().getFullYear()).slice(-2)}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}-${String(Math.floor(Math.random() * 99) + 1).padStart(2, '0')}`,
      manager: formData.manager,
      contact: formData.contact,
      dueDate: formData.dueDate,
      status: '수주등록',
      paymentStatus: '미입금',
      accountingStatus: '미확인',
      accountingConfirmedBy: null,
      accountingConfirmedAt: null,
      deliveryMethod: formData.deliveryMethod,
      totalAmount: calculateTotal() || formData.totalAmount,
      deliveryAddress: formData.deliveryAddress,
      receiverName: formData.receiverName,
      receiverPhone: formData.receiverPhone,
      items: orderItems,
      motorSpec,  // 모터/전장품 스펙
      bomData,    // 절곡물 BOM
      calculatedItems, // ★ 견적에서 산출된 품목 리스트 (공정별 작업지시에 사용)
      splits: [],
      documentHistory: [],
      changeHistory: [],
      createdAt: formData.orderDate,
      createdBy: '현재 사용자',
      note: formData.note,
    };

    onSave?.(newOrder);
    // 저장 후 상세 페이지로 이동 (생산지시 바로 가능하도록)
    onNavigate?.('order-detail', newOrder);
  };

  const canSubmit = isAdditional
    ? true  // 추가분은 이미 데이터가 있음
    : (formData.customerName && formData.siteName);

  // ���고예정일/납품요청일 미정 체크박스 상태
  const [shippingDateUndecided, setShippingDateUndecided] = useState(false);
  const [deliveryDateUndecided, setDeliveryDateUndecided] = useState(false);
  // 운임비용 상태
  const [freightCost, setFreightCost] = useState('선불');
  // 배송지 주소 분리
  const [deliveryZipcode, setDeliveryZipcode] = useState('');
  const [deliveryAddressBase, setDeliveryAddressBase] = useState('');
  const [deliveryAddressDetail, setDeliveryAddressDetail] = useState('');

  return (
    <div className="space-y-4">
      {/* 상단 헤더 */}
      <div className="flex items-center justify-between py-2">
        <div className="flex items-center gap-3">
          <h1 className="text-xl font-bold text-gray-900">
            {isAdditional ? '수주 등록 (추가분)' : '수주 등록'}
          </h1>
          {isAdditional && relatedOrders.length > 0 && (
            <span className="text-sm text-gray-500 ml-2">
              원 수주: <span className="font-mono text-blue-600">{relatedOrders[0]?.orderNo}</span>
            </span>
          )}
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={onBack}>
            <X className="w-4 h-4" /> 취소
          </Button>
          <Button variant="primary" onClick={handleSubmit} disabled={!canSubmit}>
            <Save className="w-4 h-4" /> 저장
          </Button>
        </div>
      </div>

      {/* 추가분 수주인 경우 별도 UI */}
      {isAdditional ? (
        <div className="space-y-6">
          {/* 견적 정보 (읽기 전용) */}
          <Card title="견적 정보">
            <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
              <div className="flex items-center gap-2 mb-2">
                <CheckCircle className="w-5 h-5 text-blue-600" />
                <span className="font-mono text-blue-600 font-medium">{fromQuote?.quoteNo}</span>
              </div>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                <div>
                  <span className="text-gray-500">발주처</span>
                  <p className="font-medium text-gray-900">{fromQuote?.customerName}</p>
                </div>
                <div>
                  <span className="text-gray-500">현장명</span>
                  <p className="font-medium text-gray-900">{fromQuote?.siteName}</p>
                </div>
                <div>
                  <span className="text-gray-500">담당자</span>
                  <p className="font-medium text-gray-900">{fromQuote?.manager}</p>
                </div>
                <div>
                  <span className="text-gray-500">추가분 금액</span>
                  <p className="font-bold text-blue-600 text-lg">
                    {additionalItems?.reduce((sum, i) => sum + (i.amount || 0), 0).toLocaleString()}원
                  </p>
                </div>
              </div>
            </div>
          </Card>

          {/* 추가분 품목 */}
          <Card title={`추가분 품목 (${additionalItems?.length || 0}건)`}>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">층/부호</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">규격</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">수량</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">금액</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {additionalItems?.map(item => (
                    <tr key={item.id}>
                      <td className="px-4 py-3 text-sm">{item.productName}</td>
                      <td className="px-4 py-3 text-sm">{item.floor || '-'}/{item.location || '-'}</td>
                      <td className="px-4 py-3 text-sm">{item.width && item.height ? `${item.width}×${item.height}` : '-'}</td>
                      <td className="px-4 py-3 text-sm text-right">{item.qty}</td>
                      <td className="px-4 py-3 text-sm text-right font-medium">{item.amount?.toLocaleString()}원</td>
                    </tr>
                  ))}
                </tbody>
                <tfoot className="bg-gray-50">
                  <tr>
                    <td colSpan={4} className="px-4 py-3 text-sm font-medium text-right">합계</td>
                    <td className="px-4 py-3 text-sm font-bold text-blue-600 text-right">
                      {additionalItems?.reduce((sum, i) => sum + (i.amount || 0), 0).toLocaleString()}원
                    </td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </Card>

          {/* 배송 정보 */}
          <Card title="배송 정보">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">납품예정일 *</label>
                <input
                  type="date"
                  value={formData.dueDate}
                  onChange={(e) => handleChange('dueDate', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div className="col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-2">배송방식</label>
                <div className="grid grid-cols-4 gap-x-4 gap-y-2 p-3 border border-gray-200 rounded-lg bg-gray-50">
                  {deliveryMethodOptions.map(option => (
                    <label key={option.id} className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="radio"
                        name="deliveryMethod"
                        value={option.label}
                        checked={formData.deliveryMethod === option.label}
                        onChange={(e) => handleChange('deliveryMethod', e.target.value)}
                        className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="text-sm text-gray-700">{option.label}</span>
                    </label>
                  ))}
                </div>
              </div>
              <div className="col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-1">수신처 주소</label>
                <input
                  type="text"
                  value={formData.deliveryAddress}
                  onChange={(e) => handleChange('deliveryAddress', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">수신(반장/업체)</label>
                <input
                  type="text"
                  value={formData.receiverName}
                  onChange={(e) => handleChange('receiverName', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">수신처 연락처</label>
                <input
                  type="text"
                  value={formData.receiverPhone}
                  onChange={(e) => handleChange('receiverPhone', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div className="col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <textarea
                  value={formData.note}
                  onChange={(e) => handleChange('note', e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
            </div>
          </Card>
        </div>
      ) : (
        /* ========== 일반 수주 등록 (스크린샷 UI) ========== */
        <div className="space-y-4">
          {/* 견적 불러오기 섹션 */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div className="px-4 py-3 bg-gray-50 border-b">
              <h3 className="text-sm font-semibold text-gray-700">견적 불러오기</h3>
            </div>
            <div className="p-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  {selectedQuote ? (
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-mono text-blue-600 font-bold">{selectedQuote.quoteNo}</span>
                        <CreditGradeBadge grade={selectedQuote.creditGrade} />
                      </div>
                      <p className="text-sm text-gray-600 mt-0.5">
                        {selectedQuote.customerName} / {selectedQuote.siteName} / {selectedQuote.totalAmount?.toLocaleString()}원
                      </p>
                    </div>
                  ) : (
                    <span className="text-gray-500 text-sm">확정된 견적을 선택하면 정보가 자동으로 채워집니다</span>
                  )}
                </div>
                <div className="flex items-center gap-2">
                  {selectedQuote && (
                    <Button variant="ghost" size="sm" onClick={handleClearQuote}>
                      <X className="w-4 h-4" /> 해제
                    </Button>
                  )}
                  <Button variant="primary" size="sm" onClick={() => setShowQuotePanel(true)}>
                    <FileText className="w-4 h-4" /> 견적 선택
                  </Button>
                </div>
              </div>
            </div>
          </div>

          {/* 기본 정보 섹션 */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div className="px-4 py-3 bg-gray-50 border-b">
              <h3 className="text-sm font-semibold text-gray-700">기본 정보</h3>
            </div>
            <div className="p-4">
              <div className="grid grid-cols-3 gap-x-8 gap-y-4">
                <div>
                  <label className="block text-sm text-gray-500 mb-1">발주처 <span className="text-red-500">*</span></label>
                  {selectedQuote ? (
                    <div className="px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-gray-900">{formData.customerName}</div>
                  ) : (
                    <select
                      value={formData.customerId}
                      onChange={(e) => {
                        const customer = initialCustomers.find(c => c.id === e.target.value);
                        handleChange('customerId', e.target.value);
                        handleChange('customerName', customer?.customerName || '');
                        clearFieldError('customerName');
                      }}
                      onBlur={() => handleBlur('customerName')}
                      className={getInputClassName(hasError('customerName'))}
                    >
                      <option value="">발주처를 선택하세요</option>
                      {initialCustomers.filter(c => c.customerType === '고객사').map(customer => (
                        <option key={customer.id} value={customer.id}>
                          {customer.customerName} ({customer.creditGrade}등급)
                        </option>
                      ))}
                    </select>
                  )}
                  {hasError('customerName') && <p className="text-xs text-red-500 mt-1">{getFieldError('customerName')}</p>}
                </div>
                <div>
                  <label className="block text-sm text-gray-500 mb-1">현장명 <span className="text-red-500">*</span></label>
                  <input
                    type="text"
                    value={formData.siteName}
                    onChange={(e) => {
                      handleChange('siteName', e.target.value);
                      clearFieldError('siteName');
                    }}
                    onBlur={() => handleBlur('siteName')}
                    className={`${getInputClassName(hasError('siteName'))} ${selectedQuote ? 'bg-gray-50' : ''}`}
                    placeholder="현장명 입력"
                    readOnly={!!selectedQuote}
                  />
                  {hasError('siteName') && <p className="text-xs text-red-500 mt-1">{getFieldError('siteName')}</p>}
                </div>
                <div>
                  <label className="block text-sm text-gray-500 mb-1">담당자</label>
                  <input
                    type="text"
                    value={formData.manager}
                    onChange={(e) => handleChange('manager', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="담당자 이름"
                  />
                </div>
                <div>
                  <label className="block text-sm text-gray-500 mb-1">연락처</label>
                  <input
                    type="text"
                    value={formData.contact}
                    onChange={(e) => handleChange('contact', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="010-0000-0000"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* 수주/배송 정보 섹션 */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div className="px-4 py-3 bg-gray-50 border-b">
              <h3 className="text-sm font-semibold text-gray-700">수주/배송 정보</h3>
            </div>
            <div className="p-4">
              <div className="grid grid-cols-3 gap-x-8 gap-y-4">
                {/* 출고예정일 */}
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <label className="text-sm text-gray-500">출고예정일</label>
                    <label className="flex items-center gap-1 text-xs text-gray-500">
                      <input
                        type="checkbox"
                        checked={shippingDateUndecided}
                        onChange={(e) => setShippingDateUndecided(e.target.checked)}
                        className="w-3.5 h-3.5 rounded"
                      />
                      미정
                    </label>
                  </div>
                  <input
                    type="date"
                    value={formData.orderDate}
                    onChange={(e) => handleChange('orderDate', e.target.value)}
                    disabled={shippingDateUndecided}
                    className={`w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${shippingDateUndecided ? 'bg-gray-100 text-gray-400' : ''}`}
                  />
                </div>
                {/* 납품요청일 */}
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <label className="text-sm text-gray-500">납품요청일 <span className="text-red-500">*</span></label>
                    <label className="flex items-center gap-1 text-xs text-gray-500">
                      <input
                        type="checkbox"
                        checked={deliveryDateUndecided}
                        onChange={(e) => setDeliveryDateUndecided(e.target.checked)}
                        className="w-3.5 h-3.5 rounded"
                      />
                      미정
                    </label>
                  </div>
                  <input
                    type="date"
                    value={formData.dueDate}
                    onChange={(e) => {
                      handleChange('dueDate', e.target.value);
                      clearFieldError('dueDate');
                    }}
                    onBlur={() => handleBlur('dueDate')}
                    disabled={deliveryDateUndecided}
                    className={`${getInputClassName(hasError('dueDate'))} ${deliveryDateUndecided ? 'bg-gray-100 text-gray-400' : ''}`}
                  />
                  {hasError('dueDate') && <p className="text-xs text-red-500 mt-1">{getFieldError('dueDate')}</p>}
                </div>
                {/* 배송방식 */}
                <div>
                  <label className="block text-sm text-gray-500 mb-1">배송방식</label>
                  <select
                    value={formData.deliveryMethod}
                    onChange={(e) => handleChange('deliveryMethod', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="상차">상차</option>
                    <option value="직접배차">직접배차</option>
                    <option value="직접수령">직접수령</option>
                    <option value="경동화물">경동화물</option>
                    <option value="경동택배">경동택배</option>
                    <option value="대신화물">대신화물</option>
                    <option value="대신택배">대신택배</option>
                  </select>
                </div>
                {/* 운임비용 */}
                <div>
                  <label className="block text-sm text-gray-500 mb-1">운임비용</label>
                  <select
                    value={freightCost}
                    onChange={(e) => setFreightCost(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="선불">선불</option>
                    <option value="착불">착불</option>
                    <option value="무료">무료</option>
                  </select>
                </div>
                {/* 수신(반장/업체) */}
                <div>
                  <label className="block text-sm text-gray-500 mb-1">수신(반장/업체) <span className="text-red-500">*</span></label>
                  <input
                    type="text"
                    value={formData.receiverName}
                    onChange={(e) => handleChange('receiverName', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="수신(반장/업체) 이름"
                  />
                </div>
                {/* 수신처 연락처 */}
                <div>
                  <label className="block text-sm text-gray-500 mb-1">수신처 연락처 <span className="text-red-500">*</span></label>
                  <input
                    type="text"
                    value={formData.receiverPhone}
                    onChange={(e) => handleChange('receiverPhone', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="010-0000-0000"
                  />
                </div>
                {/* 수신처 주소 */}
                <div className="col-span-3">
                  <label className="block text-sm text-gray-500 mb-1">수신처 주소 <span className="text-red-500">*</span></label>
                  <div className="flex gap-2 mb-2">
                    <input
                      type="text"
                      value={deliveryZipcode}
                      onChange={(e) => setDeliveryZipcode(e.target.value)}
                      className="w-28 px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="우편번호"
                    />
                    <Button variant="outline" size="sm" onClick={() => alert('우편번호 검색 기능')}>
                      <Search className="w-4 h-4" /> 우편번호 찾기
                    </Button>
                  </div>
                  <input
                    type="text"
                    value={deliveryAddressBase}
                    onChange={(e) => setDeliveryAddressBase(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg mb-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="기본 주소 (우편번호 검색 후 자동 입력됩니다)"
                  />
                  <input
                    type="text"
                    value={deliveryAddressDetail}
                    onChange={(e) => setDeliveryAddressDetail(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="상세 주소를 입력하세요"
                  />
                </div>
                {/* 비고 */}
                <div className="col-span-3">
                  <label className="block text-sm text-gray-500 mb-1">비고</label>
                  <textarea
                    value={formData.note}
                    onChange={(e) => handleChange('note', e.target.value)}
                    rows={2}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="특이사항"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* 품목 내역 섹션 */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div className="flex items-center justify-between px-4 py-3 bg-gray-50 border-b">
              <h3 className="text-sm font-semibold text-gray-700">품목 내역</h3>
              <Button variant="outline" size="sm" onClick={handleAddItem}>
                <Plus className="w-4 h-4" /> 품목 추가
              </Button>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50 border-b">
                  <tr>
                    <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 w-14">순번</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 w-24">품목코드</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">품명</th>
                    <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 w-16">층</th>
                    <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 w-16">부호</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 w-28">규격</th>
                    <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 w-16">수량</th>
                    <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 w-14">단위</th>
                    <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 w-24">단가</th>
                    <th className="px-3 py-2 text-right text-xs font-medium text-gray-500 w-28">금액</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {directItems.length === 0 ? (
                    <tr>
                      <td colSpan={10} className="px-4 py-8 text-center text-gray-400">
                        품목을 추가해주세요
                      </td>
                    </tr>
                  ) : (
                    directItems.map((item, idx) => (
                      <tr key={item.id} className="hover:bg-gray-50">
                        <td className="px-3 py-2 text-sm text-gray-500 text-center">{idx + 1}</td>
                        <td className="px-3 py-2 text-sm font-mono text-gray-900">{item.productCode || '-'}</td>
                        <td className="px-3 py-2 text-sm text-gray-900">{item.productName}</td>
                        <td className="px-3 py-2 text-sm text-gray-900 text-center">{item.floor || '-'}</td>
                        <td className="px-3 py-2 text-sm text-gray-900 text-center">{item.location || '-'}</td>
                        <td className="px-3 py-2 text-sm text-gray-900">{item.spec || `${item.productionSpec?.openWidth || '-'}×${item.productionSpec?.openHeight || '-'}`}</td>
                        <td className="px-3 py-2 text-sm text-gray-900 text-right">{item.qty}</td>
                        <td className="px-3 py-2 text-sm text-gray-900 text-center">{item.unit || 'EA'}</td>
                        <td className="px-3 py-2 text-sm text-gray-900 text-right">{(item.unitPrice || 0).toLocaleString()}</td>
                        <td className="px-3 py-2 text-sm font-medium text-gray-900 text-right">{(item.amount || 0).toLocaleString()}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
            {/* 합계 영역 */}
            <div className="border-t bg-gray-50 px-4 py-3">
              <div className="flex justify-end">
                <div className="w-64 space-y-1">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">소계</span>
                    <span className="font-medium text-gray-900">{calculateTotal().toLocaleString()}원</span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">할인율</span>
                    <span className="font-medium text-red-500">0 %</span>
                  </div>
                  <div className="flex items-center justify-between text-sm pt-2 border-t border-gray-200">
                    <span className="font-semibold text-gray-700">총금액</span>
                    <span className="font-bold text-lg text-blue-600">{calculateTotal().toLocaleString()}원</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* 품목 추가/수정 모달 */}
          {showItemModal && (
            <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
              <div className="bg-white rounded-xl w-full max-w-2xl">
                <div className="flex items-center justify-between p-4 border-b">
                  <div className="flex items-center gap-2">
                    <h3 className="font-bold">{editingItem ? '품목 수정' : '품목 추가'}</h3>
                  </div>
                  <button onClick={() => setShowItemModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                    ✕
                  </button>
                </div>

                <div className="p-6 space-y-6">
                  {/* 위치 정보 */}
                  <div className="grid grid-cols-3 gap-4">
                    <FormField label="층" required>
                      <TextInput
                        value={itemForm.floor}
                        onChange={(e) => setItemForm(prev => ({ ...prev, floor: e.target.value }))}
                        placeholder="예: 4층"
                      />
                    </FormField>
                    <FormField label="도면부호" required>
                      <TextInput
                        value={itemForm.location}
                        onChange={(e) => setItemForm(prev => ({ ...prev, location: e.target.value }))}
                        placeholder="예: FSS1"
                      />
                    </FormField>
                    <FormField label="품목명">
                      <TextInput
                        value={itemForm.productName}
                        onChange={(e) => setItemForm(prev => ({ ...prev, productName: e.target.value }))}
                      />
                    </FormField>
                  </div>

                  {/* 오픈 사이즈 (고객 제공) */}
                  <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                    <h4 className="font-medium text-green-800 mb-3">오픈사이즈 (고객 제공 치수)</h4>
                    <div className="grid grid-cols-2 gap-4">
                      <FormField label="가로 (mm)" required>
                        <TextInput
                          type="number"
                          value={itemForm.openWidth}
                          onChange={(e) => setItemForm(prev => ({ ...prev, openWidth: e.target.value }))}
                          placeholder="예: 7260"
                        />
                      </FormField>
                      <FormField label="세로 (mm)" required>
                        <TextInput
                          type="number"
                          value={itemForm.openHeight}
                          onChange={(e) => setItemForm(prev => ({ ...prev, openHeight: e.target.value }))}
                          placeholder="예: 2600"
                        />
                      </FormField>
                    </div>
                  </div>

                  {/* 제작 사이즈 (자동 계산) */}
                  {itemForm.openWidth && itemForm.openHeight && (
                    <div className="p-4 bg-red-50 rounded-lg border border-red-200">
                      <h4 className="font-medium text-red-800 mb-3">제작사이즈 (자동 계산)</h4>
                      <div className="grid grid-cols-4 gap-4 text-sm">
                        <div>
                          <p className="text-gray-500">가로</p>
                          <p className="font-bold text-red-700 text-lg">{(parseInt(itemForm.openWidth) + 140).toLocaleString()}</p>
                        </div>
                        <div>
                          <p className="text-gray-500">세로</p>
                          <p className="font-bold text-red-700 text-lg">{Math.max(parseInt(itemForm.openHeight) + 400, 2950).toLocaleString()}</p>
                        </div>
                        <div>
                          <p className="text-gray-500">샤프트</p>
                          <p className="font-bold">{parseInt(itemForm.openWidth) > 6000 ? '5"' : '4"'}</p>
                        </div>
                        <div>
                          <p className="text-gray-500">모터용량</p>
                          <p className="font-bold">{parseInt(itemForm.openWidth) > 6000 ? '300K' : '160K'}</p>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* 스펙 옵션 */}
                  <div className="grid grid-cols-3 gap-4">
                    <FormField label="가이드레일 타입">
                      <Select
                        options={[
                          { value: '백면형', label: '백면형 (120-70)' },
                          { value: '측면형', label: '측면형 (120-120)' },
                        ]}
                        value={itemForm.guideRailType}
                        onChange={(e) => setItemForm(prev => ({
                          ...prev,
                          guideRailType: e.target.value,
                          guideRailSpec: e.target.value === '백면형' ? '120-70' : '120-120'
                        }))}
                      />
                    </FormField>
                    <FormField label="마감">
                      <Select
                        options={[
                          { value: 'SUS마감', label: 'SUS마감' },
                          { value: '도장마감', label: '도장마감' },
                          { value: '분체마감', label: '분체마감' },
                        ]}
                        value={itemForm.finish}
                        onChange={(e) => setItemForm(prev => ({ ...prev, finish: e.target.value }))}
                      />
                    </FormField>
                    <FormField label="단가 (원)">
                      <TextInput
                        type="number"
                        value={itemForm.unitPrice}
                        onChange={(e) => setItemForm(prev => ({ ...prev, unitPrice: e.target.value }))}
                      />
                    </FormField>
                  </div>
                </div>

                <div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
                  <Button variant="outline" onClick={() => setShowItemModal(false)}>취소</Button>
                  <Button
                    variant="primary"
                    onClick={handleSaveItem}
                    disabled={!itemForm.floor || !itemForm.location || !itemForm.openWidth || !itemForm.openHeight}
                  >
                    <Check className="w-4 h-4" /> {editingItem ? '수정' : '추가'}
                  </Button>
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* 견적 선택 모달 */}
      {showQuotePanel && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between p-4 border-b">
              <h3 className="text-lg font-bold">견적 선택</h3>
              <button onClick={() => setShowQuotePanel(false)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="p-4 space-y-4 overflow-y-auto flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input type="text" value={quoteSearch} onChange={(e) => setQuoteSearch(e.target.value)} placeholder="견적번호, 거래처, 현장명 검색..." className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
              </div>
              <p className="text-sm text-gray-500">전환 가능한 견적 {availableQuotes.length}건 (최종확정 상태)</p>
              <div className="divide-y max-h-96 overflow-y-auto border rounded-lg">
                {filteredQuotes.length === 0 ? (
                  <div className="p-8 text-center text-gray-500"><p>전환 가능한 견적이 없습니다</p></div>
                ) : (
                  filteredQuotes.map((quote) => (
                    <div key={quote.id} onClick={() => handleQuoteSelect(quote)} className={`p-4 hover:bg-blue-50 cursor-pointer transition-colors ${selectedQuote?.id === quote.id ? 'bg-blue-50 border-l-4 border-l-blue-500' : ''}`}>
                      <div className="flex items-center justify-between">
                        <div>
                          <div className="flex items-center gap-2 mb-1"><span className="font-mono text-blue-600 font-bold">{quote.quoteNo}</span><CreditGradeBadge grade={quote.creditGrade} /></div>
                          <p className="text-sm text-gray-900">{quote.customerName}</p>
                          <p className="text-sm text-gray-500">{quote.siteName}</p>
                        </div>
                        <div className="text-right">
                          <p className="font-bold text-gray-900">{quote.totalAmount?.toLocaleString()}원</p>
                          <p className="text-xs text-gray-500">{quote.items?.length || 0}개 품목</p>
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 수주 수정
const OrderEdit = ({ order, onNavigate, onBack, onSave }) => {
  const [formData, setFormData] = useState({
    dueDate: order?.dueDate || '',
    shippingDate: order?.shippingDate || '',
    deliveryMethod: order?.deliveryMethod || '상차',
    freightCost: order?.freightCost || '선불',
    receiverName: order?.receiverName || '',
    receiverPhone: order?.receiverPhone || '',
    deliveryAddress: order?.deliveryAddress || '',
    note: order?.note || '',
  });

  // 출고예정일/납품요청일 미정 상태
  const [shippingDateUndecided, setShippingDateUndecided] = useState(!order?.shippingDate);
  const [deliveryDateUndecided, setDeliveryDateUndecided] = useState(!order?.dueDate);

  // 품목 목록 상태
  const [items, setItems] = useState(order?.items || []);
  const [showItemModal, setShowItemModal] = useState(false);
  const [editingItem, setEditingItem] = useState(null);
  const [itemForm, setItemForm] = useState({
    productCode: '',
    productName: '',
    floor: '',
    location: '',
    spec: '',
    qty: 1,
    unit: 'EA',
    unitPrice: 0,
  });

  // 생산 시작 후에는 품목 수정 불가
  const isProductionStarted = order?.status === '생산중' || order?.status === '생산완료';
  const canEditItems = order?.status === '수주확정';

  const unitTypes = ['EA', 'SET', 'M', 'M2'];

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 품목 추가/수정 모달 열기
  const handleAddItem = () => {
    if (!canEditItems) {
      alert('생산이 시작된 수주는 품목을 수정할 수 없습니다.');
      return;
    }
    setEditingItem(null);
    setItemForm({
      productCode: '',
      productName: '',
      floor: '',
      location: '',
      spec: '',
      qty: 1,
      unit: 'EA',
      unitPrice: 0,
    });
    setShowItemModal(true);
  };

  const handleEditItem = (item, index) => {
    if (!canEditItems) {
      alert('생산이 시작된 수주는 품목을 수정할 수 없습니다.');
      return;
    }
    setEditingItem(index);
    setItemForm({
      productCode: item.productCode || '',
      productName: item.productName || '',
      floor: item.floor || '',
      location: item.location || '',
      spec: item.spec || '',
      qty: item.qty || 1,
      unit: item.unit || 'EA',
      unitPrice: item.unitPrice || 0,
    });
    setShowItemModal(true);
  };

  const handleSaveItem = () => {
    if (!itemForm.productName || !itemForm.floor || !itemForm.location) {
      alert('품목명, 층, 부호는 필수입니다.');
      return;
    }

    const qty = parseInt(itemForm.qty) || 1;
    const unitPrice = parseInt(itemForm.unitPrice) || 0;

    const newItem = {
      id: editingItem !== null ? items[editingItem].id : Date.now(),
      productCode: itemForm.productCode || `ITEM-${String(items.length + 1).padStart(3, '0')}`,
      productName: itemForm.productName,
      floor: itemForm.floor,
      location: itemForm.location,
      spec: itemForm.spec,
      qty: qty,
      unit: itemForm.unit,
      unitPrice: unitPrice,
      amount: qty * unitPrice,
    };

    if (editingItem !== null) {
      setItems(prev => prev.map((item, idx) => idx === editingItem ? newItem : item));
    } else {
      setItems(prev => [...prev, newItem]);
    }
    setShowItemModal(false);
    setEditingItem(null);
  };

  const handleDeleteItem = (index) => {
    if (!canEditItems) {
      alert('생산이 시작된 수주는 품목을 삭제할 수 없습니다.');
      return;
    }
    if (confirm('이 품목을 삭제하시겠습니까?')) {
      setItems(prev => prev.filter((_, idx) => idx !== index));
    }
  };

  // 합계 계산
  const totalQty = items.reduce((sum, item) => sum + (item.qty || 0), 0);
  const totalAmount = items.reduce((sum, item) => sum + (item.amount || 0), 0);

  const handleSubmit = () => {
    if (items.length === 0) {
      alert('최소 1개 이상의 품목이 필요합니다.');
      return;
    }

    const history = {
      id: Date.now(),
      changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
      changeType: '수주정보수정',
      description: '수주 정보가 수정되었습니다.',
      changedBy: '현재 사용자',
    };

    onSave?.({
      ...order,
      ...formData,
      items: items,
      totalQty: totalQty,
      totalAmount: totalAmount,
      changeHistory: [...(order.changeHistory || []), history],
    });
    onBack();
  };

  if (!order) return null;

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between py-2">
        <div className="flex items-center gap-3">
          <h1 className="text-xl font-bold text-gray-900">수주 수정</h1>
          <span className="text-sm text-gray-500 font-mono bg-gray-100 px-2 py-1 rounded">{order.orderNo}</span>
          <StatusBadge status={order.status} />
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={onBack}>
            <X className="w-4 h-4" /> 취소
          </Button>
          <Button variant="primary" onClick={handleSubmit}>
            <Save className="w-4 h-4" /> 저장
          </Button>
        </div>
      </div>

      {/* 상태별 안내 메시지 */}
      {isProductionStarted && (
        <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 flex items-start gap-3">
          <AlertCircle className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
          <div>
            <p className="font-medium text-yellow-800">생산이 시작된 수주입니다</p>
            <p className="text-sm text-yellow-700">배송 정보(납기일, 배송방식, 수령인 등)만 수정 가능합니다. 품목 변경이 필요한 경우 생산팀에 문의하세요.</p>
          </div>
        </div>
      )}

      {/* 기본 정보 (읽기 전용) */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
        <h2 className="text-base font-semibold text-gray-900 mb-4">기본 정보</h2>
        <div className="grid grid-cols-4 gap-x-8 gap-y-4">
          <div>
            <label className="text-sm text-gray-500 block mb-1">로트번호</label>
            <p className="text-sm font-medium text-gray-900">{order.orderNo}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500 block mb-1">견적번호</label>
            <p className="text-sm font-medium text-gray-900">{order.quoteNo || '-'}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500 block mb-1">담당자</label>
            <p className="text-sm font-medium text-gray-900">{order.salesperson || '김판매'}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500 block mb-1">발주처</label>
            <p className="text-sm font-medium text-gray-900">{order.customerName}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500 block mb-1">현장명</label>
            <p className="text-sm font-medium text-blue-600">{order.siteName}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500 block mb-1">담당자</label>
            <p className="text-sm font-medium text-gray-900">{order.manager}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500 block mb-1">연락처</label>
            <p className="text-sm font-medium text-gray-900">{order.contact}</p>
          </div>
        </div>
      </div>

      {/* 수주/배송 정보 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
        <h2 className="text-base font-semibold text-gray-900 mb-4">수주/배송 정보</h2>
        <div className="grid grid-cols-3 gap-x-8 gap-y-4">
          {/* 출고예정일 */}
          <div>
            <div className="flex items-center justify-between mb-1">
              <label className="text-sm text-gray-500">출고예정일</label>
              <label className="flex items-center gap-1 text-xs text-gray-500">
                <input
                  type="checkbox"
                  checked={shippingDateUndecided}
                  onChange={(e) => setShippingDateUndecided(e.target.checked)}
                  className="w-3.5 h-3.5 rounded"
                />
                미정
              </label>
            </div>
            <input
              type="date"
              value={formData.shippingDate}
              onChange={(e) => handleChange('shippingDate', e.target.value)}
              disabled={shippingDateUndecided}
              className={`w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${shippingDateUndecided ? 'bg-gray-100 text-gray-400' : ''}`}
            />
          </div>

          {/* 납품요청일 */}
          <div>
            <div className="flex items-center justify-between mb-1">
              <label className="text-sm text-gray-500">납품요청일</label>
              <label className="flex items-center gap-1 text-xs text-gray-500">
                <input
                  type="checkbox"
                  checked={deliveryDateUndecided}
                  onChange={(e) => setDeliveryDateUndecided(e.target.checked)}
                  className="w-3.5 h-3.5 rounded"
                />
                미정
              </label>
            </div>
            <input
              type="date"
              value={formData.dueDate}
              onChange={(e) => handleChange('dueDate', e.target.value)}
              disabled={deliveryDateUndecided}
              className={`w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${deliveryDateUndecided ? 'bg-gray-100 text-gray-400' : ''}`}
            />
          </div>

          {/* 배송방식 */}
          <div>
            <label className="text-sm text-gray-500 block mb-1">배송방식</label>
            <select
              value={formData.deliveryMethod}
              onChange={(e) => handleChange('deliveryMethod', e.target.value)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="상차">상차</option>
              <option value="배송">배송</option>
              <option value="직납">직납</option>
              <option value="택배">택배</option>
            </select>
          </div>

          {/* 운임비용 */}
          <div>
            <label className="text-sm text-gray-500 block mb-1">운임비용</label>
            <select
              value={formData.freightCost}
              onChange={(e) => handleChange('freightCost', e.target.value)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="선불">선불</option>
              <option value="착불">착불</option>
              <option value="무료">무료</option>
            </select>
          </div>

          {/* 수신(반장/업체) */}
          <div>
            <label className="text-sm text-gray-500 block mb-1">수신(반장/업체)</label>
            <input
              type="text"
              value={formData.receiverName}
              onChange={(e) => handleChange('receiverName', e.target.value)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="수신(반장/업체) 이름"
            />
          </div>

          {/* 수신처 연락처 */}
          <div>
            <label className="text-sm text-gray-500 block mb-1">수신처 연락처</label>
            <input
              type="text"
              value={formData.receiverPhone}
              onChange={(e) => handleChange('receiverPhone', e.target.value)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="010-0000-0000"
            />
          </div>

          {/* 수신처 주소 - 전체 너비 */}
          <div className="col-span-3">
            <label className="text-sm text-gray-500 block mb-1">수신처 주소</label>
            <div className="flex gap-2">
              <input
                type="text"
                value={formData.deliveryAddress?.split(' ')[0] || ''}
                placeholder="우편번호"
                className="w-32 px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                readOnly
              />
              <input
                type="text"
                value={formData.deliveryAddress}
                onChange={(e) => handleChange('deliveryAddress', e.target.value)}
                className="flex-1 px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="기본주소"
              />
              <input
                type="text"
                placeholder="상세주소"
                className="w-48 px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>

          {/* 비고 - 전체 너비 */}
          <div className="col-span-3">
            <label className="text-sm text-gray-500 block mb-1">비고</label>
            <textarea
              value={formData.note}
              onChange={(e) => handleChange('note', e.target.value)}
              rows={2}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="배송 관련 특이사항을 입력하세요"
            />
          </div>
        </div>
      </div>

      {/* 품목 내역 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-base font-semibold text-gray-900">품목 내역</h2>
          {canEditItems ? (
            <Button variant="outline" size="sm" onClick={handleAddItem}>
              <Plus className="w-4 h-4" /> 품목 추가
            </Button>
          ) : (
            <span className="text-xs text-gray-400">생산 시작 후 수정 불가</span>
          )}
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">No</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목코드</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">층</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">부호</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">규격(mm)</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">수량</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">단위</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">단가</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">금액</th>
                {canEditItems && <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">관리</th>}
              </tr>
            </thead>
            <tbody className="divide-y">
              {items.map((item, idx) => (
                <tr key={idx} className="hover:bg-gray-50">
                  <td className="px-4 py-3 text-sm text-gray-500">{idx + 1}</td>
                  <td className="px-4 py-3 text-sm font-mono text-gray-900">{item.productCode}</td>
                  <td className="px-4 py-3 text-sm text-gray-900">{item.productName}</td>
                  <td className="px-4 py-3 text-sm text-gray-900">{item.floor}</td>
                  <td className="px-4 py-3 text-sm text-gray-900">{item.location}</td>
                  <td className="px-4 py-3 text-sm text-gray-900">{item.spec || `${item.productionSpec?.openWidth || '-'}×${item.productionSpec?.openHeight || '-'}`}</td>
                  <td className="px-4 py-3 text-sm text-gray-900 text-right">{item.qty}</td>
                  <td className="px-4 py-3 text-sm text-gray-900">{item.unit || 'EA'}</td>
                  <td className="px-4 py-3 text-sm text-gray-900 text-right">{item.unitPrice?.toLocaleString()}</td>
                  <td className="px-4 py-3 text-sm font-medium text-gray-900 text-right">{item.amount?.toLocaleString()}</td>
                  {canEditItems && (
                    <td className="px-4 py-3 text-center">
                      <div className="flex items-center justify-center gap-1">
                        <button
                          onClick={() => handleEditItem(item, idx)}
                          className="p-1 text-gray-400 hover:text-blue-600"
                        >
                          <Edit className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDeleteItem(idx)}
                          className="p-1 text-gray-400 hover:text-red-600"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {items.length === 0 && (
          <div className="text-center py-8 text-gray-500">
            <Package className="w-12 h-12 mx-auto mb-2 text-gray-300" />
            <p>등록된 품목이 없습니다</p>
            {canEditItems && (
              <button onClick={handleAddItem} className="text-blue-600 hover:underline mt-2">
                + 품목 추가하기
              </button>
            )}
          </div>
        )}

        {/* 합계 영역 */}
        {items.length > 0 && (
          <div className="mt-4 pt-4 border-t border-gray-100">
            <div className="flex justify-end">
              <div className="w-72 space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">소계</span>
                  <span className="font-medium">{totalAmount.toLocaleString()}원</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">할인율</span>
                  <span className="font-medium text-red-500">0%</span>
                </div>
                <div className="flex justify-between text-base pt-2 border-t border-gray-200">
                  <span className="font-semibold text-gray-900">총금액</span>
                  <span className="font-bold text-blue-600">{totalAmount.toLocaleString()}원</span>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 품목 추가/수정 모달 */}
      {showItemModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl w-full max-w-md">
            <div className="flex items-center justify-between p-4 border-b">
              <h3 className="font-bold">{editingItem !== null ? '품목 수정' : '품목 추가'}</h3>
              <button onClick={() => setShowItemModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-4 space-y-4">
              {/* 품목코드/품목명 */}
              <div className="grid grid-cols-2 gap-3">
                <FormField label="품목코드">
                  <input
                    type="text"
                    value={itemForm.productCode}
                    onChange={(e) => setItemForm(prev => ({ ...prev, productCode: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                    placeholder="자동생성"
                  />
                </FormField>
                <FormField label="품목명" required>
                  <input
                    type="text"
                    value={itemForm.productName}
                    onChange={(e) => setItemForm(prev => ({ ...prev, productName: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                    placeholder="슬랫 셔터"
                  />
                </FormField>
              </div>

              {/* 층/부호 */}
              <div className="grid grid-cols-2 gap-3">
                <FormField label="층" required>
                  <input
                    type="text"
                    value={itemForm.floor}
                    onChange={(e) => setItemForm(prev => ({ ...prev, floor: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                    placeholder="1층"
                  />
                </FormField>
                <FormField label="부호" required>
                  <input
                    type="text"
                    value={itemForm.location}
                    onChange={(e) => setItemForm(prev => ({ ...prev, location: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                    placeholder="G-01"
                  />
                </FormField>
              </div>

              {/* 규격 */}
              <FormField label="규격(mm)">
                <input
                  type="text"
                  value={itemForm.spec}
                  onChange={(e) => setItemForm(prev => ({ ...prev, spec: e.target.value }))}
                  className="w-full px-3 py-2 border rounded-lg"
                  placeholder="4000×2000"
                />
              </FormField>

              {/* 수량/단위/단가 */}
              <div className="grid grid-cols-3 gap-3">
                <FormField label="수량">
                  <input
                    type="number"
                    value={itemForm.qty}
                    onChange={(e) => setItemForm(prev => ({ ...prev, qty: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                    min="1"
                  />
                </FormField>
                <FormField label="단위">
                  <select
                    value={itemForm.unit}
                    onChange={(e) => setItemForm(prev => ({ ...prev, unit: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                  >
                    {unitTypes.map(u => (
                      <option key={u} value={u}>{u}</option>
                    ))}
                  </select>
                </FormField>
                <FormField label="단가(원)">
                  <input
                    type="number"
                    value={itemForm.unitPrice}
                    onChange={(e) => setItemForm(prev => ({ ...prev, unitPrice: e.target.value }))}
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </FormField>
              </div>

              {/* 금액 계산 */}
              <div className="p-3 bg-gray-50 rounded-lg flex justify-between items-center">
                <span className="text-gray-600">금액</span>
                <span className="text-lg font-bold text-blue-600">
                  {((parseInt(itemForm.qty) || 0) * (parseInt(itemForm.unitPrice) || 0)).toLocaleString()}원
                </span>
              </div>
            </div>
            <div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
              <Button variant="outline" onClick={() => setShowItemModal(false)}>취소</Button>
              <Button variant="primary" onClick={handleSaveItem}>
                {editingItem !== null ? '수정' : '추가'}
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};


// ============ 작업지시 관리 ============

// 작업지시 목록
// ============ 제품 이력 추적 (Traceability) ============
const ProductTraceability = ({ workOrders, workResults, onNavigate }) => {
  const [searchType, setSearchType] = useState('lot'); // lot, workOrder, order, product
  const [searchValue, setSearchValue] = useState('');
  const [traceResult, setTraceResult] = useState(null);
  const [selectedNode, setSelectedNode] = useState(null);

  // 샘플 추적 데이터
  const sampleTraceData = {
    'KD-WE-250215-01-절곡': {
      lotNo: 'KD-WE-250215-01-절곡',
      productName: 'KD 웨이브 블라인드',
      workOrderNo: 'KD-KD-WO-2502-0012-01',
      orderNo: 'KD-TS-250200-12',
      customer: '삼성SDI 기흥캠퍼스',
      productionDate: '2025-02-15',
      status: '출하완료',
      timeline: [
        {
          step: 1, stage: '원자재 입고', date: '2025-02-10', lotNo: 'RM-250210-001',
          details: { materialName: '슬랫(웨이브)', supplier: '삼성SDI', qty: '100EA', iqcResult: '합격', inspector: '김품질' }
        },
        {
          step: 2, stage: '수입검사(IQC)', date: '2025-02-10', lotNo: 'IQC-250210-001',
          details: { inspectionType: '수입검사', result: '합격', defectQty: 0, inspector: '김품질', checkItems: ['외관검사', '치수검사', '성적서 확인'] }
        },
        {
          step: 3, stage: '자재 출고', date: '2025-02-12', lotNo: 'MO-250212-001',
          details: { fromLocation: '원자재창고', toLocation: '생산라인', qty: '50EA', issuedBy: '박자재' }
        },
        {
          step: 4, stage: '절곡 작업', date: '2025-02-15', lotNo: 'KD-WE-250215-01-절곡',
          details: { processName: '절곡', workOrderNo: 'KD-KD-WO-2502-0012-01', worker: '김생산', goodQty: 48, defectQty: 2, machine: '절곡기-01' }
        },
        {
          step: 5, stage: '중간검사(PQC)', date: '2025-02-15', lotNo: 'PQC-250215-001',
          details: { inspectionType: '중간검사', result: '합격', sampleQty: 5, defectQty: 0, inspector: '이품질', checkItems: ['외관', '치수', '동작'] }
        },
        {
          step: 6, stage: '포밍 작업', date: '2025-02-16', lotNo: 'KD-WE-250216-01-포밍',
          details: { processName: '포밍', workOrderNo: 'KD-KD-WO-2502-0012-02', worker: '박생산', goodQty: 48, defectQty: 0, machine: '포밍기-02' }
        },
        {
          step: 7, stage: '최종검사(FQC)', date: '2025-02-17', lotNo: 'FQC-250217-001',
          details: { inspectionType: '최종검사', result: '합격', totalQty: 48, passQty: 48, failQty: 0, inspector: '최품질' }
        },
        {
          step: 8, stage: '포장/라벨링', date: '2025-02-17', lotNo: 'PKG-250217-001',
          details: { packagingType: '골판지박스', labelInfo: 'KD-WE-250215', palletNo: 'PLT-001', packedBy: '정포장' }
        },
        {
          step: 9, stage: '출하', date: '2025-02-18', lotNo: 'SHP-250218-001',
          details: { shipmentNo: 'SH-2502-0008', deliveryAddress: '경기도 용인시 기흥구', carrier: '삼성물류', driverName: '김운송' }
        }
      ],
      inputMaterials: [
        { materialCode: 'SLT-WV-01', materialName: '슬랫(웨이브)', lotNo: 'RM-250210-001', qty: 50, supplier: '삼성SDI' },
        { materialCode: 'END-CAP-01', materialName: '엔드캡', lotNo: 'RM-250208-003', qty: 100, supplier: '부품공업' },
        { materialCode: 'CORD-01', materialName: '조작줄', lotNo: 'RM-250209-002', qty: 50, supplier: '로프텍' }
      ],
      relatedWorkOrders: [
        { woNo: 'KD-KD-WO-2502-0012-01', processName: '절곡', status: '완료', completedQty: 48 },
        { woNo: 'KD-KD-WO-2502-0012-02', processName: '포밍', status: '완료', completedQty: 48 },
        { woNo: 'KD-KD-WO-2502-0012-03', processName: '포장', status: '완료', completedQty: 48 }
      ],
      qualityRecords: [
        { type: 'IQC', date: '2025-02-10', result: '합격', inspector: '김품질' },
        { type: 'PQC', date: '2025-02-15', result: '합격', inspector: '이품질' },
        { type: 'FQC', date: '2025-02-17', result: '합격', inspector: '최품질' }
      ]
    }
  };

  const handleSearch = () => {
    if (!searchValue.trim()) {
      alert('검색어를 입력하세요.');
      return;
    }
    // 샘플 데이터에서 검색 (실제로는 API 호출)
    const found = sampleTraceData[searchValue] || sampleTraceData['KD-WE-250215-01-절곡'];
    setTraceResult(found);
    setSelectedNode(null);
  };

  const getStageColor = (stage) => {
    const colors = {
      '원자재 입고': 'bg-blue-100 border-blue-500 text-blue-700',
      '수입검사(IQC)': 'bg-green-100 border-green-500 text-green-700',
      '자재 출고': 'bg-yellow-100 border-yellow-500 text-yellow-700',
      '절곡 작업': 'bg-purple-100 border-purple-500 text-purple-700',
      '중간검사(PQC)': 'bg-green-100 border-green-500 text-green-700',
      '포밍 작업': 'bg-purple-100 border-purple-500 text-purple-700',
      '최종검사(FQC)': 'bg-green-100 border-green-500 text-green-700',
      '포장/라벨링': 'bg-orange-100 border-orange-500 text-orange-700',
      '출하': 'bg-red-100 border-red-500 text-red-700',
    };
    return colors[stage] || 'bg-gray-100 border-gray-500 text-gray-700';
  };

  const getStageIcon = (stage) => {
    const icons = {
      '원자재 입고': '📦',
      '수입검사(IQC)': '🔍',
      '자재 출고': '📤',
      '절곡 작업': '⚙️',
      '중간검사(PQC)': '✅',
      '포밍 작업': '⚙️',
      '최종검사(FQC)': '🏆',
      '포장/라벨링': '📋',
      '출하': '🚚',
    };
    return icons[stage] || '📍';
  };

  return (
    <div className="p-4 space-y-4">
      {/* 페이지 헤더 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold">제품 이력 추적</h1>
          <p className="text-sm text-gray-500">원자재 입고부터 출하까지 전체 제조 이력을 추적합니다</p>
        </div>
      </div>

      {/* 검색 영역 */}
      <div className="bg-white rounded border p-4">
        <div className="flex gap-4 items-end">
          <div className="flex-1">
            <label className="block text-sm font-medium mb-1">검색 유형</label>
            <select
              value={searchType}
              onChange={(e) => setSearchType(e.target.value)}
              className="w-full border rounded px-3 py-2 text-sm"
            >
              <option value="lot">LOT 번호</option>
              <option value="workOrder">작업지시 번호</option>
              <option value="order">수주 번호</option>
              <option value="product">제품명</option>
            </select>
          </div>
          <div className="flex-[2]">
            <label className="block text-sm font-medium mb-1">검색어</label>
            <input
              type="text"
              value={searchValue}
              onChange={(e) => setSearchValue(e.target.value)}
              placeholder="예: KD-WE-250215-01-절곡"
              className="w-full border rounded px-3 py-2 text-sm"
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            />
          </div>
          <button
            onClick={handleSearch}
            className="px-6 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-2"
          >
            <Search className="w-4 h-4" />
            추적 조회
          </button>
        </div>
        <div className="mt-2 text-xs text-gray-500">
          * 샘플 데이터: "KD-WE-250215-01-절곡" 을 입력하여 테스트할 수 있습니다.
        </div>
      </div>

      {/* 검색 결과 */}
      {traceResult && (
        <div className="space-y-4">
          {/* 제품 정보 요약 */}
          <div className="bg-white rounded border p-4">
            <h2 className="text-lg font-bold mb-3 flex items-center gap-2">
              <Package className="w-5 h-5" /> 제품 정보
            </h2>
            <div className="grid grid-cols-4 gap-4">
              <div>
                <div className="text-xs text-gray-500">LOT 번호</div>
                <div className="font-medium">{traceResult.lotNo}</div>
              </div>
              <div>
                <div className="text-xs text-gray-500">제품명</div>
                <div className="font-medium">{traceResult.productName}</div>
              </div>
              <div>
                <div className="text-xs text-gray-500">수주번호</div>
                <div className="font-medium">{traceResult.orderNo}</div>
              </div>
              <div>
                <div className="text-xs text-gray-500">거래처</div>
                <div className="font-medium">{traceResult.customer}</div>
              </div>
              <div>
                <div className="text-xs text-gray-500">작업지시 번호</div>
                <div className="font-medium">{traceResult.workOrderNo}</div>
              </div>
              <div>
                <div className="text-xs text-gray-500">생산일자</div>
                <div className="font-medium">{traceResult.productionDate}</div>
              </div>
              <div>
                <div className="text-xs text-gray-500">현재 상태</div>
                <span className={`px-2 py-1 rounded text-xs font-medium ${traceResult.status === '출하완료' ? 'bg-green-100 text-green-800' :
                    traceResult.status === '생산중' ? 'bg-blue-100 text-blue-800' :
                      'bg-gray-100 text-gray-800'
                  }`}>{traceResult.status}</span>
              </div>
            </div>
          </div>

          {/* 제조 이력 타임라인 */}
          <div className="bg-white rounded border p-4">
            <h2 className="text-lg font-bold mb-4 flex items-center gap-2">
              <GitBranch className="w-5 h-5" /> 제조 이력 타임라인
            </h2>
            <div className="relative">
              {/* 타임라인 라인 */}
              <div className="absolute left-8 top-0 bottom-0 w-0.5 bg-gray-300"></div>

              <div className="space-y-4">
                {traceResult.timeline.map((item, idx) => (
                  <div
                    key={idx}
                    className={`relative flex items-start gap-4 cursor-pointer hover:bg-gray-50 p-2 rounded ${selectedNode === idx ? 'bg-blue-50' : ''}`}
                    onClick={() => setSelectedNode(selectedNode === idx ? null : idx)}
                  >
                    {/* 단계 번호 */}
                    <div className={`relative z-10 w-16 h-16 rounded-full flex flex-col items-center justify-center border-2 ${getStageColor(item.stage)}`}>
                      <span className="text-lg">{getStageIcon(item.stage)}</span>
                      <span className="text-xs font-bold">{item.step}</span>
                    </div>

                    {/* 내용 */}
                    <div className="flex-1 pt-1">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="font-bold">{item.stage}</span>
                        <span className="text-xs text-gray-500">{item.date}</span>
                      </div>
                      <div className="text-sm text-gray-600">LOT: {item.lotNo}</div>

                      {/* 상세 정보 (선택 시 표시) */}
                      {selectedNode === idx && item.details && (
                        <div className="mt-2 p-3 bg-gray-100 rounded text-sm">
                          {Object.entries(item.details).map(([key, value]) => (
                            <div key={key} className="flex gap-2">
                              <span className="text-gray-500 w-24">{key}:</span>
                              <span className="font-medium">{Array.isArray(value) ? value.join(', ') : value}</span>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>

                    {/* 펼침 아이콘 */}
                    <ChevronDown className={`w-5 h-5 text-gray-400 transition-transform ${selectedNode === idx ? 'rotate-180' : ''}`} />
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* 투입 원자재 정보 */}
          <div className="grid grid-cols-2 gap-4">
            <div className="bg-white rounded border p-4">
              <h2 className="text-lg font-bold mb-3 flex items-center gap-2">
                <Layers className="w-5 h-5" /> 투입 원자재
              </h2>
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-3 py-2 text-left">자재코드</th>
                    <th className="px-3 py-2 text-left">자재명</th>
                    <th className="px-3 py-2 text-left">입고 LOT</th>
                    <th className="px-3 py-2 text-right">수량</th>
                  </tr>
                </thead>
                <tbody>
                  {traceResult.inputMaterials.map((mat, idx) => (
                    <tr key={idx} className="border-t hover:bg-gray-50">
                      <td className="px-3 py-2">{mat.materialCode}</td>
                      <td className="px-3 py-2">{mat.materialName}</td>
                      <td className="px-3 py-2 font-mono text-xs">{mat.lotNo}</td>
                      <td className="px-3 py-2 text-right">{mat.qty}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* 관련 작업지시 */}
            <div className="bg-white rounded border p-4">
              <h2 className="text-lg font-bold mb-3 flex items-center gap-2">
                <ClipboardList className="w-5 h-5" /> 관련 작업지시
              </h2>
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-3 py-2 text-left">작업지시 번호</th>
                    <th className="px-3 py-2 text-left">공정</th>
                    <th className="px-3 py-2 text-center">상태</th>
                    <th className="px-3 py-2 text-right">완료수량</th>
                  </tr>
                </thead>
                <tbody>
                  {traceResult.relatedWorkOrders.map((wo, idx) => (
                    <tr key={idx} className="border-t hover:bg-gray-50">
                      <td className="px-3 py-2 font-mono text-xs">{wo.woNo}</td>
                      <td className="px-3 py-2">{wo.processName}</td>
                      <td className="px-3 py-2 text-center">
                        <span className={`px-2 py-0.5 rounded text-xs ${wo.status === '완료' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'
                          }`}>{wo.status}</span>
                      </td>
                      <td className="px-3 py-2 text-right">{wo.completedQty}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* 품질 검사 기록 */}
          <div className="bg-white rounded border p-4">
            <h2 className="text-lg font-bold mb-3 flex items-center gap-2">
              <CheckCircle className="w-5 h-5" /> 품질 검사 기록
            </h2>
            <div className="flex gap-4">
              {traceResult.qualityRecords.map((qr, idx) => (
                <div key={idx} className={`flex-1 p-4 rounded border-2 ${qr.result === '합격' ? 'border-green-500 bg-green-50' : 'border-red-500 bg-red-50'
                  }`}>
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-bold">{qr.type}</span>
                    <span className={`px-2 py-1 rounded text-xs font-medium ${qr.result === '합격' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
                      }`}>{qr.result}</span>
                  </div>
                  <div className="text-sm text-gray-600">
                    <div>검사일: {qr.date}</div>
                    <div>검사자: {qr.inspector}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 인쇄/내보내기 버튼 */}
          <div className="flex justify-end gap-2">
            <button className="px-4 py-2 border rounded hover:bg-gray-50 flex items-center gap-2">
              <Download className="w-4 h-4" />
              Excel 다운로드
            </button>
            <button className="px-4 py-2 border rounded hover:bg-gray-50 flex items-center gap-2">
              <FileText className="w-4 h-4" />
              PDF 출력
            </button>
            <button className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-2">
              <Printer className="w-4 h-4" />
              이력추적표 인쇄
            </button>
          </div>
        </div>
      )}

      {/* 검색 전 안내 */}
      {!traceResult && (
        <div className="bg-white rounded border p-8 text-center text-gray-500">
          <GitBranch className="w-16 h-16 mx-auto mb-4 text-gray-300" />
          <p className="text-lg font-medium mb-2">제품 이력을 검색하세요</p>
          <p className="text-sm">LOT 번호, 작업지시 번호, 수주 번호로 제품의 전체 제조 이력을 추적할 수 있습니다.</p>
          <div className="mt-4 p-4 bg-gray-50 rounded inline-block text-left">
            <div className="text-sm font-medium mb-2">추적 가능 정보:</div>
            <ul className="text-sm space-y-1">
              <li>• 원자재 입고 LOT 및 공급업체</li>
              <li>• 수입검사(IQC) 결과</li>
              <li>• 공정별 작업 이력 및 작업자</li>
              <li>• 중간검사(PQC) / 최종검사(FQC) 결과</li>
              <li>• 포장 및 출하 정보</li>
            </ul>
          </div>
        </div>
      )}
    </div>
  );
};

// ============ 생산관리 현황판 (관리자용) ============
const ProductionStatusBoard = ({ workOrders, workResults, onNavigate }) => {
  const [selectedFactory, setSelectedFactory] = useState('all');

  const factories = [
    { id: 'all', name: '전체', icon: Factory },
    { id: '스크린', name: '스크린공장', icon: Factory },
    { id: '슬랫', name: '슬랫공장', icon: Factory },
    { id: '절곡', name: '절곡공장', icon: Factory },
  ];

  // 공장별 현황 계산
  const getFactoryStats = (factoryId) => {
    const filtered = factoryId === 'all'
      ? workOrders
      : workOrders.filter(wo => wo.processType === factoryId);

    return {
      total: filtered.length,
      waiting: filtered.filter(wo => wo.status === '작업대기').length,
      working: filtered.filter(wo => wo.status === '작업중').length,
      complete: filtered.filter(wo => wo.status === '작업완료').length,
      urgent: filtered.filter(wo => wo.priority === '긴급').length,
      delayed: filtered.filter(wo => {
        const dueDate = new Date(wo.dueDate);
        return dueDate < new Date() && wo.status !== '작업완료';
      }).length,
    };
  };

  // 오늘 작업 현황
  const todayStats = {
    started: workResults.filter(wr => wr.workDate === new Date().toISOString().split('T')[0]).length,
    completed: workResults.filter(wr =>
      wr.workDate === new Date().toISOString().split('T')[0] && wr.status === '작업완료'
    ).length,
  };

  // 작업자별 현황
  const workerStats = {};
  workOrders.forEach(wo => {
    if (wo.assignee) {
      if (!workerStats[wo.assignee]) {
        workerStats[wo.assignee] = { total: 0, working: 0, complete: 0 };
      }
      workerStats[wo.assignee].total++;
      if (wo.status === '작업중') workerStats[wo.assignee].working++;
      if (wo.status === '작업완료') workerStats[wo.assignee].complete++;
    }
  });

  // 긴급 작업 목록
  const urgentWorks = workOrders
    .filter(wo => wo.priority === '긴급' && wo.status !== '작업완료')
    .slice(0, 5);

  // 지연 작업 목록
  const delayedWorks = workOrders
    .filter(wo => {
      const dueDate = new Date(wo.dueDate);
      return dueDate < new Date() && wo.status !== '작업완료';
    })
    .slice(0, 5);

  const currentStats = getFactoryStats(selectedFactory);

  return (
    <div className="space-y-6">
      <PageHeader
        icon={BarChart3}
        title="생산 현황판"
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => onNavigate('worker-task-view')}>
              <User className="w-4 h-4" /> 작업자 화면
            </Button>
            <Button variant="primary" onClick={() => onNavigate('work-order-list')}>
              <ClipboardList className="w-4 h-4" /> 작업지시 목록
            </Button>
          </div>
        }
      />

      {/* 공장 선택 탭 */}
      <div className="flex gap-2 bg-white p-2 rounded-xl border">
        {factories.map(factory => (
          <button
            key={factory.id}
            onClick={() => setSelectedFactory(factory.id)}
            className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-lg text-sm font-medium transition-all ${selectedFactory === factory.id
                ? 'bg-blue-500 text-white shadow-md'
                : 'bg-gray-50 text-gray-600 hover:bg-gray-100'
              }`}
          >
            <factory.icon className="w-5 h-5" />
            {factory.name}
          </button>
        ))}
      </div>

      {/* 현황 카드 */}
      <div className="grid grid-cols-2 md:grid-cols-6 gap-4">
        <div className="bg-white p-4 rounded-xl border">
          <p className="text-sm text-gray-500 mb-1">전체 작업</p>
          <p className="text-2xl font-bold text-gray-900">{currentStats.total}건</p>
        </div>
        <div className="bg-yellow-50 p-4 rounded-xl border border-yellow-200">
          <p className="text-sm text-yellow-700 mb-1">작업대기</p>
          <p className="text-2xl font-bold text-yellow-600">{currentStats.waiting}건</p>
        </div>
        <div className="bg-blue-50 p-4 rounded-xl border border-blue-200">
          <p className="text-sm text-blue-700 mb-1">작업중</p>
          <p className="text-2xl font-bold text-blue-600">{currentStats.working}건</p>
        </div>
        <div className="bg-green-50 p-4 rounded-xl border border-green-200">
          <p className="text-sm text-green-700 mb-1">작업완료</p>
          <p className="text-2xl font-bold text-green-600">{currentStats.complete}건</p>
        </div>
        <div className="bg-red-50 p-4 rounded-xl border border-red-200">
          <p className="text-sm text-red-700 mb-1">긴급</p>
          <p className="text-2xl font-bold text-red-600">{currentStats.urgent}건</p>
        </div>
        <div className="bg-orange-50 p-4 rounded-xl border border-orange-200">
          <p className="text-sm text-orange-700 mb-1">지연</p>
          <p className="text-2xl font-bold text-orange-600">{currentStats.delayed}건</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 긴급 작업 */}
        <Card title="🔴 긴급 작업">
          {urgentWorks.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              <CheckCircle className="w-12 h-12 mx-auto mb-2 text-green-400" />
              <p>긴급 작업 없음</p>
            </div>
          ) : (
            <div className="space-y-3">
              {urgentWorks.map(wo => (
                <div
                  key={wo.id}
                  onClick={() => onNavigate('work-order-detail', wo)}
                  className="p-3 bg-red-50 rounded-lg border border-red-200 cursor-pointer hover:bg-red-100"
                >
                  <div className="flex items-center justify-between mb-1">
                    <span className="font-mono text-sm text-red-700">{wo.workOrderNo}</span>
                    <StatusBadge status={wo.status} />
                  </div>
                  <p className="text-sm text-gray-700">{wo.customerName} / {wo.siteName}</p>
                  <p className="text-xs text-gray-500">납기: {wo.dueDate}</p>
                </div>
              ))}
            </div>
          )}
        </Card>

        {/* 지연 작업 */}
        <Card title="⚠️ 지연 작업">
          {delayedWorks.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              <CheckCircle className="w-12 h-12 mx-auto mb-2 text-green-400" />
              <p>지연 작업 없음</p>
            </div>
          ) : (
            <div className="space-y-3">
              {delayedWorks.map(wo => (
                <div
                  key={wo.id}
                  onClick={() => onNavigate('work-order-detail', wo)}
                  className="p-3 bg-orange-50 rounded-lg border border-orange-200 cursor-pointer hover:bg-orange-100"
                >
                  <div className="flex items-center justify-between mb-1">
                    <span className="font-mono text-sm text-orange-700">{wo.workOrderNo}</span>
                    <span className="text-xs text-red-600 font-medium">
                      {Math.ceil((new Date() - new Date(wo.dueDate)) / (1000 * 60 * 60 * 24))}일 지연
                    </span>
                  </div>
                  <p className="text-sm text-gray-700">{wo.customerName}</p>
                  <p className="text-xs text-gray-500">담당: {wo.assignee || '미지정'}</p>
                </div>
              ))}
            </div>
          )}
        </Card>

        {/* 작업자별 현황 */}
        <Card title="👷 작업자별 현황">
          {Object.keys(workerStats).length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              <User className="w-12 h-12 mx-auto mb-2 text-gray-300" />
              <p>지정된 작업자 없음</p>
            </div>
          ) : (
            <div className="space-y-3">
              {Object.entries(workerStats).map(([worker, stats]) => (
                <div key={worker} className="p-3 bg-gray-50 rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-medium text-gray-900">{worker}</span>
                    <span className="text-xs text-gray-500">{stats.total}건 배정</span>
                  </div>
                  <div className="flex gap-2">
                    <span className="text-xs px-2 py-1 bg-blue-100 text-blue-700 rounded">
                      작업중 {stats.working}
                    </span>
                    <span className="text-xs px-2 py-1 bg-green-100 text-green-700 rounded">
                      완료 {stats.complete}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </Card>
      </div>
    </div>
  );
};

// ============ 작업자 전용 화면 (반응형 대시보드) ============
// ============================================================
// 작업자 대시보드 - 모바일/데스크탑 반응형
// ============================================================
const WorkerTaskView = ({ workOrders, workResults, onNavigate, onBack, onStartWork, onCompleteWork, onReportIssue, onUpdateItemStatus, onPrintWorkLog, onMaterialInput }) => {
  // 공정관리에서 사용중인 공정 목록 동적으로 가져오기
  const activeProcesses = sampleProcesses.filter(p => p.isActive);

  // ★ 작업자/팀 선택 상태 - 개인 또는 공정팀 선택 가능
  const [viewMode, setViewMode] = useState('team'); // 'individual' 또는 'team'
  const [selectedWorker, setSelectedWorker] = useState('전체'); // 개인 선택 시 사용
  const [selectedTeam, setSelectedTeam] = useState('전체'); // 팀 선택 시 사용
  const [sortOption, setSortOption] = useState('priority'); // 정렬 옵션: priority, dueDate, recent

  // 작업자 목록 - 공정관리에서 배정된 작업자 목록 동적으로 가져옴
  const allAssignedWorkers = activeProcesses.flatMap(p => p.assignedWorkers || []);
  const workers = ['전체', ...new Set(allAssignedWorkers)];
  // 팀/공정 목록 - 공정관리에서 동적으로 가져옴
  const teams = ['전체', ...activeProcesses.map(p => `${p.processName}팀`)];

  // 공정명과 팀명 매핑 (동적 생성)
  const teamProcessMap = activeProcesses.reduce((acc, p) => {
    acc[`${p.processName}팀`] = p.processName;
    return acc;
  }, {});

  const [showCompleteToast, setShowCompleteToast] = useState(null);
  const [showIssueModal, setShowIssueModal] = useState(false);
  const [selectedTask, setSelectedTask] = useState(null);
  const [quickInputTask, setQuickInputTask] = useState(null);
  const [quickResult, setQuickResult] = useState({ goodQty: 0, defectQty: 0 });
  // ★ 개별 수량 처리를 위한 상태
  const [expandedTask, setExpandedTask] = useState(null);  // 펼쳐진 작업 (공정 상세 보기)
  const [stepProgress, setStepProgress] = useState({});    // { taskId: { stepCode: [true, true, false] } }

  // ★ 공정 단계명 매핑 (stepStatus 키 → processWorkflows stepName 정규화)
  // E2E 데이터의 stepStatus 키와 processWorkflows의 stepName 간 불일치 해결
  const stepNameMapping = {
    // 스크린 공정
    '원단절단': '원단 절단',
    '원단 절단': '원단 절단',
    '앤드락작업': '앤드락 작업',
    '앤드락 작업': '앤드락 작업',
    '미싱': '미싱',
    '중간검사': '중간검사',
    '포장': '포장',
    // 슬랫 공정
    '코일절단': '코일 절단',
    '코일 절단': '코일 절단',
    '미미작업': '미미작업',
    // 절곡 공정
    '절곡판/코일 절단': '절곡판/코일 절단',
    'V컷팅': 'V컷팅',
    '절곡': '절곡',
    // 재고생산 공정
    '준비': '준비',
    '작업': '작업',
    '검사': '검사',
  };

  // ★ stepStatus에서 stepProgress 초기화 (작업지시 데이터 → 작업자 화면 진행상태 연동)
  // 작업 선택 시 또는 컴포넌트 마운트 시 stepStatus 데이터를 stepProgress로 변환
  const initializeStepProgressFromStatus = (task) => {
    if (!task || !task.stepStatus) return;

    const steps = getTaskSteps(task);
    const totalQty = task.totalQty || 1;
    const newProgress = {};

    steps.forEach(step => {
      // stepStatus 키 찾기 (정규화된 이름으로 검색)
      const statusKey = Object.keys(task.stepStatus).find(key =>
        stepNameMapping[key] === step.stepName || key === step.stepName
      );

      if (statusKey && task.stepStatus[statusKey]) {
        const stepData = task.stepStatus[statusKey];
        if (stepData.status === '완료') {
          // 완료된 단계는 모든 항목 체크
          newProgress[step.stepCode] = Array(totalQty).fill(true);
        } else if (stepData.status === '진행중') {
          // 진행중인 단계는 완료된 수량만큼 체크
          const completedCount = task.completedQty || 0;
          newProgress[step.stepCode] = Array(totalQty).fill(false).map((_, i) => i < completedCount);
        } else {
          // 대기 상태는 빈 배열
          newProgress[step.stepCode] = Array(totalQty).fill(false);
        }
      }
    });

    setStepProgress(prev => ({
      ...prev,
      [task.id]: newProgress
    }));
  };

  // ★ 작업 펼치기 시 stepStatus에서 초기화
  const handleExpandTask = (taskId) => {
    if (expandedTask === taskId) {
      setExpandedTask(null);
    } else {
      setExpandedTask(taskId);
      // 아직 초기화되지 않은 경우에만 stepStatus에서 로드
      if (!stepProgress[taskId]) {
        const task = workOrders.find(wo => wo.id === taskId);
        initializeStepProgressFromStatus(task);
      }
    }
  };
  // ★ 작업일지 모달 상태
  const [showWorkLogModal, setShowWorkLogModal] = useState(false);
  const [workLogTask, setWorkLogTask] = useState(null);
  // ★ 작업일지 양식보기 모달 상태 (데이터 연동)
  const [showWorkLogDataPreview, setShowWorkLogDataPreview] = useState(false);
  const [workLogDataPreviewTask, setWorkLogDataPreviewTask] = useState(null);

  // ★ 담당자 확인 함수
  const isAssignedToWorker = (wo, worker) => {
    if (worker === '전체') return true;
    if (wo.assignees && Array.isArray(wo.assignees)) return wo.assignees.includes(worker);
    if (wo.assignee) return wo.assignee.split(', ').map(a => a.trim()).includes(worker);
    return false;
  };

  // ★ 팀/공정 확인 함수 - 동적 매핑 사용
  const isInTeam = (wo, team) => {
    if (team === '전체') return true;
    // 위에서 정의한 동적 teamProcessMap 사용
    return wo.processType === teamProcessMap[team];
  };

  // 내 작업 목록 (미완료만) - 개인/팀 모드에 따라 필터링
  const myTasks = workOrders
    .filter(wo => {
      if (wo.status === '작업완료') return false;
      if (viewMode === 'individual') {
        return isAssignedToWorker(wo, selectedWorker);
      } else {
        return isInTeam(wo, selectedTeam);
      }
    })
    .sort((a, b) => {
      // 작업중인 것은 항상 최상단
      if (a.status === '작업중' && b.status !== '작업중') return -1;
      if (a.status !== '작업중' && b.status === '작업중') return 1;

      // 정렬 옵션에 따른 정렬
      if (sortOption === 'priority') {
        // 우선순위순 (숫자가 낮을수록 높은 우선순위)
        const aPriority = a.priorityLevel || a.workSequence || 5;
        const bPriority = b.priorityLevel || b.workSequence || 5;
        if (aPriority !== bPriority) return aPriority - bPriority;
        // 같은 우선순위면 긴급 우선
        if (a.priority === '긴급' && b.priority !== '긴급') return -1;
        if (a.priority !== '긴급' && b.priority === '긴급') return 1;
        return new Date(a.dueDate) - new Date(b.dueDate);
      } else if (sortOption === 'dueDate') {
        // 납기일순
        return new Date(a.dueDate) - new Date(b.dueDate);
      } else {
        // 최신등록순 (ID 내림차순)
        return b.id - a.id;
      }
    });

  // 오늘 완료한 작업
  const todayCompleted = workOrders.filter(wo => {
    if (wo.status !== '작업완료') return false;
    if (!wo.completedAt) return false;
    const today = new Date().toDateString();
    return new Date(wo.completedAt).toDateString() === today;
  });

  // 공정별 통계 - 공정관리에서 동적으로 가져옴
  const processStats = activeProcesses.reduce((acc, p) => {
    acc[p.processName] = myTasks.filter(t => t.processType === p.processName);
    return acc;
  }, {});

  // 긴급 작업 수
  const urgentCount = myTasks.filter(t => t.priority === '긴급').length;
  const inProgressCount = myTasks.filter(t => t.status === '작업중').length;

  // 빠른 완료 처리
  const handleQuickComplete = (task) => {
    // ★ 자재투입이 필요한데 투입하지 않은 경우 경고
    if (needsMaterialInput(task)) {
      const confirmProceed = window.confirm(
        `⚠️ 자재 투입이 필요합니다!\n\n` +
        `작업지시: ${task.workOrderNo}\n` +
        `공정: ${task.processType}\n\n` +
        `자재 투입 없이 완료 처리하시겠습니까?\n` +
        `(LOT 추적이 불가능해집니다)`
      );
      if (!confirmProceed) {
        // 자재투입 모달 열기
        onMaterialInput?.(task);
        return;
      }
    }

    onStartWork?.(task);
    onCompleteWork?.({
      ...task,
      status: '작업완료',
      goodQty: task.totalQty || 0,
      defectQty: 0,
      note: '빠른 완료',
      completedAt: new Date().toISOString(),
    });
    setShowCompleteToast({ taskNo: task.workOrderNo, qty: task.totalQty });
    setTimeout(() => setShowCompleteToast(null), 2000);
  };

  // 실적 입력 후 완료
  const submitQuickResult = (task) => {
    onStartWork?.(task);
    onCompleteWork?.({
      ...task,
      status: '작업완료',
      goodQty: quickResult.goodQty,
      defectQty: quickResult.defectQty,
      completedAt: new Date().toISOString(),
    });
    setQuickInputTask(null);
    setQuickResult({ goodQty: 0, defectQty: 0 });
    setShowCompleteToast({ taskNo: task.workOrderNo, qty: quickResult.goodQty });
    setTimeout(() => setShowCompleteToast(null), 2000);
  };

  // ★ 자재 투입 필요 여부 확인 함수
  // 공정별로 필요한 자재가 정의되어 있고, 해당 자재가 투입되지 않은 경우 true 반환
  const needsMaterialInput = (task) => {
    // 자재투입이 필요한 공정 유형
    const processesRequiringMaterial = ['스크린', '슬랫', '절곡'];
    if (!processesRequiringMaterial.includes(task.processType)) return false;

    // 작업중 또는 대기 상태인 경우에만 자재투입 필요
    if (task.status === '작업완료') return false;

    // 이미 자재가 투입된 경우 (materialInputs 배열에 데이터가 있음)
    if (task.materialInputs && task.materialInputs.length > 0) return false;

    return true;
  };

  // ★ 자재 투입 상태 확인 함수
  const getMaterialInputStatus = (task) => {
    // 자재투입이 필요없는 공정
    const processesRequiringMaterial = ['스크린', '슬랫', '절곡'];
    if (!processesRequiringMaterial.includes(task.processType)) {
      return { status: 'not-required', label: '해당없음', color: 'gray' };
    }

    // 이미 자재가 투입된 경우
    if (task.materialInputs && task.materialInputs.length > 0) {
      return { status: 'completed', label: '투입완료', color: 'green', count: task.materialInputs.length };
    }

    // 자재 투입 필요
    return { status: 'required', label: '투입필요', color: 'red' };
  };

  // 공정타입별 색상
  const getProcessColor = (type) => {
    const colors = {
      '스크린': { bg: 'bg-blue-500', light: 'bg-blue-100', text: 'text-blue-700' },
      '슬랫': { bg: 'bg-purple-500', light: 'bg-purple-100', text: 'text-purple-700' },
      '절곡': { bg: 'bg-orange-500', light: 'bg-orange-100', text: 'text-orange-700' },
      '재고생산': { bg: 'bg-green-500', light: 'bg-green-100', text: 'text-green-700' },
    };
    return colors[type] || { bg: 'bg-gray-500', light: 'bg-gray-100', text: 'text-gray-700' };
  };

  // ★ 공정별 작업 단계 정의 (processMasterConfig에서 가져옴)
  const processWorkflows = {
    SCREEN: {
      code: 'SCREEN', name: '스크린',
      steps: [
        { stepNo: 1, stepCode: 'SCR-MAT', stepName: '자재투입', isQCStep: false },
        { stepNo: 2, stepCode: 'SCR-CNT', stepName: '절단매수확인', isQCStep: false },
        { stepNo: 3, stepCode: 'SCR-CUT', stepName: '원단 절단', isQCStep: false },
        { stepNo: 4, stepCode: 'SCR-CHK', stepName: '절단 Check', isQCStep: true },
        { stepNo: 5, stepCode: 'SCR-SEW', stepName: '미싱', isQCStep: false },
        { stepNo: 6, stepCode: 'SCR-END', stepName: '앤드락 작업', isQCStep: false },
        { stepNo: 7, stepCode: 'SCR-QC', stepName: '중간검사', isQCStep: true },
        { stepNo: 8, stepCode: 'SCR-PACK', stepName: '포장', isQCStep: false },
      ]
    },
    SLAT: {
      code: 'SLAT', name: '슬랫',
      steps: [
        { stepNo: 1, stepCode: 'SLT-CUT', stepName: '코일 절단', isQCStep: false },
        { stepNo: 2, stepCode: 'SLT-FIN', stepName: '미미작업', isQCStep: false },
        { stepNo: 3, stepCode: 'SLT-QC1', stepName: '중간검사', isQCStep: true },
        { stepNo: 4, stepCode: 'SLT-PACK', stepName: '포장', isQCStep: false },
      ]
    },
    FOLD: {
      code: 'FOLD', name: '절곡',
      steps: [
        { stepNo: 1, stepCode: 'FLD-CUT', stepName: '절곡판/코일 절단', isQCStep: false },
        { stepNo: 2, stepCode: 'FLD-VCUT', stepName: 'V컷팅', isQCStep: false },
        { stepNo: 3, stepCode: 'FLD-BEND', stepName: '절곡', isQCStep: false },
        { stepNo: 4, stepCode: 'FLD-QC', stepName: '중간검사', isQCStep: true },
        { stepNo: 5, stepCode: 'FLD-PACK', stepName: '포장', isQCStep: false },
      ]
    },
    STOCK: {
      code: 'STOCK', name: '재고생산',
      steps: [
        { stepNo: 1, stepCode: 'STK-PREP', stepName: '준비', isQCStep: false },
        { stepNo: 2, stepCode: 'STK-WORK', stepName: '작업', isQCStep: false },
        { stepNo: 3, stepCode: 'STK-QC', stepName: '검사', isQCStep: true },
        { stepNo: 4, stepCode: 'STK-PACK', stepName: '포장', isQCStep: false },
      ]
    }
  };

  // ★ 공정 타입명 → 코드 변환
  const getProcessCode = (typeName) => {
    const map = { '스크린': 'SCREEN', '슬랫': 'SLAT', '절곡': 'FOLD', '재고생산': 'STOCK' };
    return map[typeName] || 'STOCK';
  };

  // ★ 작업의 공정 단계 가져오기
  const getTaskSteps = (task) => {
    const code = getProcessCode(task.processType);
    return processWorkflows[code]?.steps || [];
  };

  // ★ 개별 수량 체크 토글
  const toggleItemCheck = (taskId, stepCode, itemIndex) => {
    setStepProgress(prev => {
      const taskProgress = prev[taskId] || {};
      const stepChecks = taskProgress[stepCode] || [];
      const newChecks = [...stepChecks];
      newChecks[itemIndex] = !newChecks[itemIndex];
      return {
        ...prev,
        [taskId]: {
          ...taskProgress,
          [stepCode]: newChecks
        }
      };
    });
  };

  // ★ 단계 전체 완료 여부 확인
  const isStepComplete = (taskId, stepCode, totalQty) => {
    const checks = stepProgress[taskId]?.[stepCode] || [];
    return checks.filter(Boolean).length >= totalQty;
  };

  // ★ 모든 단계 완료 여부 확인
  const isAllStepsComplete = (task) => {
    const steps = getTaskSteps(task);
    return steps.every(step => isStepComplete(task.id, step.stepCode, task.totalQty || 0));
  };

  // ★ 단계 완료 개수 가져오기
  const getStepCompletedCount = (taskId, stepCode) => {
    const checks = stepProgress[taskId]?.[stepCode] || [];
    return checks.filter(Boolean).length;
  };

  // ★ 검사 요청 처리 (QC Step)
  const requestInspection = (task, step) => {
    alert(`${step.stepName} 검사 요청이 품질팀에 전송되었습니다.`);
    // QC 단계는 자동 완료 처리
    const totalQty = task.totalQty || 0;
    setStepProgress(prev => ({
      ...prev,
      [task.id]: {
        ...prev[task.id],
        [step.stepCode]: Array(totalQty).fill(true)
      }
    }));
  };



  // ★ 개별 항목 상세 정보 생성 (전개도/치수 정보)
  const getItemDetails = (task, itemIndex) => {
    // 실제로는 작업지시에 연결된 BOM/전개도 데이터에서 가져옴
    const baseW = task.productionSizeW || 2500;
    const baseH = task.productionSizeH || 3000;
    const variation = (itemIndex % 3) * 100; // 항목별 사이즈 차이

    return {
      itemNo: itemIndex + 1,
      // 층/호수/부호 정보
      floor: `${Math.floor((itemIndex / 2) + 1)}층`,
      unit: `${(itemIndex % 10) + 1}호`,
      code: ['A', 'B', 'C', 'D'][itemIndex % 4],
      // 전개 치수 정보
      width: baseW + variation,
      height: baseH + (variation * 1.2),
      // 규격
      spec: `W${baseW + variation} × H${Math.floor(baseH + (variation * 1.2))}`,
      // 자재 정보
      material: task.processType === '슬랫' ? '슬랫 코일' :
        task.processType === '스크린' ? '스크린 원단' : '절곡판',
      lotNo: task.assignedLots?.[0]?.lotNo || `LOT-${task.processType?.substring(0, 2)}-2025-${String(itemIndex + 1).padStart(3, '0')}`,
      // 비고
      note: itemIndex === 0 ? '선행 생산' : '',
    };
  };

  // ============ 대시보드 렌더링 ============
  return (
    <div className="min-h-screen bg-gray-50">
      {/* 상단 헤더 - 심플하게 */}
      <header className="bg-white border-b sticky top-0 z-10">
        <div className="px-4 sm:px-6 lg:px-8 py-3 sm:py-4">
          <h1 className="text-lg sm:text-xl font-bold text-gray-900">
            작업자 화면
          </h1>
        </div>
      </header>

      {/* 메인 대시보드 - 전체 폭 사용 */}
      <main className="px-4 sm:px-6 lg:px-8 py-4 sm:py-6">
        {/* 상단 통계 카드 - 모바일 2열, 데스크탑 4열 */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 sm:gap-3 mb-4">
          <div className="bg-white rounded-lg p-3 border border-gray-200 text-center">
            <p className="text-xs text-gray-500">할일</p>
            <p className="text-xl sm:text-2xl font-bold text-gray-800">{myTasks.length}<span className="text-sm ml-0.5">건</span></p>
          </div>
          <div className="bg-white rounded-lg p-3 border border-gray-200 text-center">
            <p className="text-xs text-gray-500">작업중</p>
            <p className="text-xl sm:text-2xl font-bold text-gray-700">{inProgressCount}<span className="text-sm ml-0.5">건</span></p>
          </div>
          <div className="bg-white rounded-lg p-3 border border-gray-200 text-center">
            <p className="text-xs text-gray-500">완료</p>
            <p className="text-xl sm:text-2xl font-bold text-gray-600">{todayCompleted.length}<span className="text-sm ml-0.5">건</span></p>
          </div>
          <div className={`rounded-lg p-3 border text-center ${urgentCount > 0 ? 'bg-gray-100 border-gray-400' : 'bg-white border-gray-200'}`}>
            <p className="text-xs text-gray-500">긴급</p>
            <p className={`text-xl sm:text-2xl font-bold ${urgentCount > 0 ? 'text-gray-900' : 'text-gray-400'}`}>{urgentCount}<span className="text-sm ml-0.5">건</span></p>
          </div>
        </div>

        {/* 작업 목록 */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-sm font-semibold text-gray-700">내 작업 목록</h2>
            {/* 정렬 옵션 */}
            <select
              value={sortOption}
              onChange={(e) => setSortOption(e.target.value)}
              className="text-xs border rounded px-2 py-1 bg-white"
            >
              <option value="priority">우선순위순</option>
              <option value="dueDate">납기일순</option>
              <option value="recent">최신등록순</option>
            </select>
          </div>

          {myTasks.length === 0 ? (
            <div className="bg-white rounded-lg p-8 text-center border">
              <p className="text-lg font-bold text-gray-900 mb-1">모든 작업 완료</p>
              <p className="text-sm text-gray-500">현재 배정된 작업이 없습니다.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
              {myTasks.map((task) => {
                const isUrgent = task.priority === '긴급';
                const isWorking = task.status === '작업중';
                const priorityLevel = task.priorityLevel || task.workSequence || 5;

                return (
                  <div
                    key={task.id}
                    className={`bg-white rounded-lg border overflow-hidden ${isUrgent ? 'border-gray-400' :
                        isWorking ? 'border-gray-400' :
                          'border-gray-200'
                      }`}
                  >
                    <div className="p-4">
                      {/* 1순위: 제품명 + 수량 (한 줄 좌우 배치) */}
                      <div className="bg-gray-100 rounded-lg p-3 mb-3 flex items-center justify-between">
                        <p className="text-lg sm:text-xl font-bold text-gray-900">
                          {task.productName || '제품'}
                        </p>
                        <p className="text-xl sm:text-2xl font-black text-gray-800">
                          {task.totalQty || 0}<span className="text-base sm:text-lg ml-1">EA</span>
                        </p>
                      </div>

                      {/* 2순위: 상태/우선순위/납기 (중요) */}
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center gap-2 flex-wrap">
                          {/* 우선순위 */}
                          <span className={`px-3 py-1 rounded text-sm font-bold ${priorityLevel <= 3
                              ? 'bg-gray-800 text-white'
                              : priorityLevel <= 6
                                ? 'bg-gray-600 text-white'
                                : 'bg-gray-400 text-white'
                            }`}>
                            {priorityLevel}순위
                          </span>
                          {isUrgent && (
                            <span className="px-3 py-1 rounded text-sm font-bold bg-gray-900 text-white">
                              긴급
                            </span>
                          )}
                          {isWorking && (
                            <span className="px-3 py-1 rounded text-sm font-bold bg-gray-700 text-white">
                              작업중
                            </span>
                          )}
                        </div>
                        {/* 납기일 - 우측 */}
                        <div className="text-right">
                          <p className="text-xs text-gray-500">납기</p>
                          <p className="text-sm sm:text-base font-bold text-gray-800">{task.dueDate}</p>
                        </div>
                      </div>

                      {/* 3순위: 공정/작업지시번호 */}
                      <div className="flex items-center gap-2 mb-2 text-sm">
                        <span className="px-2 py-1 rounded bg-gray-200 text-gray-800 font-medium">
                          {task.processType}
                        </span>
                        <span className="font-mono text-gray-600">{task.workOrderNo}</span>
                      </div>

                      {/* 4순위: 발주처/현장 (작게) */}
                      <div className="text-xs sm:text-sm text-gray-500 mb-2">
                        <span className="font-medium text-gray-700">{task.customerName}</span>
                        {task.siteName && <span className="mx-1">·</span>}
                        {task.siteName && <span>{task.siteName}</span>}
                      </div>

                      {/* 담당자 */}
                      {(task.assignedWorkers?.length > 0 || task.assignee) && (
                        <p className="text-xs text-gray-400 mb-2">
                          담당: {task.assignedWorkers?.length > 0
                            ? task.assignedWorkers.length > 2
                              ? `${task.assignedWorkers.slice(0, 2).join(', ')} 외 ${task.assignedWorkers.length - 2}명`
                              : task.assignedWorkers.join(', ')
                            : task.assignee
                          }
                        </p>
                      )}

                      {/* 지시사항 표시 */}
                      {task.instruction && (
                        <div className="mb-3 p-2 bg-gray-100 border border-gray-300 rounded text-xs sm:text-sm text-gray-700">
                          <span className="font-bold text-gray-800">지시:</span> {task.instruction}
                        </div>
                      )}

                      {/* 액션 버튼들 - 터치 친화적 반응형 */}
                      <div className="space-y-2 mt-3">
                        {/* 메인 액션: 전량완료 (가장 중요) */}
                        <button
                          onClick={() => handleQuickComplete(task)}
                          className="w-full py-4 bg-gray-800 hover:bg-gray-900 active:bg-black text-white rounded-lg text-lg font-bold"
                        >
                          전량완료
                        </button>
                        {/* 보조 액션: 2열 배치 */}
                        <div className="grid grid-cols-2 gap-2">
                          <button
                            onClick={() => handleExpandTask(task.id)}
                            className={`py-3 rounded-lg text-sm font-medium border ${expandedTask === task.id
                                ? 'bg-gray-700 text-white border-gray-700'
                                : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
                              }`}
                          >
                            공정상세
                          </button>
                          <button
                            onClick={() => onMaterialInput?.(task)}
                            className="py-3 rounded-lg text-sm font-medium border bg-white text-gray-700 border-gray-300 hover:bg-gray-50"
                          >
                            자재투입
                          </button>
                        </div>
                        {/* 기타 액션: 2열 배치 */}
                        <div className="grid grid-cols-2 gap-2">
                          <button
                            onClick={() => {
                              setWorkLogDataPreviewTask(task);
                              setShowWorkLogDataPreview(true);
                            }}
                            className="py-2.5 bg-white text-gray-600 rounded-lg text-xs font-medium border border-gray-200 hover:bg-gray-50"
                          >
                            작업일지
                          </button>
                          <button
                            onClick={() => {
                              setSelectedTask(task);
                              setShowIssueModal(true);
                            }}
                            className="py-2.5 bg-white text-gray-600 rounded-lg text-xs font-medium border border-gray-200 hover:bg-gray-50"
                          >
                            이슈보고
                          </button>
                        </div>
                      </div>
                    </div>

                    {/* 공정 단계별 개별 체크 영역 */}
                    {expandedTask === task.id && (
                      <div className="border-t bg-gray-50 p-3">
                        {/* 투입 자재 LOT 정보 */}
                        {task.materialInputs && task.materialInputs.length > 0 && (
                          <div className="mb-3 p-2 bg-white rounded border border-gray-300">
                            <div className="flex items-center justify-between mb-2">
                              <span className="text-sm font-medium text-gray-700">투입 자재 ({task.materialInputs.length}건)</span>
                            </div>
                            <div className="space-y-1">
                              {task.materialInputs.map((input, idx) => (
                                <div key={input.id || idx} className="flex items-center justify-between text-xs bg-gray-100 p-2 rounded">
                                  <span className="font-medium text-gray-800">{input.materialName || input.materialCode} {input.qty}{input.unit}</span>
                                  <span className="font-mono text-gray-600">{input.lotNo}</span>
                                </div>
                              ))}
                            </div>
                          </div>
                        )}

                        {/* 자재 미투입 경고 */}
                        {needsMaterialInput(task) && (
                          <div className="mb-3 p-2 bg-gray-100 rounded border border-gray-300">
                            <p className="text-sm font-medium text-gray-800 mb-2">자재 투입 필요</p>
                            <button
                              onClick={() => onMaterialInput?.(task)}
                              className="w-full py-2 bg-gray-700 text-white rounded text-sm font-medium"
                            >
                              자재 투입하기
                            </button>
                          </div>
                        )}

                        <div className="flex items-center justify-between mb-3">
                          <h4 className="text-sm font-semibold text-gray-700">공정 단계 ({getTaskSteps(task).length}단계)</h4>
                          <span className="text-xs text-gray-500">
                            {getTaskSteps(task).filter(s => isStepComplete(task.id, s.stepCode, task.totalQty)).length} / {getTaskSteps(task).length} 완료
                          </span>
                        </div>

                        <div className="space-y-3">
                          {getTaskSteps(task).map((step, stepIdx) => {
                            const completedCount = getStepCompletedCount(task.id, step.stepCode);
                            const totalQty = task.totalQty || 0;
                            const isComplete = completedCount >= totalQty;
                            const prevStep = getTaskSteps(task)[stepIdx - 1];
                            const isPrevComplete = !prevStep || isStepComplete(task.id, prevStep.stepCode, totalQty);

                            return (
                              <div
                                key={step.stepCode}
                                className={`rounded-lg border p-3 transition-all ${isComplete
                                    ? 'bg-gray-200 border-gray-400'
                                    : isPrevComplete
                                      ? 'bg-white border-gray-200'
                                      : 'bg-gray-100 border-gray-200 opacity-50'
                                  }`}
                              >
                                {/* 단계 헤더 */}
                                <div className="flex items-center justify-between mb-2">
                                  <div className="flex items-center gap-2">
                                    <span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${isComplete
                                        ? 'bg-gray-700 text-white'
                                        : 'bg-gray-400 text-white'
                                      }`}>
                                      {step.stepNo}
                                    </span>
                                    <span className={`font-medium text-sm ${isComplete ? 'text-gray-600' : 'text-gray-800'}`}>
                                      {step.stepName}
                                    </span>
                                    {step.isQCStep && (
                                      <span className="px-1.5 py-0.5 bg-gray-300 text-gray-700 text-xs rounded">검사</span>
                                    )}
                                  </div>
                                  <span className={`text-xs font-medium ${isComplete ? 'text-gray-600' : 'text-gray-500'
                                    }`}>
                                    {completedCount}/{totalQty}
                                  </span>
                                </div>

                                {/* 개별 체크박스 또는 검사 요청 버튼 */}
                                {isPrevComplete && !isComplete && (
                                  step.isQCStep ? (
                                    // QC 단계: 검사 요청 버튼
                                    <button
                                      onClick={() => requestInspection(task, step)}
                                      className="w-full py-2 bg-gray-600 text-white rounded text-sm font-medium"
                                    >
                                      검사 요청
                                    </button>
                                  ) : (
                                    // 작업 단계: 개별 항목 카드 + 체크박스
                                    <div className="space-y-2">
                                      {Array.from({ length: totalQty }, (_, i) => {
                                        const isChecked = stepProgress[task.id]?.[step.stepCode]?.[i] || false;
                                        const itemDetail = getItemDetails(task, i);
                                        return (
                                          <div
                                            key={i}
                                            className={`rounded-lg border p-3 transition-all ${isChecked
                                                ? 'bg-gray-200 border-gray-400'
                                                : 'bg-white border-gray-200 hover:border-gray-400'
                                              }`}
                                          >
                                            <div className="flex items-start gap-3">
                                              {/* 체크 버튼 */}
                                              <button
                                                onClick={() => toggleItemCheck(task.id, step.stepCode, i)}
                                                className={`flex-shrink-0 w-12 h-12 sm:w-14 sm:h-14 rounded-lg font-bold text-lg border transition-all active:scale-95 flex items-center justify-center ${isChecked
                                                    ? 'bg-gray-700 border-gray-700 text-white'
                                                    : 'bg-gray-500 border-gray-500 text-white hover:bg-gray-600'
                                                  }`}
                                              >
                                                {i + 1}
                                              </button>

                                              {/* 항목 상세 정보 */}
                                              <div className="flex-1 min-w-0">
                                                <div className="flex items-center gap-2 mb-1 flex-wrap">
                                                  <span className="font-bold text-gray-900">#{itemDetail.itemNo}</span>
                                                  <span className="px-2 py-0.5 bg-gray-600 text-white text-xs rounded font-medium">
                                                    {itemDetail.floor} {itemDetail.unit}-{itemDetail.code}
                                                  </span>
                                                  {itemDetail.note && (
                                                    <span className="px-2 py-0.5 bg-gray-400 text-white text-xs rounded">
                                                      {itemDetail.note}
                                                    </span>
                                                  )}
                                                </div>

                                                {/* 전개도 치수 */}
                                                <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
                                                  <div className="flex items-center gap-1">
                                                    <span className="text-gray-500">규격:</span>
                                                    <span className="font-mono font-medium text-gray-800">{itemDetail.spec}</span>
                                                  </div>
                                                  <div className="flex items-center gap-1">
                                                    <span className="text-gray-500">자재:</span>
                                                    <span className="text-gray-800">{itemDetail.material}</span>
                                                  </div>
                                                  <div className="col-span-2 flex items-center gap-1">
                                                    <span className="text-gray-500">LOT:</span>
                                                    <span className="font-mono text-gray-600">{itemDetail.lotNo}</span>
                                                  </div>
                                                </div>
                                              </div>

                                              {/* 완료 표시 */}
                                              {isChecked && (
                                                <span className="text-gray-600 font-bold text-sm">완료</span>
                                              )}
                                            </div>
                                          </div>
                                        );
                                      })}
                                    </div>
                                  )
                                )}

                                {/* 완료 상태 표시 */}
                                {isComplete && (
                                  <span className="text-gray-600 text-sm font-medium">완료</span>
                                )}
                              </div>
                            );
                          })}
                        </div>

                        {/* 전체 완료 버튼 */}
                        {isAllStepsComplete(task) && (
                          <button
                            onClick={() => {
                              onStartWork?.(task);
                              onCompleteWork?.({
                                ...task,
                                status: '작업완료',
                                goodQty: task.totalQty || 0,
                                defectQty: 0,
                                completedAt: new Date().toISOString(),
                              });
                              setExpandedTask(null);
                              setShowCompleteToast({ taskNo: task.workOrderNo, qty: task.totalQty });
                              setTimeout(() => setShowCompleteToast(null), 2000);
                            }}
                            className="w-full mt-3 py-2 bg-gray-800 text-white rounded font-medium text-sm"
                          >
                            모든 공정 완료 - 작업 종료
                          </button>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* 오늘 완료한 작업 */}
        {todayCompleted.length > 0 && (
          <div className="mt-4">
            <h2 className="text-sm font-semibold text-gray-700 mb-2">오늘 완료 ({todayCompleted.length}건)</h2>
            <div className="bg-gray-100 rounded-lg p-2 space-y-1">
              {todayCompleted.slice(0, 3).map((task) => (
                <div key={task.id} className="flex items-center justify-between bg-white rounded p-2 text-sm">
                  <span className="font-mono text-xs text-gray-600">{task.workOrderNo}</span>
                  <span className="text-gray-700">{task.customerName}</span>
                  <span className="text-gray-500">{task.totalQty}EA</span>
                </div>
              ))}
              {todayCompleted.length > 3 && (
                <p className="text-xs text-gray-500 text-center">외 {todayCompleted.length - 3}건</p>
              )}
            </div>
          </div>
        )}
      </main>

      {/* 빠른 실적 입력 모달 - 바텀시트 스타일 */}
      {quickInputTask && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-end sm:items-center justify-center">
          <div className="bg-white w-full sm:max-w-md sm:rounded-xl rounded-t-2xl overflow-hidden animate-slide-up">
            <div className="p-4 border-b flex items-center justify-between">
              <h3 className="font-bold text-gray-900">실적 입력</h3>
              <button onClick={() => setQuickInputTask(null)} className="p-2 hover:bg-gray-100 rounded-lg">
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            <div className="p-4 space-y-4">
              {/* 작업 정보 */}
              <div className="bg-gray-50 rounded-lg p-3">
                <p className="font-mono text-sm text-gray-600">{quickInputTask.workOrderNo}</p>
                <p className="font-medium text-gray-900">{quickInputTask.customerName}</p>
                <p className="text-sm text-gray-500">목표: {quickInputTask.totalQty}EA</p>
              </div>

              {/* 수량 입력 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">양품</label>
                  <input
                    type="number"
                    value={quickResult.goodQty}
                    onChange={(e) => setQuickResult({ ...quickResult, goodQty: parseInt(e.target.value) || 0 })}
                    className="w-full px-4 py-3 border rounded-lg text-center text-xl font-bold focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">불량</label>
                  <input
                    type="number"
                    value={quickResult.defectQty}
                    onChange={(e) => setQuickResult({ ...quickResult, defectQty: parseInt(e.target.value) || 0 })}
                    className="w-full px-4 py-3 border rounded-lg text-center text-xl font-bold focus:ring-2 focus:ring-red-500"
                  />
                </div>
              </div>

              {/* 빠른 선택 버튼 */}
              <div className="flex gap-2 flex-wrap">
                <button
                  onClick={() => setQuickResult({ goodQty: quickInputTask.totalQty, defectQty: 0 })}
                  className="px-3 py-2 bg-green-100 text-green-700 rounded-lg text-sm font-medium"
                >
                  전량 완료
                </button>
                {quickInputTask.totalQty > 1 && (
                  <button
                    onClick={() => setQuickResult({ goodQty: quickInputTask.totalQty - 1, defectQty: 1 })}
                    className="px-3 py-2 bg-yellow-100 text-yellow-700 rounded-lg text-sm font-medium"
                  >
                    불량 1개
                  </button>
                )}
              </div>
            </div>

            <div className="p-4 border-t flex gap-3">
              <button
                onClick={() => setQuickInputTask(null)}
                className="flex-1 py-3 border rounded-lg font-medium text-gray-700 hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={() => submitQuickResult(quickInputTask)}
                className="flex-1 py-3 bg-blue-500 text-white rounded-lg font-medium hover:bg-blue-600"
              >
                완료 처리
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 완료 토스트 */}
      {showCompleteToast && (
        <div className="fixed top-20 left-1/2 -translate-x-1/2 z-50 animate-bounce">
          <div className="bg-green-500 text-white px-6 py-3 rounded-full shadow-xl flex items-center gap-2">
            <CheckCircle className="w-5 h-5" />
            <span className="font-bold">{showCompleteToast.taskNo} 완료! ({showCompleteToast.qty}EA)</span>
          </div>
        </div>
      )}

      {/* 이슈 보고 모달 */}
      {showIssueModal && selectedTask && (
        <IssueReportModal
          task={selectedTask}
          onClose={() => setShowIssueModal(false)}
          onSubmit={(issue) => {
            onReportIssue?.(selectedTask, issue);
            setShowIssueModal(false);
          }}
        />
      )}

      {/* 작업일지 출력 모달 - 공정별 전용 템플릿 (데이터 맵핑) */}
      {showWorkLogModal && workLogTask && (
        <WorkLogTemplateModal
          workOrder={workLogTask}
          order={null}
          workLog={null}
          workResults={null}
          onClose={() => {
            setShowWorkLogModal(false);
            setWorkLogTask(null);
          }}
        />
      )}

      {/* 작업일지 양식보기 모달 - 실제 데이터 연동 */}
      {showWorkLogDataPreview && workLogDataPreviewTask && (
        <WorkLogDataPreviewModal
          workOrder={workLogDataPreviewTask}
          workResults={workResults?.filter(r => r.workOrderNo === workLogDataPreviewTask.workOrderNo) || []}
          order={null}
          onClose={() => {
            setShowWorkLogDataPreview(false);
            setWorkLogDataPreviewTask(null);
          }}
        />
      )}
    </div>
  );
};

// ★ 입고 로트 입력 모달
const MaterialLotInputModal = ({ task, onClose, onSubmit }) => {
  const [materialName, setMaterialName] = useState('');
  const [lotNo, setLotNo] = useState('');
  const [qty, setQty] = useState('');
  const [unit, setUnit] = useState('EA');

  // 공정별 자재 프리셋
  const materialPresets = {
    '스크린': [
      { name: '방충망 원단 (1016)', unit: 'm' },
      { name: '방충망 원단 (1270)', unit: 'm' },
      { name: '방충망 원단 (1524)', unit: 'm' },
      { name: '앤드락', unit: 'EA' },
    ],
    '슬랫': [
      { name: '슬랫 코일 (백색)', unit: 'm' },
      { name: '슬랫 코일 (아이보리)', unit: 'm' },
      { name: '미미 부품', unit: 'EA' },
    ],
    '절곡': [
      { name: '철판 (1.0t)', unit: '매' },
      { name: '철판 (1.2t)', unit: '매' },
      { name: '철판 (1.5t)', unit: '매' },
    ],
  };

  const presets = materialPresets[task.processType] || [];

  const handlePresetSelect = (preset) => {
    setMaterialName(preset.name);
    setUnit(preset.unit);
  };

  const handleSubmit = () => {
    if (!materialName || !lotNo || !qty) {
      alert('자재명, 로트번호, 수량을 모두 입력해주세요.');
      return;
    }
    onSubmit({
      materialName,
      lotNo,
      qty: parseInt(qty) || 0,
      unit,
    });
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-end sm:items-center justify-center z-50">
      <div className="bg-white w-full sm:max-w-md sm:rounded-xl rounded-t-xl max-h-[90vh] overflow-auto">
        <div className="flex items-center justify-between p-4 border-b sticky top-0 bg-white">
          <h3 className="font-bold text-gray-900">📦 입고 로트 등록</h3>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg">
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        <div className="p-4 space-y-4">
          {/* 작업 정보 */}
          <div className="p-3 bg-blue-50 rounded-lg">
            <p className="text-sm font-medium text-blue-800">{task.workOrderNo}</p>
            <p className="text-xs text-blue-600">{task.customerName} · {task.processType}</p>
          </div>

          {/* 자재 프리셋 */}
          {presets.length > 0 && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">자주 쓰는 자재</label>
              <div className="flex flex-wrap gap-2">
                {presets.map((preset, idx) => (
                  <button
                    key={idx}
                    onClick={() => handlePresetSelect(preset)}
                    className={`px-3 py-2 rounded-lg text-sm border transition-all ${materialName === preset.name
                        ? 'border-amber-500 bg-amber-50 text-amber-700'
                        : 'border-gray-200 hover:border-gray-300 text-gray-700'
                      }`}
                  >
                    {preset.name}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* 자재명 입력 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">자재명 *</label>
            <input
              type="text"
              value={materialName}
              onChange={(e) => setMaterialName(e.target.value)}
              className="w-full px-3 py-3 border rounded-lg focus:ring-2 focus:ring-amber-500 text-base"
              placeholder="자재명을 입력하세요"
            />
          </div>

          {/* 로트번호 입력 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">입고 로트번호 *</label>
            <input
              type="text"
              value={lotNo}
              onChange={(e) => setLotNo(e.target.value.toUpperCase())}
              className="w-full px-3 py-3 border rounded-lg focus:ring-2 focus:ring-amber-500 text-base font-mono"
              placeholder="예: LOT-241210-001"
            />
          </div>

          {/* 수량 입력 */}
          <div className="grid grid-cols-3 gap-3">
            <div className="col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-2">투입 수량 *</label>
              <input
                type="number"
                value={qty}
                onChange={(e) => setQty(e.target.value)}
                className="w-full px-3 py-3 border rounded-lg focus:ring-2 focus:ring-amber-500 text-base text-center font-bold"
                placeholder="0"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">단위</label>
              <select
                value={unit}
                onChange={(e) => setUnit(e.target.value)}
                className="w-full px-3 py-3 border rounded-lg focus:ring-2 focus:ring-amber-500 text-base"
              >
                <option value="EA">EA</option>
                <option value="m">m</option>
                <option value="매">매</option>
                <option value="kg">kg</option>
                <option value="roll">roll</option>
              </select>
            </div>
          </div>
        </div>

        <div className="p-4 border-t flex gap-3">
          <Button variant="outline" className="flex-1" onClick={onClose}>취소</Button>
          <Button variant="primary" className="flex-1" onClick={handleSubmit}>
            <Plus className="w-4 h-4" /> 로트 등록
          </Button>
        </div>
      </div>
    </div>
  );
};

// ★ 작업일지 미리보기/출력 모달 (공정별 전용 템플릿 적용 - ISO 인증용)
const WorkLogPreviewModal = ({ task, workLogData, onClose }) => {
  const handlePrint = () => {
    window.print();
  };

  // 공정 타입에 따른 문서 코드 매핑
  const getDocCode = (processType) => {
    const codeMap = {
      '스크린': 'WL-SCR',
      '절곡': 'WL-FLD',
      '슬랫': 'WL-SLT',
      '포밍': 'WL-STK',
      '포장': 'WL-PKG',
    };
    return codeMap[processType] || 'WL-GEN';
  };

  const docCode = getDocCode(task.processType);

  // ===== 스크린 작업일지: 망규격 × 폭규격 매트릭스 테이블 =====
  const ScreenWorkLogTable = () => {
    // 매트릭스 데이터 (documentTemplateConfig 기준)
    const rowHeaders = ['1016', '1270', '1524', '1780']; // 망규격 (세로)
    const colHeaders = ['900', '1000', '1100', '1200', '1300', '1400', '1500']; // 폭규격 (가로)

    // 샘플 데이터 (실제로는 workLogData.screenProduction에서 가져옴)
    const screenData = workLogData.screenProduction || {};

    // 행/열 합계 계산
    const rowTotals = rowHeaders.map(row =>
      colHeaders.reduce((sum, col) => sum + (screenData[`${row}_${col}`] || 0), 0)
    );
    const colTotals = colHeaders.map(col =>
      rowHeaders.reduce((sum, row) => sum + (screenData[`${row}_${col}`] || 0), 0)
    );
    const grandTotal = rowTotals.reduce((sum, val) => sum + val, 0);

    return (
      <div className="mb-4">
        <div className="bg-black text-white px-3 py-1 font-bold text-sm">작 업 내 역 (망규격 × 폭규격)</div>
        <div className="overflow-x-auto">
          <table className="w-full border-collapse text-xs">
            <thead>
              <tr>
                <th className="border border-gray-400 bg-gray-100 px-2 py-1 font-bold">망규격 ↓ / 폭규격 →</th>
                {colHeaders.map(col => (
                  <th key={col} className="border border-gray-400 bg-gray-100 px-2 py-1 font-medium w-14">{col}</th>
                ))}
                <th className="border border-gray-400 bg-blue-100 px-2 py-1 font-bold">합계</th>
              </tr>
            </thead>
            <tbody>
              {rowHeaders.map((row, rowIdx) => (
                <tr key={row}>
                  <th className="border border-gray-400 bg-gray-100 px-2 py-1 font-medium">{row}</th>
                  {colHeaders.map(col => (
                    <td key={col} className="border border-gray-400 px-2 py-1 text-center bg-yellow-50">
                      {screenData[`${row}_${col}`] || '-'}
                    </td>
                  ))}
                  <td className="border border-gray-400 px-2 py-1 text-center font-bold bg-blue-50">
                    {rowTotals[rowIdx] || '-'}
                  </td>
                </tr>
              ))}
              <tr className="bg-blue-100">
                <th className="border border-gray-400 px-2 py-1 font-bold">합계</th>
                {colTotals.map((total, idx) => (
                  <td key={idx} className="border border-gray-400 px-2 py-1 text-center font-bold">
                    {total || '-'}
                  </td>
                ))}
                <td className="border border-gray-400 px-2 py-1 text-center font-bold text-lg bg-green-200">
                  {grandTotal} 매
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    );
  };

  // ===== 절곡 작업일지: 부품별 도면 포함 테이블 =====
  const FoldWorkLogTable = () => {
    const parts = workLogData.foldParts || [
      { partCode: 'FLD-001', partName: '앙카브라켓', spec: '100×50×3T', material: 'STS304', qty: 120, unit: 'EA' },
      { partCode: 'FLD-002', partName: '고정클립', spec: '80×30×2T', material: 'STS304', qty: 240, unit: 'EA' },
      { partCode: 'FLD-003', partName: '연결브라켓', spec: '150×80×3T', material: 'STS304', qty: 80, unit: 'EA' },
    ];
    const totalQty = parts.reduce((sum, p) => sum + p.qty, 0);

    return (
      <div className="mb-4">
        <div className="bg-black text-white px-3 py-1 font-bold text-sm">부 품 작 업 내 역</div>
        <table className="w-full border-collapse text-xs">
          <thead>
            <tr className="bg-gray-100">
              <th className="border border-gray-400 px-2 py-1 font-bold w-10">NO</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-20">부품코드</th>
              <th className="border border-gray-400 px-2 py-1 font-bold">부품명</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-32">도면</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-24">규격</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-16">재질</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-14">수량</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-10">단위</th>
            </tr>
          </thead>
          <tbody>
            {parts.map((part, idx) => (
              <tr key={part.partCode}>
                <td className="border border-gray-400 px-2 py-1 text-center">{idx + 1}</td>
                <td className="border border-gray-400 px-2 py-1 text-center font-mono">{part.partCode}</td>
                <td className="border border-gray-400 px-2 py-1">{part.partName}</td>
                <td className="border border-gray-400 px-2 py-1 text-center">
                  <div className="w-full h-16 bg-gray-100 border border-dashed border-gray-300 flex items-center justify-center text-gray-400 text-xs">
                    📐 도면 이미지
                  </div>
                </td>
                <td className="border border-gray-400 px-2 py-1 text-center">{part.spec}</td>
                <td className="border border-gray-400 px-2 py-1 text-center">{part.material}</td>
                <td className="border border-gray-400 px-2 py-1 text-center font-bold bg-yellow-50">{part.qty}</td>
                <td className="border border-gray-400 px-2 py-1 text-center">{part.unit}</td>
              </tr>
            ))}
            <tr className="bg-blue-100">
              <td colSpan={6} className="border border-gray-400 px-2 py-1 text-right font-bold">총 생산량:</td>
              <td className="border border-gray-400 px-2 py-1 text-center font-bold text-lg">{totalQty}</td>
              <td className="border border-gray-400 px-2 py-1 text-center font-bold">EA</td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  };

  // ===== 슬랫 작업일지: LOT별 생산내역 테이블 =====
  const SlatWorkLogTable = () => {
    const lots = workLogData.slatLots || [
      { lotNo: 'SLT-241210-01', spec: '100mm', color: '화이트', productionQty: 500, defectQty: 5 },
      { lotNo: 'SLT-241210-02', spec: '100mm', color: '아이보리', productionQty: 300, defectQty: 3 },
      { lotNo: 'SLT-241210-03', spec: '80mm', color: '화이트', productionQty: 400, defectQty: 2 },
    ];
    const totalProduction = lots.reduce((sum, l) => sum + l.productionQty, 0);
    const totalDefect = lots.reduce((sum, l) => sum + l.defectQty, 0);
    const totalGood = totalProduction - totalDefect;
    const yieldRate = totalProduction > 0 ? Math.round((totalGood / totalProduction) * 100) : 0;

    return (
      <div className="mb-4">
        <div className="bg-black text-white px-3 py-1 font-bold text-sm">L O T 별 생 산 내 역</div>
        <table className="w-full border-collapse text-xs">
          <thead>
            <tr className="bg-gray-100">
              <th className="border border-gray-400 px-2 py-1 font-bold w-10">NO</th>
              <th className="border border-gray-400 px-2 py-1 font-bold">LOT번호</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-20">규격</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-16">색상</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-16">생산량</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-14">불량</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-14">양품</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-14">양품율</th>
            </tr>
          </thead>
          <tbody>
            {lots.map((lot, idx) => {
              const good = lot.productionQty - lot.defectQty;
              const rate = lot.productionQty > 0 ? Math.round((good / lot.productionQty) * 100) : 0;
              return (
                <tr key={lot.lotNo}>
                  <td className="border border-gray-400 px-2 py-1 text-center">{idx + 1}</td>
                  <td className="border border-gray-400 px-2 py-1 font-mono">{lot.lotNo}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center">{lot.spec}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center">{lot.color}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center font-bold bg-yellow-50">{lot.productionQty}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center text-red-600">{lot.defectQty}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center text-green-600">{good}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center">{rate}%</td>
                </tr>
              );
            })}
            <tr className="bg-blue-100 font-bold">
              <td colSpan={4} className="border border-gray-400 px-2 py-1 text-right">합 계:</td>
              <td className="border border-gray-400 px-2 py-1 text-center">{totalProduction}</td>
              <td className="border border-gray-400 px-2 py-1 text-center text-red-600">{totalDefect}</td>
              <td className="border border-gray-400 px-2 py-1 text-center text-green-600">{totalGood}</td>
              <td className="border border-gray-400 px-2 py-1 text-center text-lg">{yieldRate}%</td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  };

  // ===== 포밍 작업일지: 재고부품 생산내역 =====
  const FormingWorkLogTable = () => {
    const items = workLogData.formingItems || [
      { itemCode: 'STK-001', itemName: '슬랫 캡', spec: '100mm', qty: 200, unit: 'EA' },
      { itemCode: 'STK-002', itemName: '바텀레일', spec: '1200mm', qty: 50, unit: 'EA' },
    ];
    const totalQty = items.reduce((sum, i) => sum + i.qty, 0);

    return (
      <div className="mb-4">
        <div className="bg-black text-white px-3 py-1 font-bold text-sm">포 밍 생 산 내 역</div>
        <table className="w-full border-collapse text-xs">
          <thead>
            <tr className="bg-gray-100">
              <th className="border border-gray-400 px-2 py-1 font-bold w-10">NO</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-24">품목코드</th>
              <th className="border border-gray-400 px-2 py-1 font-bold">품목명</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-24">규격</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-16">수량</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-12">단위</th>
            </tr>
          </thead>
          <tbody>
            {items.map((item, idx) => (
              <tr key={item.itemCode}>
                <td className="border border-gray-400 px-2 py-1 text-center">{idx + 1}</td>
                <td className="border border-gray-400 px-2 py-1 font-mono">{item.itemCode}</td>
                <td className="border border-gray-400 px-2 py-1">{item.itemName}</td>
                <td className="border border-gray-400 px-2 py-1 text-center">{item.spec}</td>
                <td className="border border-gray-400 px-2 py-1 text-center font-bold bg-yellow-50">{item.qty}</td>
                <td className="border border-gray-400 px-2 py-1 text-center">{item.unit}</td>
              </tr>
            ))}
            <tr className="bg-blue-100">
              <td colSpan={4} className="border border-gray-400 px-2 py-1 text-right font-bold">총 생산량:</td>
              <td className="border border-gray-400 px-2 py-1 text-center font-bold text-lg">{totalQty}</td>
              <td className="border border-gray-400 px-2 py-1 text-center font-bold">EA</td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  };

  // ===== 포장 작업일지: 박스별 수량 테이블 =====
  const PackagingWorkLogTable = () => {
    const boxes = workLogData.packagingBoxes || [
      { boxNo: 1, boxType: '대', itemName: '슬랫 100mm', qty: 50, note: '' },
      { boxNo: 2, boxType: '중', itemName: '고정클립', qty: 100, note: '' },
      { boxNo: 3, boxType: '소', itemName: '연결브라켓', qty: 40, note: '취급주의' },
    ];
    const totalBoxes = boxes.length;

    return (
      <div className="mb-4">
        <div className="bg-black text-white px-3 py-1 font-bold text-sm">포 장 내 역</div>
        <table className="w-full border-collapse text-xs">
          <thead>
            <tr className="bg-gray-100">
              <th className="border border-gray-400 px-2 py-1 font-bold w-12">박스번호</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-12">규격</th>
              <th className="border border-gray-400 px-2 py-1 font-bold">내용물</th>
              <th className="border border-gray-400 px-2 py-1 font-bold w-16">수량</th>
              <th className="border border-gray-400 px-2 py-1 font-bold">비고</th>
            </tr>
          </thead>
          <tbody>
            {boxes.map(box => (
              <tr key={box.boxNo}>
                <td className="border border-gray-400 px-2 py-1 text-center font-bold">{box.boxNo}</td>
                <td className="border border-gray-400 px-2 py-1 text-center">{box.boxType}</td>
                <td className="border border-gray-400 px-2 py-1">{box.itemName}</td>
                <td className="border border-gray-400 px-2 py-1 text-center font-bold bg-yellow-50">{box.qty}</td>
                <td className="border border-gray-400 px-2 py-1 text-gray-600">{box.note}</td>
              </tr>
            ))}
            <tr className="bg-blue-100">
              <td colSpan={3} className="border border-gray-400 px-2 py-1 text-right font-bold">총 박스 수:</td>
              <td className="border border-gray-400 px-2 py-1 text-center font-bold text-lg">{totalBoxes}</td>
              <td className="border border-gray-400 px-2 py-1 text-center font-bold">박스</td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  };

  // 공정별 전용 테이블 렌더링
  const renderProcessSpecificTable = () => {
    switch (docCode) {
      case 'WL-SCR': return <ScreenWorkLogTable />;
      case 'WL-FLD': return <FoldWorkLogTable />;
      case 'WL-SLT': return <SlatWorkLogTable />;
      case 'WL-STK': return <FormingWorkLogTable />;
      case 'WL-PKG': return <PackagingWorkLogTable />;
      default: return null;
    }
  };

  // 자재 사용 내역 타이틀 (공정별)
  const getMaterialTitle = () => {
    const titles = {
      'WL-SCR': '원단 사용내역',
      'WL-FLD': '철판 사용내역',
      'WL-SLT': '슬랫 자재 사용내역',
      'WL-STK': '포밍 자재 사용내역',
      'WL-PKG': '포장재 사용내역',
    };
    return titles[docCode] || '자재 사용 내역';
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className={`bg-white w-full rounded-xl max-h-[90vh] overflow-auto shadow-2xl ${docCode === 'WL-SCR' ? 'max-w-4xl' : 'max-w-2xl'}`}>
        {/* 모달 헤더 */}
        <div className="flex items-center justify-between p-4 border-b sticky top-0 bg-white z-10">
          <div className="flex items-center gap-3">
            <h3 className="font-bold text-gray-900">📋 {task.processType} 작업일지</h3>
            <span className="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded font-mono">{docCode}</span>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={handlePrint}
              className="px-4 py-2 bg-blue-500 text-white rounded-lg text-sm font-medium hover:bg-blue-600 flex items-center gap-2"
            >
              <Printer className="w-4 h-4" /> 출력
            </button>
            <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg">
              <X className="w-5 h-5 text-gray-500" />
            </button>
          </div>
        </div>

        {/* 작업일지 미리보기 (ISO 인증용 양식) */}
        <div className="p-6 print:p-0" id="work-log-printable">
          {/* 문서 헤더 */}
          <div className="text-center mb-6">
            <h1 className="text-2xl font-bold tracking-widest">{task.processType} 작 업 일 지</h1>
            <p className="text-sm text-gray-500 mt-1">{workLogData.workLogNo}</p>
          </div>

          {/* 결재라인 (우측 상단) - APR-2LINE 스타일 */}
          <div className="flex justify-end mb-4">
            <table className="border-collapse border border-gray-400 text-sm">
              <thead>
                <tr className="bg-gray-100">
                  {workLogData.approvalLine.roles.map(role => (
                    <th key={role.id} className="border border-gray-400 px-4 py-1 font-medium w-20">
                      {role.label}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                <tr>
                  {workLogData.approvalLine.roles.map(role => (
                    <td key={role.id} className="border border-gray-400 px-4 py-3 h-16 text-center align-middle">
                      {role.signed ? (
                        <div className="text-center">
                          <span className="text-red-500 font-bold">{role.name}</span>
                          <p className="text-xs text-gray-500">{role.date}</p>
                        </div>
                      ) : (
                        <span className="text-gray-300">(인)</span>
                      )}
                    </td>
                  ))}
                </tr>
              </tbody>
            </table>
          </div>

          {/* 기본 정보 테이블 (WL-HEADER-INFO 블록) */}
          <table className="w-full border-collapse border border-gray-400 mb-4 text-sm">
            <tbody>
              <tr>
                <th className="border border-gray-400 bg-gray-100 px-3 py-2 w-24 text-left font-medium">신청업체</th>
                <td className="border border-gray-400 px-3 py-2">{workLogData.customerName}</td>
                <th className="border border-gray-400 bg-gray-100 px-3 py-2 w-24 text-left font-medium">작성일</th>
                <td className="border border-gray-400 px-3 py-2">{workLogData.workDate}</td>
              </tr>
              <tr>
                <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">현장명</th>
                <td className="border border-gray-400 px-3 py-2">{workLogData.siteName}</td>
                <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">작성자</th>
                <td className="border border-gray-400 px-3 py-2">{workLogData.writer}</td>
              </tr>
              <tr>
                <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">작업지시번호</th>
                <td className="border border-gray-400 px-3 py-2" colSpan={3}>{workLogData.workOrderNo}</td>
              </tr>
              <tr>
                <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">신청내용</th>
                <td className="border border-gray-400 px-3 py-2" colSpan={3}>{workLogData.requestContent}</td>
              </tr>
            </tbody>
          </table>

          {/* ★ 공정별 전용 작업내역 테이블 (ISO 인증용 핵심 블록) */}
          {renderProcessSpecificTable()}

          {/* 공정 진행 상태 (비 ISO 공정은 범용 테이블 사용) */}
          {!renderProcessSpecificTable() && (
            <>
              <div className="mb-4">
                <h3 className="text-sm font-bold mb-2 flex items-center gap-2">
                  <span className="w-1 h-4 bg-blue-500 rounded"></span>
                  공정 진행 현황 ({workLogData.progress.completed}/{workLogData.progress.total} 완료)
                </h3>
                <div className="flex gap-2 flex-wrap">
                  {workLogData.progress.steps.map((step, idx) => (
                    <div
                      key={step.name}
                      className={`px-3 py-2 rounded-lg border text-sm flex items-center gap-2 ${step.status.status === 'completed'
                          ? 'bg-green-50 border-green-300 text-green-700'
                          : step.status.status === 'waiting'
                            ? 'bg-yellow-50 border-yellow-300 text-yellow-700'
                            : 'bg-gray-50 border-gray-200 text-gray-500'
                        }`}
                    >
                      <span className="font-medium">{idx + 1}. {step.name}</span>
                      {step.type === 'inspection' && <span className="text-xs bg-purple-100 text-purple-600 px-1 rounded">품질팀</span>}
                      {step.status.status === 'completed' && <Check className="w-4 h-4" />}
                      {step.status.status === 'waiting' && <Clock className="w-4 h-4" />}
                    </div>
                  ))}
                </div>
              </div>

              {/* 생산 실적 (범용) */}
              <table className="w-full border-collapse border border-gray-400 mb-4 text-sm">
                <thead>
                  <tr className="bg-gray-100">
                    <th className="border border-gray-400 px-3 py-2 font-medium">지시 수량</th>
                    <th className="border border-gray-400 px-3 py-2 font-medium">양품 수량</th>
                    <th className="border border-gray-400 px-3 py-2 font-medium">불량 수량</th>
                    <th className="border border-gray-400 px-3 py-2 font-medium">양품율</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td className="border border-gray-400 px-3 py-3 text-center font-bold text-lg">{workLogData.production.totalQty}</td>
                    <td className="border border-gray-400 px-3 py-3 text-center font-bold text-lg text-green-600">{workLogData.production.goodQty}</td>
                    <td className="border border-gray-400 px-3 py-3 text-center font-bold text-lg text-red-600">{workLogData.production.defectQty}</td>
                    <td className="border border-gray-400 px-3 py-3 text-center font-bold text-lg">
                      {workLogData.production.totalQty > 0
                        ? Math.round((workLogData.production.goodQty / workLogData.production.totalQty) * 100)
                        : 0}%
                    </td>
                  </tr>
                </tbody>
              </table>
            </>
          )}

          {/* 생산실적 요약 (WL-SUMMARY 블록) */}
          {renderProcessSpecificTable() && (
            <div className="mb-4">
              <div className="bg-black text-white px-3 py-1 font-bold text-sm">생 산 실 적 요 약</div>
              <div className="grid grid-cols-4 gap-0">
                <div className="border border-gray-400 p-3 text-center">
                  <div className="text-xs text-gray-500">총 생산량</div>
                  <div className="text-xl font-bold">{workLogData.production.totalQty}</div>
                </div>
                <div className="border border-gray-400 p-3 text-center">
                  <div className="text-xs text-gray-500">양품 수량</div>
                  <div className="text-xl font-bold text-green-600">{workLogData.production.goodQty}</div>
                </div>
                <div className="border border-gray-400 p-3 text-center">
                  <div className="text-xs text-gray-500">불량 수량</div>
                  <div className="text-xl font-bold text-red-600">{workLogData.production.defectQty}</div>
                </div>
                <div className="border border-gray-400 p-3 text-center">
                  <div className="text-xs text-gray-500">양품율</div>
                  <div className="text-xl font-bold">
                    {workLogData.production.totalQty > 0
                      ? Math.round((workLogData.production.goodQty / workLogData.production.totalQty) * 100)
                      : 0}%
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* 자재 사용 내역 (WL-MATERIAL-USAGE 블록) */}
          <div className="mb-4">
            <div className="bg-black text-white px-3 py-1 font-bold text-sm">{getMaterialTitle()}</div>
            {workLogData.materialUsage.length > 0 ? (
              <table className="w-full border-collapse text-xs">
                <thead>
                  <tr className="bg-gray-100">
                    <th className="border border-gray-400 px-2 py-1 font-bold w-10">NO</th>
                    <th className="border border-gray-400 px-2 py-1 font-bold">자재명</th>
                    <th className="border border-gray-400 px-2 py-1 font-bold">입고 로트번호</th>
                    <th className="border border-gray-400 px-2 py-1 font-bold w-16">사용량</th>
                    <th className="border border-gray-400 px-2 py-1 font-bold w-20">투입시간</th>
                    <th className="border border-gray-400 px-2 py-1 font-bold">비고</th>
                  </tr>
                </thead>
                <tbody>
                  {workLogData.materialUsage.map((material, idx) => (
                    <tr key={material.id}>
                      <td className="border border-gray-400 px-2 py-1 text-center">{idx + 1}</td>
                      <td className="border border-gray-400 px-2 py-1">{material.materialName}</td>
                      <td className="border border-gray-400 px-2 py-1 font-mono">{material.lotNo}</td>
                      <td className="border border-gray-400 px-2 py-1 text-center">{material.qty} {material.unit}</td>
                      <td className="border border-gray-400 px-2 py-1 text-center">
                        {new Date(material.inputAt).toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' })}
                      </td>
                      <td className="border border-gray-400 px-2 py-1 text-gray-500">{material.remarks || ''}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <div className="border border-gray-400 p-4 text-center text-gray-400 text-sm">
                투입된 자재가 없습니다
              </div>
            )}
          </div>

          {/* 특이사항 (RMK-STANDARD 블록) */}
          <div className="mb-4">
            <div className="bg-black text-white px-3 py-1 font-bold text-sm">특 이 사 항</div>
            <div className="border border-gray-400 p-3 min-h-[60px] text-sm">
              {workLogData.remarks || <span className="text-gray-400">특이사항 없음</span>}
            </div>
          </div>
        </div>

        {/* 모달 푸터 */}
        <div className="p-4 border-t flex gap-3 sticky bottom-0 bg-white">
          <Button variant="outline" className="flex-1" onClick={onClose}>닫기</Button>
          <Button variant="primary" className="flex-1" onClick={handlePrint}>
            <Printer className="w-4 h-4" /> 인쇄하기
          </Button>
        </div>
      </div>
    </div>
  );
};

// 이슈 보고 모달
const IssueReportModal = ({ task, onClose, onSubmit }) => {
  const [issueType, setIssueType] = useState('');
  const [description, setDescription] = useState('');

  // 이슈 유형 - 아이콘 없이 기본 항목으로
  const issueTypes = [
    { id: 'defect', label: '불량품 발생' },
    { id: 'no-stock', label: '재고 없음' },
    { id: 'delay', label: '일정 지연' },
    { id: 'equipment', label: '설비 문제' },
    { id: 'other', label: '기타' },
  ];

  const handleSubmit = () => {
    if (!issueType) {
      alert('이슈 유형을 선택해주세요.');
      return;
    }
    onSubmit({
      type: issueType,
      description,
      reportedAt: new Date().toISOString(),
      taskId: task.id,
    });
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-end sm:items-center justify-center z-50">
      <div className="bg-white w-full sm:max-w-md sm:rounded-xl rounded-t-xl max-h-[80vh] overflow-hidden">
        <div className="flex items-center justify-between p-4 border-b">
          <h3 className="font-bold text-gray-900">이슈 보고</h3>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg">
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        <div className="p-4 space-y-4">
          <div className="p-3 bg-gray-50 rounded-lg">
            <p className="text-sm text-gray-600">작업: {task.workOrderNo}</p>
            <p className="text-sm text-gray-600">{task.customerName}</p>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">이슈 유형</label>
            <div className="grid grid-cols-2 gap-2">
              {issueTypes.map(type => (
                <button
                  key={type.id}
                  onClick={() => setIssueType(type.id)}
                  className={`p-3 rounded-lg border text-left transition-all ${issueType === type.id
                      ? 'border-blue-500 bg-blue-50'
                      : 'border-gray-200 hover:border-gray-300'
                    }`}
                >
                  <p className="text-sm font-medium">{type.label}</p>
                </button>
              ))}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">상세 내용</label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={3}
              className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
              placeholder="이슈 내용을 상세히 입력해주세요..."
            />
          </div>
        </div>

        <div className="flex gap-2 p-4 border-t bg-gray-50">
          <Button variant="outline" className="flex-1" onClick={onClose}>취소</Button>
          <Button variant="primary" className="flex-1" onClick={handleSubmit}>
            <Send className="w-4 h-4" /> 보고
          </Button>
        </div>
      </div>
    </div>
  );
};

// ============ 생산지시 상세 모달 (스텝/위자드 기반) ============
const ProductionOrderModal = ({ order, onClose, onConfirm, onPreview, inventory = [] }) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [priority, setPriority] = useState('일반');
  const [note, setNote] = useState('');
  const [showDetailTab, setShowDetailTab] = useState('screen'); // 상세 탭 (스크린/모터/절곡)

  // 품목에서 카테고리 추정
  const inferCategory = (item) => {
    if (item.category) return item.category;
    const name = (item.productName || '').toLowerCase();
    if (name.includes('슬랫') || name.includes('slat')) return '슬랫';
    if (name.includes('철재') || name.includes('steel')) return '철재';
    return '스크린';
  };

  // 품목 카테고리 분석
  const items = order.items || [];
  const categories = [...new Set(items.map(item => inferCategory(item)))];
  const hasScreen = categories.includes('스크린');
  const hasSlat = categories.includes('슬랫') || categories.includes('철재');

  // 생성될 작업지시 미리보기
  const previewWorkOrders = [];
  const dateCode = new Date().toISOString().slice(2, 10).replace(/-/g, '');
  let seqNum = 1;

  if (hasScreen) {
    const screenItems = items.filter(item => inferCategory(item) === '스크린');
    previewWorkOrders.push({
      processType: '스크린',
      workOrderNo: `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`,
      steps: ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'],
      itemCount: screenItems.length,
      totalQty: screenItems.reduce((sum, item) => sum + (item.qty || 1), 0),
    });
  }

  if (hasSlat) {
    const slatItems = items.filter(item => ['슬랫', '철재'].includes(inferCategory(item)));
    previewWorkOrders.push({
      processType: '슬랫',
      workOrderNo: `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`,
      steps: ['코일절단', '중간검사', '미미작업', '포장'],
      itemCount: slatItems.length,
      totalQty: slatItems.reduce((sum, item) => sum + (item.qty || 1), 0),
    });
  }

  // 절곡 공정 (항상 필요)
  previewWorkOrders.push({
    processType: '절곡',
    workOrderNo: `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`,
    steps: ['절단', '절곡', '중간검사', '포장'],
    itemCount: items.length,
    totalQty: items.length,
  });

  // 자재 소요량 계산
  const materialRequirements = [
    { code: 'SCR-MAT-001', name: '스크린 원단', unit: '㎡', required: hasScreen ? items.filter(i => inferCategory(i) === '스크린').length * 15 : 0, stock: 500 },
    { code: 'SCR-MAT-002', name: '앤드락', unit: 'EA', required: hasScreen ? items.filter(i => inferCategory(i) === '스크린').length * 2 : 0, stock: 800 },
    { code: 'SCR-MAT-003', name: '하단바', unit: 'EA', required: hasScreen ? items.filter(i => inferCategory(i) === '스크린').length : 0, stock: 120 },
    { code: 'SLT-MAT-001', name: '슬랫 코일', unit: 'KG', required: hasSlat ? items.filter(i => ['슬랫', '철재'].includes(inferCategory(i))).length * 25 : 0, stock: 1500 },
    { code: 'SLT-MAT-002', name: '미미자재', unit: 'EA', required: hasSlat ? items.filter(i => ['슬랫', '철재'].includes(inferCategory(i))).length * 4 : 0, stock: 600 },
    { code: 'BND-MAT-001', name: '철판', unit: 'KG', required: items.length * 30, stock: 2000 },
    { code: 'BND-MAT-002', name: '가이드레일', unit: 'M', required: items.length * 6, stock: 300 },
    { code: 'BND-MAT-003', name: '케이스', unit: 'EA', required: items.length, stock: 100 },
  ].filter(m => m.required > 0);

  // 재고에서 실제 수량 반영
  const materialsWithStock = materialRequirements.map(m => {
    const inventoryItem = inventory.find(i => i.materialCode === m.code);
    return {
      ...m,
      stock: inventoryItem?.stock ?? m.stock,
      isShort: (inventoryItem?.stock ?? m.stock) < m.required,
    };
  });

  // 품목에서 productionSpec 추출
  const screenItems = order.items?.map((item, idx) => {
    const spec = item.productionSpec || {};
    return {
      seq: String(idx + 1).padStart(2, '0'),
      type: spec.type || '와이어',
      drawingNo: spec.drawingNo || `${item.floor} ${item.location}`,
      openWidth: spec.openWidth || parseInt(item.spec?.split('×')[0]) || 0,
      openHeight: spec.openHeight || parseInt(item.spec?.split('×')[1]) || 0,
      prodWidth: spec.prodWidth || (parseInt(item.spec?.split('×')[0]) || 0) + 140,
      prodHeight: spec.prodHeight || Math.max((parseInt(item.spec?.split('×')[1]) || 0) + 400, 2950),
      guideRailType: spec.guideRailType || '백면형',
      guideRailSpec: spec.guideRailSpec || '120-70',
      shaft: spec.shaft || (parseInt(item.spec?.split('×')[0]) > 6000 ? 5 : 4),
      caseSpec: spec.caseSpec || '500-330',
      motorBracket: spec.motorBracket || '380-180',
      capacity: spec.capacity || (parseInt(item.spec?.split('×')[0]) > 6000 ? 300 : 160),
      finish: spec.finish || 'SUS마감',
    };
  }) || [];

  // 모터 스펙 (있으면 사용, 없으면 자동 계산)
  const motorSpec = order.motorSpec || {
    motors220V: [
      { model: 'KD-150K', qty: 0 },
      { model: 'KD-300K', qty: 0 },
      { model: 'KD-400K', qty: 0 },
    ],
    motors380V: [
      { model: 'KD-150K', qty: screenItems.filter(i => i.capacity <= 160).length },
      { model: 'KD-300K', qty: screenItems.filter(i => i.capacity > 160 && i.capacity <= 300).length },
      { model: 'KD-400K', qty: screenItems.filter(i => i.capacity > 300).length },
    ],
    brackets: [
      { spec: '380-180 [2-4"]', qty: screenItems.filter(i => i.shaft === 4).length },
      { spec: '380-180 [2-5"]', qty: screenItems.filter(i => i.shaft === 5).length },
    ],
    heatSinks: [
      { spec: '40-60, L-380', qty: screenItems.length * 4 },
    ],
    controllers: [
      { type: '매입형', qty: 0 },
      { type: '노출형', qty: 0 },
      { type: '핫라스', qty: 0 },
    ],
  };

  // BOM 데이터 (있으면 사용, 없으면 자동 계산)
  const bomData = order.bomData || {
    guideRails: {
      items: [
        { type: '백면형', spec: '120-70', code: 'KSE01/KWE01', lengths: [{ length: 3000, qty: screenItems.length * 2 }] },
        { type: '하부BASE', spec: '130-80', code: '', lengths: [{ length: 0, qty: screenItems.length * 2 }] },
      ],
      smokeBarrier: { spec: 'W80', lengths: [{ length: 2950, qty: screenItems.length * 2 }] },
    },
    cases: {
      mainSpec: '500-330',
      items: [
        { length: 4000, qty: Math.ceil(screenItems.length * 0.6) },
        { length: 3500, qty: Math.ceil(screenItems.length * 0.3) },
        { length: 3000, qty: Math.ceil(screenItems.length * 0.1) },
      ],
      sideCover: { spec: '500-355', qty: screenItems.length * 2 },
      smokeBarrier: { spec: 'W80', length: 3000, qty: Math.ceil(screenItems.length * 1.5) },
    },
    bottomFinish: {
      items: [
        { name: '하단마감재', spec: '50-40', lengths: [{ length: 4000, qty: screenItems.length }] },
        { name: '하단보강빔바', spec: '80-17', lengths: [{ length: 4000, qty: screenItems.length * 2 }] },
        { name: '하단부재횡철', spec: '50-12T', lengths: [{ length: 2000, qty: screenItems.length * 4 }] },
      ],
    },
  };

  // 스텝 정의 (4단계로 간소화)
  const steps = [
    { id: 'info', label: '기본정보', icon: FileText, description: '우선순위 및 메모' },
    { id: 'preview', label: '작업지시 확인', icon: ClipboardList, description: '생성될 작업지시' },
    { id: 'material', label: '자재확인', icon: Box, description: '자재 재고 확인' },
    { id: 'detail', label: '상세확인', icon: Package, description: '품목/BOM 상세' },
  ];

  // 스텝 이동
  const goNext = () => setCurrentStep(prev => Math.min(prev + 1, steps.length - 1));
  const goPrev = () => setCurrentStep(prev => Math.max(prev - 1, 0));
  const isLastStep = currentStep === steps.length - 1;

  // 백면형 가이드레일 전개도 SVG
  const GuideRailFrontSVG = () => (
    <svg viewBox="0 0 200 140" className="w-full h-32 border rounded bg-white">
      <text x="100" y="15" textAnchor="middle" className="text-xs fill-gray-700 font-medium">백면형 (120-70)</text>
      {/* 외곽선 */}
      <path d="M 40,30 L 40,120 L 50,120 L 50,40 L 150,40 L 150,120 L 160,120 L 160,30 Z"
        fill="none" stroke="#374151" strokeWidth="2" />
      {/* 내부선 */}
      <line x1="50" y1="40" x2="50" y2="120" stroke="#9CA3AF" strokeWidth="1" />
      <line x1="150" y1="40" x2="150" y2="120" stroke="#9CA3AF" strokeWidth="1" />
      {/* 치수선 */}
      <line x1="40" y1="125" x2="160" y2="125" stroke="#3B82F6" strokeWidth="1" markerEnd="url(#arrowhead)" />
      <text x="100" y="135" textAnchor="middle" className="text-xs fill-blue-600">120</text>
      <line x1="165" y1="30" x2="165" y2="120" stroke="#3B82F6" strokeWidth="1" />
      <text x="175" y="75" textAnchor="middle" className="text-xs fill-blue-600">70</text>
      {/* 부품 번호 */}
      <circle cx="45" cy="75" r="8" fill="#FEF3C7" stroke="#F59E0B" />
      <text x="45" y="79" textAnchor="middle" className="text-xs fill-amber-700">①</text>
      <circle cx="100" cy="55" r="8" fill="#FEF3C7" stroke="#F59E0B" />
      <text x="100" y="59" textAnchor="middle" className="text-xs fill-amber-700">②</text>
      <circle cx="155" cy="75" r="8" fill="#FEF3C7" stroke="#F59E0B" />
      <text x="155" y="79" textAnchor="middle" className="text-xs fill-amber-700">③</text>
    </svg>
  );

  // 측면형 가이드레일 전개도 SVG
  const GuideRailSideSVG = () => (
    <svg viewBox="0 0 200 140" className="w-full h-32 border rounded bg-white">
      <text x="100" y="15" textAnchor="middle" className="text-xs fill-gray-700 font-medium">측면형 (120-120)</text>
      {/* 외곽선 - 더 깊은 형태 */}
      <path d="M 40,30 L 40,120 L 50,120 L 50,40 L 150,40 L 150,120 L 160,120 L 160,30 Z"
        fill="none" stroke="#374151" strokeWidth="2" />
      {/* 내부 추가선 */}
      <line x1="60" y1="50" x2="60" y2="120" stroke="#9CA3AF" strokeWidth="1" />
      <line x1="140" y1="50" x2="140" y2="120" stroke="#9CA3AF" strokeWidth="1" />
      {/* 치수선 */}
      <line x1="40" y1="125" x2="160" y2="125" stroke="#3B82F6" strokeWidth="1" />
      <text x="100" y="135" textAnchor="middle" className="text-xs fill-blue-600">120</text>
      <line x1="165" y1="30" x2="165" y2="120" stroke="#3B82F6" strokeWidth="1" />
      <text x="175" y="75" textAnchor="middle" className="text-xs fill-blue-600">120</text>
      {/* 부품 번호 */}
      <circle cx="45" cy="75" r="8" fill="#DBEAFE" stroke="#3B82F6" />
      <text x="45" y="79" textAnchor="middle" className="text-xs fill-blue-700">①</text>
      <circle cx="100" cy="55" r="8" fill="#DBEAFE" stroke="#3B82F6" />
      <text x="100" y="59" textAnchor="middle" className="text-xs fill-blue-700">②</text>
      <circle cx="155" cy="75" r="8" fill="#DBEAFE" stroke="#3B82F6" />
      <text x="155" y="79" textAnchor="middle" className="text-xs fill-blue-700">③</text>
    </svg>
  );

  // 케이스(셔터박스) 전개도 SVG
  const CaseBoxSVG = () => (
    <svg viewBox="0 0 280 160" className="w-full h-40 border rounded bg-white">
      <text x="140" y="15" textAnchor="middle" className="text-xs fill-gray-700 font-medium">케이스(셔터박스) 500-330</text>
      {/* 메인 박스 */}
      <rect x="40" y="30" width="200" height="100" fill="none" stroke="#374151" strokeWidth="2" />
      {/* 내부 구획 */}
      <line x1="90" y1="30" x2="90" y2="130" stroke="#9CA3AF" strokeWidth="1" strokeDasharray="4" />
      <line x1="190" y1="30" x2="190" y2="130" stroke="#9CA3AF" strokeWidth="1" strokeDasharray="4" />
      <line x1="40" y1="80" x2="240" y2="80" stroke="#9CA3AF" strokeWidth="1" strokeDasharray="4" />
      {/* 치수 */}
      <line x1="40" y1="140" x2="240" y2="140" stroke="#3B82F6" strokeWidth="1" />
      <text x="140" y="152" textAnchor="middle" className="text-xs fill-blue-600">500</text>
      <line x1="250" y1="30" x2="250" y2="130" stroke="#3B82F6" strokeWidth="1" />
      <text x="265" y="80" textAnchor="middle" className="text-xs fill-blue-600">330</text>
      {/* 부품 라벨 */}
      <text x="65" y="60" textAnchor="middle" className="text-xs fill-gray-500">전면부</text>
      <text x="140" y="60" textAnchor="middle" className="text-xs fill-gray-500">린텔부</text>
      <text x="215" y="60" textAnchor="middle" className="text-xs fill-gray-500">후면</text>
      <text x="65" y="110" textAnchor="middle" className="text-xs fill-gray-500">①측면덮개</text>
      <text x="140" y="110" textAnchor="middle" className="text-xs fill-gray-500">②상부덮개</text>
      <text x="215" y="110" textAnchor="middle" className="text-xs fill-gray-500">③하부</text>
    </svg>
  );

  const hasShortage = materialsWithStock.some(m => m.isShort);

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl w-full max-w-5xl flex flex-col" style={{ maxHeight: '90vh' }}>
        {/* 헤더 - 고정 */}
        <div className="flex items-center justify-between p-4 border-b bg-gray-50" style={{ flexShrink: 0 }}>
          <div className="flex items-center gap-3">
            <Factory className="w-6 h-6 text-blue-600" />
            <div>
              <h2 className="text-lg font-bold">생산지시</h2>
              <p className="text-sm text-gray-500">{order.orderNo} · {order.siteName}</p>
            </div>
          </div>
          <div className="flex items-center gap-4">
            {/* 요약 정보 */}
            <div className="hidden md:flex items-center gap-4 text-sm">
              <div className="px-3 py-1 bg-blue-100 rounded-full text-blue-700">
                <span className="font-medium">{previewWorkOrders.length}</span>개 작업지시
              </div>
              {hasShortage && (
                <div className="px-3 py-1 bg-red-100 rounded-full text-red-700 flex items-center gap-1">
                  <AlertCircle className="w-3 h-3" /> 자재 부족
                </div>
              )}
            </div>
            <button onClick={onClose} className="p-2 hover:bg-gray-200 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
              ✕
            </button>
          </div>
        </div>

        {/* 탭 네비게이션 - 고정 */}
        <div className="flex border-b bg-gray-50 overflow-x-auto" style={{ flexShrink: 0 }}>
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-4 py-2 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${activeTab === tab.id
                  ? 'border-blue-500 text-blue-600 bg-white'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-100'
                }`}
            >
              <tab.icon className="w-4 h-4" />
              {tab.label}
              {tab.id === 'material' && hasShortage && (
                <span className="w-2 h-2 bg-red-500 rounded-full" />
              )}
            </button>
          ))}
        </div>

        {/* 탭 콘텐츠 - 스크롤 */}
        <div className="p-4" style={{ flex: 1, overflowY: 'auto' }}>
          {/* 기본정보 탭 */}
          {activeTab === 'info' && (
            <div className="space-y-6">
              {/* 신용등급 안내 */}
              <div className={`p-4 rounded-lg ${order.creditGrade === 'A' ? 'bg-green-50 border border-green-200' :
                  order.creditGrade === 'B' ? 'bg-yellow-50 border border-yellow-200' :
                    'bg-red-50 border border-red-200'
                }`}>
                <div className="flex items-center gap-2 mb-2">
                  <CreditGradeBadge grade={order.creditGrade} />
                  <span className="font-medium">
                    {order.creditGrade === 'A' ? '자동 진행 거래처' :
                      order.creditGrade === 'B' ? '입금확인 후 출고 거래처' :
                        '출고 시 경리승인 필요 거래처'}
                  </span>
                </div>
                <p className="text-sm">
                  {order.creditGrade === 'A' && '생산지시 후 자동으로 생산이 진행되고, 완료 후 바로 출고됩니다.'}
                  {order.creditGrade === 'B' && '생산지시 후 생산이 진행되며, 출고 시 입금확인이 필요합니다.'}
                  {order.creditGrade === 'C' && (
                    order.accountingStatus === '회계확인완료'
                      ? '✅ 경리승인 완료. 생산지시 가능하며, 출고 시 입금확인이 필요합니다.'
                      : '⚠️ 생산지시는 가능하나, 출고 시 경리승인이 필요합니다.'
                  )}
                </p>
              </div>

              {/* 수주 정보 */}
              <div className="grid grid-cols-1 gap-6">
                <Card title="신청 업체">
                  <div className="space-y-3 text-sm">
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-gray-500">발주일</span>
                      <span className="font-medium">{order.orderDate}</span>
                    </div>
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-gray-500">발주처</span>
                      <span className="font-medium">{order.customerName}</span>
                    </div>
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-gray-500">발주담당자</span>
                      <span className="font-medium">{order.manager || '-'}</span>
                    </div>
                    <div className="flex justify-between py-2">
                      <span className="text-gray-500">연락처</span>
                      <span className="font-medium">{order.contact || '-'}</span>
                    </div>
                  </div>
                </Card>

                <Card title="납품 정보">
                  <div className="space-y-3 text-sm">
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-gray-500">현장명</span>
                      <span className="font-medium text-blue-600">{order.siteName}</span>
                    </div>
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-gray-500">납기요청일</span>
                      <span className="font-medium text-red-600">{order.dueDate}</span>
                    </div>
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-gray-500">인수담당자</span>
                      <span className="font-medium">{order.receiverName || '-'}</span>
                    </div>
                    <div className="flex justify-between py-2">
                      <span className="text-gray-500">배송방법</span>
                      <span className="font-medium">{order.deliveryMethod || '상차'}</span>
                    </div>
                  </div>
                </Card>
              </div>

              {/* 배송지 */}
              <Card title="배송지 주소">
                <p className="text-sm">{order.deliveryAddress || '-'}</p>
              </Card>
            </div>
          )}

          {/* 작업지시 미리보기 탭 */}
          {activeTab === 'preview' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <h3 className="font-bold text-lg">
                  생성될 작업지시 ({previewWorkOrders.length}건)
                </h3>
              </div>

              {/* 작업지시 카드들 */}
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
                {previewWorkOrders.map((wo, idx) => (
                  <div key={idx} className="border rounded-xl overflow-hidden">
                    <div className={`px-4 py-3 font-medium flex items-center justify-between ${wo.processType === '스크린' ? 'bg-blue-50 text-blue-700' :
                        wo.processType === '슬랫' ? 'bg-purple-50 text-purple-700' :
                          'bg-amber-50 text-amber-700'
                      }`}>
                      <span>{wo.processType} 공정</span>
                      <span className="text-xs font-mono bg-white/50 px-2 py-0.5 rounded">{wo.workOrderNo}</span>
                    </div>
                    <div className="p-4 space-y-4">
                      {/* 수량 정보 */}
                      <div className="grid grid-cols-2 gap-4 text-sm">
                        <div>
                          <p className="text-gray-500">품목 수</p>
                          <p className="text-xl font-bold">{wo.itemCount}건</p>
                        </div>
                        <div>
                          <p className="text-gray-500">총 수량</p>
                          <p className="text-xl font-bold">{wo.totalQty}EA</p>
                        </div>
                      </div>

                      {/* 작업 단계 */}
                      <div>
                        <p className="text-xs text-gray-500 mb-2">작업 단계</p>
                        <div className="flex flex-wrap gap-1">
                          {wo.steps.map((step, sidx) => (
                            <span key={sidx} className="text-xs px-2 py-1 bg-gray-100 rounded">
                              {sidx + 1}. {step}
                            </span>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* 옵션 설정 */}
              <Card title="생산지시 옵션">
                <div className="grid grid-cols-1 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">우선순위</label>
                    <div className="flex gap-2">
                      {['긴급', '높음', '일반', '낮음'].map(p => (
                        <button
                          key={p}
                          onClick={() => setPriority(p)}
                          className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${priority === p
                              ? p === '긴급' ? 'bg-red-500 text-white' :
                                p === '높음' ? 'bg-orange-500 text-white' :
                                  p === '일반' ? 'bg-blue-500 text-white' :
                                    'bg-gray-500 text-white'
                              : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                            }`}
                        >
                          {p}
                        </button>
                      ))}
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">특이사항</label>
                    <textarea
                      value={note}
                      onChange={(e) => setNote(e.target.value)}
                      placeholder="생산 시 주의사항 입력..."
                      rows={2}
                      className="w-full px-3 py-2 border rounded-lg text-sm"
                    />
                  </div>
                </div>
              </Card>
            </div>
          )}

          {/* 자재 소요량 탭 */}
          {activeTab === 'material' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <h3 className="font-bold text-lg flex items-center gap-2">
                  <Box className="w-5 h-5 text-green-500" />
                  자재 소요량 확인
                </h3>
                {hasShortage && (
                  <div className="flex items-center gap-2 px-3 py-1 bg-red-100 text-red-700 rounded-full text-sm">
                    <AlertCircle className="w-4 h-4" />
                    일부 자재 재고 부족
                  </div>
                )}
              </div>

              <Card>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-4 py-3 text-left font-medium text-gray-500">자재코드</th>
                        <th className="px-4 py-3 text-left font-medium text-gray-500">자재명</th>
                        <th className="px-4 py-3 text-center font-medium text-gray-500">단위</th>
                        <th className="px-4 py-3 text-right font-medium text-gray-500">소요량</th>
                        <th className="px-4 py-3 text-right font-medium text-gray-500">현재고</th>
                        <th className="px-4 py-3 text-right font-medium text-gray-500">예상잔고</th>
                        <th className="px-4 py-3 text-center font-medium text-gray-500">상태</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {materialsWithStock.map((m, idx) => (
                        <tr key={idx} className={m.isShort ? 'bg-red-50' : ''}>
                          <td className="px-4 py-3 font-mono text-blue-600">{m.code}</td>
                          <td className="px-4 py-3 font-medium">{m.name}</td>
                          <td className="px-4 py-3 text-center text-gray-500">{m.unit}</td>
                          <td className="px-4 py-3 text-right font-medium">{m.required.toLocaleString()}</td>
                          <td className="px-4 py-3 text-right">{m.stock.toLocaleString()}</td>
                          <td className={`px-4 py-3 text-right font-bold ${m.isShort ? 'text-red-600' : 'text-green-600'}`}>
                            {(m.stock - m.required).toLocaleString()}
                          </td>
                          <td className="px-4 py-3 text-center">
                            {m.isShort ? (
                              <span className="inline-flex items-center gap-1 px-2 py-1 bg-red-100 text-red-700 rounded-full text-xs">
                                <XCircle className="w-3 h-3" /> 부족
                              </span>
                            ) : (
                              <span className="inline-flex items-center gap-1 px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs">
                                <CheckCircle className="w-3 h-3" /> 충분
                              </span>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </Card>

              {hasShortage && (
                <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                  <div className="flex items-start gap-3">
                    <AlertCircle className="w-5 h-5 text-yellow-600 mt-0.5" />
                    <div>
                      <h4 className="font-medium text-yellow-800">재고 부족 경고</h4>
                      <p className="text-sm text-yellow-700 mt-1">
                        일부 자재의 재고가 부족합니다. 생산지시는 가능하지만, 자재 입고 후 생산을 진행하시기 바랍니다.
                      </p>
                      <Button variant="outline" size="sm" className="mt-3">
                        <Download className="w-4 h-4" /> 구매요청서 생성
                      </Button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* 스크린 품목 탭 */}
          {activeTab === 'screen' && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="font-bold text-lg">1. 스크린 ({screenItems.length}개)</h3>
                <p className="text-sm text-gray-500">* 가이드레일 너비 120° 기준</p>
              </div>
              <div className="overflow-x-auto border rounded-lg">
                <table className="w-full text-sm">
                  <thead className="bg-gray-100">
                    <tr>
                      <th rowSpan="2" className="px-2 py-2 text-center border-r font-medium">일련번호</th>
                      <th rowSpan="2" className="px-2 py-2 text-center border-r font-medium">종류</th>
                      <th rowSpan="2" className="px-2 py-2 text-center border-r font-medium">도면부호</th>
                      <th colSpan="2" className="px-2 py-1 text-center border-r border-b font-medium bg-green-100 text-green-800">오픈사이즈(mm)</th>
                      <th colSpan="2" className="px-2 py-1 text-center border-r border-b font-medium bg-red-100 text-red-800">제작사이즈(mm)</th>
                      <th rowSpan="2" className="px-2 py-2 text-center border-r font-medium">가이드레일<br />유형</th>
                      <th rowSpan="2" className="px-2 py-2 text-center border-r font-medium">샤프트<br />(인치)</th>
                      <th rowSpan="2" className="px-2 py-2 text-center border-r font-medium">케이스<br />(규격)</th>
                      <th colSpan="2" className="px-2 py-1 text-center border-r border-b font-medium">모터</th>
                      <th rowSpan="2" className="px-2 py-2 text-center font-medium">마감</th>
                    </tr>
                    <tr>
                      <th className="px-2 py-1 text-center border-r font-medium bg-green-50">가로</th>
                      <th className="px-2 py-1 text-center border-r font-medium bg-green-50">세로</th>
                      <th className="px-2 py-1 text-center border-r font-medium bg-red-50">(오픈+140)</th>
                      <th className="px-2 py-1 text-center border-r font-medium bg-red-50">(오픈+350)</th>
                      <th className="px-2 py-1 text-center border-r font-medium">브라켓</th>
                      <th className="px-2 py-1 text-center border-r font-medium">용량(KG)</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {screenItems.map((item, idx) => (
                      <tr key={idx} className={idx % 2 === 1 ? 'bg-gray-50' : ''}>
                        <td className="px-2 py-2 text-center border-r">{item.seq}</td>
                        <td className="px-2 py-2 text-center border-r">{item.type}</td>
                        <td className="px-2 py-2 text-center border-r font-medium">{item.drawingNo}</td>
                        <td className="px-2 py-2 text-center border-r bg-green-50 text-green-700">{item.openWidth?.toLocaleString()}</td>
                        <td className="px-2 py-2 text-center border-r bg-green-50 text-green-700">{item.openHeight?.toLocaleString()}</td>
                        <td className="px-2 py-2 text-center border-r bg-red-50 text-red-700 font-bold">{item.prodWidth?.toLocaleString()}</td>
                        <td className="px-2 py-2 text-center border-r bg-red-50 text-red-700 font-bold">{item.prodHeight?.toLocaleString()}</td>
                        <td className="px-2 py-2 text-center border-r text-xs">{item.guideRailType}<br />({item.guideRailSpec})</td>
                        <td className="px-2 py-2 text-center border-r">{item.shaft}</td>
                        <td className="px-2 py-2 text-center border-r text-xs">{item.caseSpec}</td>
                        <td className="px-2 py-2 text-center border-r text-xs">{item.motorBracket}</td>
                        <td className="px-2 py-2 text-center border-r">{item.capacity}</td>
                        <td className="px-2 py-2 text-center text-xs">{item.finish}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* 모터/전장품 탭 */}
          {activeTab === 'motor' && (
            <div className="space-y-6">
              <h3 className="font-bold text-lg">2. 모터</h3>

              <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                {/* 2-1. 모터(220V 단상) */}
                <Card title="2-1. 모터(220V 단상)">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-2 py-1 text-left">모터 용량</th>
                        <th className="px-2 py-1 text-right">수량</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {motorSpec.motors220V?.map((motor, idx) => (
                        <tr key={idx}>
                          <td className="px-2 py-2">{motor.model}</td>
                          <td className="px-2 py-2 text-right font-medium">{motor.qty || '-'}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </Card>

                {/* 2-2. 모터(380V 삼상) */}
                <Card title="2-2. 모터(380V 삼상)">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-2 py-1 text-left">모터 용량</th>
                        <th className="px-2 py-1 text-right">수량</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {motorSpec.motors380V?.map((motor, idx) => (
                        <tr key={idx}>
                          <td className="px-2 py-2 text-red-600 font-medium">{motor.model}</td>
                          <td className="px-2 py-2 text-right font-bold text-red-600">{motor.qty || '-'}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </Card>

                {/* 2-3. 브라켓 */}
                <Card title="2-3. 브라켓">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-2 py-1 text-left">브라켓</th>
                        <th className="px-2 py-1 text-right">수량</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {motorSpec.brackets?.map((bracket, idx) => (
                        <tr key={idx}>
                          <td className="px-2 py-2">{bracket.spec}</td>
                          <td className="px-2 py-2 text-right font-medium">{bracket.qty || '-'}</td>
                        </tr>
                      ))}
                      <tr className="bg-yellow-50">
                        <td className="px-2 py-2">방열등</td>
                        <td className="px-2 py-2 text-right font-medium">{motorSpec.heatSinks?.[0]?.qty || screenItems.length * 4}</td>
                      </tr>
                    </tbody>
                  </table>
                </Card>

                {/* 2-4. 연동제어기 */}
                <Card title="2-4. 연동제어기">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-2 py-1 text-left">품명</th>
                        <th className="px-2 py-1 text-right">수량</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {motorSpec.controllers?.map((ctrl, idx) => (
                        <tr key={idx}>
                          <td className="px-2 py-2">{ctrl.type}</td>
                          <td className="px-2 py-2 text-right font-medium">{ctrl.qty || '-'}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </Card>
              </div>

              <p className="text-sm text-gray-500">* 별도 추가사항</p>
            </div>
          )}

          {/* 절곡물 BOM 탭 */}
          {activeTab === 'bom' && (
            <div className="space-y-8">
              <h3 className="font-bold text-lg">3. 절곡물</h3>

              {/* 3-1. 가이드레일 */}
              <div className="space-y-4">
                <div className="flex items-center gap-2">
                  <span className="font-bold">3-1. 가이드레일</span>
                  <span className="text-sm text-gray-500">- EGI 1.55T + 마감재 EGI 1.15T + 별도마감재 SUS 1.15T</span>
                </div>

                <div className="grid grid-cols-1 gap-6">
                  {/* 백면형 */}
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-amber-50 px-4 py-2 font-medium border-b">백면형 (120-70)</div>
                    <div className="p-4">
                      <GuideRailFrontSVG />
                      <div className="mt-4 text-xs text-gray-500">
                        ① 마감재 ② 가이드레일 ③ C형 ④ D형
                      </div>
                      <table className="w-full text-sm mt-4">
                        <thead className="bg-gray-50">
                          <tr>
                            <th className="px-2 py-1 text-left">코드</th>
                            <th className="px-2 py-1 text-right">길이</th>
                            <th className="px-2 py-1 text-right">수량</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y">
                          {bomData.guideRails?.items?.filter(i => i.type === '백면형').map((item, idx) => (
                            item.lengths?.map((len, lidx) => (
                              <tr key={`${idx}-${lidx}`} className={len.qty > 0 ? 'bg-blue-50' : ''}>
                                <td className="px-2 py-1 text-blue-600 font-medium">{item.code || '-'}</td>
                                <td className="px-2 py-1 text-right">L: {len.length?.toLocaleString()}</td>
                                <td className="px-2 py-1 text-right font-bold">{len.qty || '-'}</td>
                              </tr>
                            ))
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>

                  {/* 측면형 */}
                  <div className="border rounded-lg overflow-hidden">
                    <div className="bg-blue-50 px-4 py-2 font-medium border-b">측면형 (120-120)</div>
                    <div className="p-4">
                      <GuideRailSideSVG />
                      <div className="mt-4 text-xs text-gray-500">
                        ① ② 마감재 ③ ④ 가이드레일 ⑤ C형 ⑥ D형
                      </div>
                      <table className="w-full text-sm mt-4">
                        <thead className="bg-gray-50">
                          <tr>
                            <th className="px-2 py-1 text-left">코드</th>
                            <th className="px-2 py-1 text-right">길이</th>
                            <th className="px-2 py-1 text-right">수량</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y">
                          {bomData.guideRails?.items?.filter(i => i.type === '측면형').map((item, idx) => (
                            item.lengths?.map((len, lidx) => (
                              <tr key={`${idx}-${lidx}`} className={len.qty > 0 ? 'bg-blue-50' : ''}>
                                <td className="px-2 py-1 text-blue-600 font-medium">{item.code || '-'}</td>
                                <td className="px-2 py-1 text-right">L: {len.length?.toLocaleString()}</td>
                                <td className="px-2 py-1 text-right font-bold">{len.qty || '-'}</td>
                              </tr>
                            ))
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>

                {/* 하부BASE & 연기차단재 */}
                <div className="grid grid-cols-1 gap-6">
                  <Card title="하부BASE (130-80)">
                    <table className="w-full text-sm">
                      <tbody>
                        {bomData.guideRails?.items?.filter(i => i.type === '하부BASE').map((item, idx) => (
                          <tr key={idx}>
                            <td className="py-2">하부BASE</td>
                            <td className="py-2 text-right font-bold">{item.lengths?.[0]?.qty || '-'}개</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </Card>

                  <Card title="연기차단재 (W80)">
                    <div className="text-sm">
                      <p className="text-gray-500 mb-2">원 0.8T 화이바글라스코팅직물</p>
                      <p className="text-red-600 font-medium mb-2">* 가이드레일 양쪽에 설치</p>
                      <table className="w-full">
                        <thead className="bg-gray-50">
                          <tr>
                            <th className="px-2 py-1 text-left">규격(L)</th>
                            <th className="px-2 py-1 text-right">수량</th>
                          </tr>
                        </thead>
                        <tbody>
                          {bomData.guideRails?.smokeBarrier?.lengths?.map((len, idx) => (
                            <tr key={idx}>
                              <td className="px-2 py-1">{len.length?.toLocaleString()}</td>
                              <td className="px-2 py-1 text-right font-bold">{len.qty}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </Card>
                </div>
              </div>

              {/* 3-2. 케이스(셔터박스) */}
              <div className="space-y-4 pt-4 border-t">
                <div className="flex items-center gap-2">
                  <span className="font-bold">3-2. 케이스(셔터박스)</span>
                  <span className="text-sm text-gray-500">- EGI 1.55T</span>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div className="md:col-span-2 border rounded-lg overflow-hidden">
                    <div className="bg-pink-50 px-4 py-2 font-medium border-b">규격: {bomData.cases?.mainSpec} (150,300,400/K용)</div>
                    <div className="p-4">
                      <CaseBoxSVG />
                      <table className="w-full text-sm mt-4">
                        <thead className="bg-gray-50">
                          <tr>
                            <th className="px-2 py-1 text-left">규격</th>
                            <th className="px-2 py-1 text-right">길이</th>
                            <th className="px-2 py-1 text-right">수량</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y">
                          {bomData.cases?.items?.map((item, idx) => (
                            <tr key={idx} className={item.qty > 0 ? 'bg-pink-50' : ''}>
                              <td className="px-2 py-1">{bomData.cases?.mainSpec}</td>
                              <td className="px-2 py-1 text-right">L: {item.length?.toLocaleString()}</td>
                              <td className="px-2 py-1 text-right font-bold">{item.qty || '-'}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>

                  <div className="space-y-4">
                    <Card title="측면덮개">
                      <div className="text-sm">
                        <p>규격: {bomData.cases?.sideCover?.spec}</p>
                        <p className="font-bold text-lg">{bomData.cases?.sideCover?.qty}개</p>
                      </div>
                    </Card>
                    <Card title="상부덮개">
                      <div className="text-sm">
                        <p>규격: 1219-389</p>
                        <p className="font-bold text-lg">{bomData.cases?.topCover?.qty || 0}개</p>
                      </div>
                    </Card>
                    <Card title="연기차단재 (W80)">
                      <div className="text-sm">
                        <p>전면부, 린텔부 양쪽에 설치</p>
                        <p className="mt-2">L: {bomData.cases?.smokeBarrier?.length?.toLocaleString()} × <span className="font-bold">{bomData.cases?.smokeBarrier?.qty}개</span></p>
                      </div>
                    </Card>
                  </div>
                </div>
              </div>

              {/* 3-3. 하단마감재 */}
              <div className="space-y-4 pt-4 border-t">
                <div className="flex items-center gap-2">
                  <span className="font-bold">3-3. 하단마감재</span>
                  <span className="text-sm text-gray-500">- 하단마감재(EGI 1.55T) + 하단보강빔바(EGI 1.55T) + 하단 무게평철(50-12T)</span>
                </div>

                <div className="overflow-x-auto border rounded-lg">
                  <table className="w-full text-sm">
                    <thead className="bg-pink-100">
                      <tr>
                        <th className="px-3 py-2 text-left">구성품</th>
                        <th className="px-3 py-2 text-center">길이 (mm)</th>
                        <th className="px-3 py-2 text-center">수량</th>
                        <th className="px-3 py-2 text-left">구성품</th>
                        <th className="px-3 py-2 text-center">길이 (mm)</th>
                        <th className="px-3 py-2 text-center">수량</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      <tr className="bg-pink-50">
                        <td rowSpan="2" className="px-3 py-2 font-medium border-r">하단마감재<br />(50-40)</td>
                        <td className="px-3 py-2 text-center border-r">L: 4,000</td>
                        <td className="px-3 py-2 text-center font-bold border-r">{bomData.bottomFinish?.items?.[0]?.lengths?.[0]?.qty || 11}</td>
                        <td rowSpan="2" className="px-3 py-2 font-medium border-r">하단보강빔바<br />(80-17)</td>
                        <td className="px-3 py-2 text-center border-r">L: 4,000</td>
                        <td className="px-3 py-2 text-center font-bold">{bomData.bottomFinish?.items?.[1]?.lengths?.[0]?.qty || 28}</td>
                      </tr>
                      <tr className="bg-pink-50">
                        <td className="px-3 py-2 text-center border-r">L: 3,000</td>
                        <td className="px-3 py-2 text-center font-bold border-r">{bomData.bottomFinish?.items?.[0]?.lengths?.[1]?.qty || 8}</td>
                        <td className="px-3 py-2 text-center border-r">L: 3,000</td>
                        <td className="px-3 py-2 text-center font-bold">{bomData.bottomFinish?.items?.[1]?.lengths?.[1]?.qty || 12}</td>
                      </tr>
                      <tr className="bg-pink-50">
                        <td className="px-3 py-2 font-medium border-r">하단보강철</td>
                        <td className="px-3 py-2 text-center border-r">L: 4,000</td>
                        <td className="px-3 py-2 text-center font-bold border-r">{bomData.bottomFinish?.items?.[2]?.lengths?.[0]?.qty || 13}</td>
                        <td className="px-3 py-2 font-medium border-r">하단 부재횡철<br />(50-12T)</td>
                        <td className="px-3 py-2 text-center border-r">L: 2,000</td>
                        <td className="px-3 py-2 text-center font-bold">{bomData.bottomFinish?.items?.[3]?.lengths?.[0]?.qty || 67}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 하단 버튼 - 고정 */}
        <div className="flex gap-2 p-4 border-t bg-gray-50" style={{ flexShrink: 0 }}>
          <Button variant="outline" onClick={onClose}>
            취소
          </Button>
          <Button variant="outline" onClick={onPreview}>
            <FileText className="w-4 h-4" /> 생산지시서 미리보기
          </Button>
          <Button
            variant="primary"
            className="flex-1"
            onClick={onConfirm}
          >
            <Factory className="w-4 h-4" /> 생산지시 확정 ({previewWorkOrders.length}건)
          </Button>
        </div>
      </div>
    </div>
  );
};

// ============ 생산지시 생성 페이지 (전체 페이지 형태 - 섹션 기반) ============
const ProductionOrderCreatePage = ({ order, onBack, onConfirm, onNavigate, inventory = [] }) => {
  const [priority, setPriority] = useState('일반');
  const [note, setNote] = useState('');
  // ★ 생산지시 완료 확인 다이얼로그 상태
  const [showCompleteDialog, setShowCompleteDialog] = useState(false);
  const [completeInfo, setCompleteInfo] = useState({ workOrders: [] });

  // ★ 생산지시 확정 핸들러 (다이얼로그 표시)
  const handleConfirm = () => {
    // 상위 컴포넌트에 확정 요청
    onConfirm?.(order);
    // 다이얼로그 표시
    setCompleteInfo({ workOrders: previewWorkOrders, itemCount: items.length });
    setShowCompleteDialog(true);
  };

  // ★ 공정관리 연동: classifyItemToProcess를 사용하여 품목을 공정별로 자동 분류
  const classifyItem = (item) => {
    const result = classifyItemToProcess(item);
    return result.processName || '미분류';
  };

  const items = order?.items || [];

  // ★ 공정별 품목 그룹핑 (공정관리 규칙 기반)
  const itemsByProcess = items.reduce((acc, item) => {
    const processName = classifyItem(item);
    if (!acc[processName]) {
      acc[processName] = [];
    }
    acc[processName].push(item);
    return acc;
  }, {});

  // ★ 공정별 작업지시 생성 프리뷰 (공정관리 기준)
  const processWorkflows = {
    '스크린': { steps: ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'], color: 'blue' },
    '슬랫': { steps: ['코일절단', '중간검사', '미미작업', '포장'], color: 'green' },
    '절곡': { steps: ['절단', '절곡', '중간검사', '포장'], color: 'orange' },
    '미분류': { steps: ['작업준비', '가공', '검사', '포장'], color: 'gray' },
  };

  const previewWorkOrders = [];
  const dateCode = new Date().toISOString().slice(2, 10).replace(/-/g, '');
  let seqNum = 1;

  // ★ 분류된 공정별로 작업지시 생성 (동적 생성)
  Object.entries(itemsByProcess).forEach(([processName, processItems]) => {
    if (processItems.length === 0) return;

    const workflow = processWorkflows[processName] || processWorkflows['미분류'];
    previewWorkOrders.push({
      processType: processName,
      processId: classifyItemToProcess(processItems[0]).processId,
      workOrderNo: `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`,
      steps: workflow.steps,
      color: workflow.color,
      itemCount: processItems.length,
      totalQty: processItems.reduce((sum, item) => sum + (item.qty || 1), 0),
      items: processItems, // ★ 해당 공정의 품목 목록 포함
    });
  });

  // ★ 절곡 공정은 모든 품목에 공통 적용 (가이드레일, 케이스 등)
  if (!itemsByProcess['절곡'] && items.length > 0) {
    previewWorkOrders.push({
      processType: '절곡',
      processId: 'P-002',
      workOrderNo: `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`,
      steps: processWorkflows['절곡'].steps,
      color: 'orange',
      itemCount: items.length,
      totalQty: items.length,
      items: items, // 전체 품목 대상
      note: '공통 절곡 부품 제작',
    });
  }

  // 레거시 호환을 위한 카테고리 체크
  const hasScreen = !!itemsByProcess['스크린'];
  const hasSlat = !!itemsByProcess['슬랫'];

  // 레거시 inferCategory 함수 (자재 요구량 계산용)
  const inferCategory = (item) => {
    const processName = classifyItem(item);
    if (processName === '슬랫') return '슬랫';
    if (processName === '절곡') return '철재';
    return '스크린';
  };

  const materialRequirements = [
    { code: 'SCR-MAT-001', name: '스크린 원단', unit: '㎡', required: hasScreen ? items.filter(i => inferCategory(i) === '스크린').length * 15 : 0, stock: 500 },
    { code: 'SCR-MAT-002', name: '앤드락', unit: 'EA', required: hasScreen ? items.filter(i => inferCategory(i) === '스크린').length * 2 : 0, stock: 800 },
    { code: 'BND-MAT-001', name: '철판', unit: 'KG', required: items.length * 30, stock: 2000 },
    { code: 'BND-MAT-002', name: '가이드레일', unit: 'M', required: items.length * 6, stock: 300 },
    { code: 'BND-MAT-003', name: '케이스', unit: 'EA', required: items.length, stock: 100 },
  ].filter(m => m.required > 0);

  const materialsWithStock = materialRequirements.map(m => {
    const inventoryItem = inventory.find(i => i.materialCode === m.code);
    return { ...m, stock: inventoryItem?.stock ?? m.stock, isShort: (inventoryItem?.stock ?? m.stock) < m.required };
  });

  const screenItems = order?.items?.map((item, idx) => {
    const spec = item.productionSpec || {};
    const openW = spec.openWidth || parseInt(item.spec?.split('×')[0]) || item.openWidth || 0;
    const openH = spec.openHeight || parseInt(item.spec?.split('×')[1]) || item.openHeight || 0;
    return {
      seq: String(idx + 1).padStart(2, '0'), type: spec.type || '와이어',
      drawingNo: spec.drawingNo || `${item.floor || ''} ${item.location || ''}`.trim() || `품목 ${idx + 1}`,
      openWidth: openW, openHeight: openH, prodWidth: openW + 140, prodHeight: Math.max(openH + 400, 2950),
      guideRailType: spec.guideRailType || '백면형', guideRailSpec: spec.guideRailSpec || '120-70',
      shaft: openW > 6000 ? 5 : 4, capacity: openW > 6000 ? 300 : 160, finish: spec.finish || 'SUS마감',
      productName: item.productName || '', qty: item.qty || 1,
    };
  }) || [];

  const motorSpec = {
    motors380V: [
      { model: 'KD-150K', qty: screenItems.filter(i => i.capacity <= 160).length },
      { model: 'KD-300K', qty: screenItems.filter(i => i.capacity > 160 && i.capacity <= 300).length },
    ],
    brackets: [
      { spec: '380-180 [2-4"]', qty: screenItems.filter(i => i.shaft === 4).length },
      { spec: '380-180 [2-5"]', qty: screenItems.filter(i => i.shaft === 5).length },
    ],
  };

  const bomData = {
    guideRails: {
      items: [
        { type: '백면형', spec: '120-70', code: 'KSE01/KWE01', lengths: [{ length: 3000, qty: screenItems.length * 2 }] },
      ]
    },
    cases: { mainSpec: '500-330', items: [{ length: 4000, qty: Math.ceil(screenItems.length * 0.6) }], sideCover: { spec: '500-355', qty: screenItems.length * 2 } },
    bottomFinish: { items: [{ name: '하단마감재', spec: '50-40', lengths: [{ length: 4000, qty: screenItems.length }] }] },
  };

  const hasShortage = materialsWithStock.some(m => m.isShort);

  if (!order) return <div className="p-8 text-center"><p className="text-gray-500">수주 정보를 찾을 수 없습니다.</p><Button variant="outline" className="mt-4" onClick={onBack}><ArrowLeft className="w-4 h-4" /> 뒤로가기</Button></div>;

  return (
    <div className="space-y-6">
      {/* 헤더 영역 - 타이틀 위, 버튼 아래 */}
      <div className="space-y-3">
        {/* 타이틀 영역 */}
        <div className="flex items-center gap-4">
          <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
            <Factory className="w-6 h-6 text-blue-500" />
            생산지시 생성
          </h1>
          <span className="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm font-medium">{previewWorkOrders.length}개 작업지시 생성 예정</span>
          {hasShortage && <span className="px-3 py-1 bg-red-100 text-red-700 rounded-full text-sm flex items-center gap-1"><AlertCircle className="w-3 h-3" />자재 부족</span>}
        </div>
        {/* 버튼 영역 */}
        <div className="flex items-center justify-end gap-2">
          <Button variant="outline" onClick={onBack}>
            <ArrowLeft className="w-4 h-4" /> 취소
          </Button>
          <Button variant="primary" onClick={handleConfirm}>
            <Factory className="w-4 h-4" /> 생산지시 확정
          </Button>
        </div>
      </div>

      {/* 수주 정보 섹션 */}
      <Card title="수주 정보">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <div><span className="text-xs text-gray-500">수주번호</span><p className="font-medium">{order.orderNo}</p></div>
          <div><span className="text-xs text-gray-500">거래처</span><p className="font-medium">{order.customerName}</p></div>
          <div><span className="text-xs text-gray-500">현장명</span><p className="font-medium">{order.siteName}</p></div>
          <div><span className="text-xs text-gray-500">납기일</span><p className="font-medium text-red-600">{order.dueDate}</p></div>
          <div><span className="text-xs text-gray-500">품목 수</span><p className="font-medium">{items.length}건</p></div>
          <div><span className="text-xs text-gray-500">총수량</span><p className="font-medium">{items.reduce((sum, i) => sum + (i.qty || 1), 0)}EA</p></div>
          <div><span className="text-xs text-gray-500">신용등급</span><p className="font-medium"><CreditGradeBadge grade={order.creditGrade} /></p></div>
          <div><span className="text-xs text-gray-500">상태</span><p className="font-medium">{order.status}</p></div>
        </div>
      </Card>

      {/* 생산지시 옵션 섹션 - 우선순위 매핑 테이블 포함 */}
      <Card title="생산지시 옵션">
        <div className="space-y-6">
          {/* 우선순위 선택 + 매핑 테이블 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">우선순위 (영업)</label>
            <div className="flex gap-2 mb-4">
              {['긴급', '높음', '일반', '낮음'].map(p => (
                <button key={p} onClick={() => setPriority(p)}
                  className={`px-4 py-2 rounded-lg border text-sm font-medium ${priority === p ? (p === '긴급' ? 'bg-red-100 border-red-300 text-red-700' : p === '높음' ? 'bg-orange-100 border-orange-300 text-orange-700' : p === '일반' ? 'bg-blue-100 border-blue-300 text-blue-700' : 'bg-gray-100 border-gray-300 text-gray-700') : 'bg-white border-gray-200 text-gray-600 hover:bg-gray-50'}`}>{p}</button>
              ))}
            </div>

            {/* 우선순위 매핑 테이블 */}
            <div className="bg-gray-50 rounded-lg p-4 border">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b">
                    <th className="text-left py-2 px-3 text-gray-600 font-medium">생산지시 (영업)</th>
                    <th className="text-left py-2 px-3 text-gray-600 font-medium">작업지시 기본값 (공장)</th>
                    <th className="text-left py-2 px-3 text-gray-600 font-medium">비고 (현장의 여유 공간)</th>
                  </tr>
                </thead>
                <tbody>
                  <tr className={`border-b ${priority === '긴급' ? 'bg-red-50' : ''}`}>
                    <td className="py-2 px-3 font-medium text-red-700">긴급</td>
                    <td className="py-2 px-3"><span className="px-2 py-0.5 bg-red-100 text-red-700 rounded text-xs font-medium">1순위</span></td>
                    <td className="py-2 px-3 text-gray-600">무조건 제일 먼저</td>
                  </tr>
                  <tr className={`border-b ${priority === '높음' ? 'bg-orange-50' : ''}`}>
                    <td className="py-2 px-3 font-medium text-orange-700">높음</td>
                    <td className="py-2 px-3"><span className="px-2 py-0.5 bg-orange-100 text-orange-700 rounded text-xs font-medium">3순위</span></td>
                    <td className="py-2 px-3 text-gray-600">(2순위는 현장에서 '새치기' 할 때 쓰도록 비워둠)</td>
                  </tr>
                  <tr className={`border-b ${priority === '일반' ? 'bg-blue-50' : ''}`}>
                    <td className="py-2 px-3 font-medium text-blue-700">일반</td>
                    <td className="py-2 px-3"><span className="px-2 py-0.5 bg-blue-100 text-blue-700 rounded text-xs font-medium">5순위</span></td>
                    <td className="py-2 px-3 text-gray-600">(4순위 비워둠)</td>
                  </tr>
                  <tr className={`${priority === '낮음' ? 'bg-gray-100' : ''}`}>
                    <td className="py-2 px-3 font-medium text-gray-700">낮음</td>
                    <td className="py-2 px-3"><span className="px-2 py-0.5 bg-gray-200 text-gray-700 rounded text-xs font-medium">9순위</span></td>
                    <td className="py-2 px-3 text-gray-600">뒤로 쪽 밀어둠</td>
                  </tr>
                </tbody>
              </table>

              {/* 선택된 우선순위 결과 표시 */}
              <div className="mt-4 pt-4 border-t flex items-center gap-4">
                <span className="text-sm text-gray-600">선택된 설정:</span>
                <span className={`px-3 py-1 rounded-full text-sm font-medium ${priority === '긴급' ? 'bg-red-100 text-red-700' : priority === '높음' ? 'bg-orange-100 text-orange-700' : priority === '일반' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-700'}`}>
                  생산지시: {priority}
                </span>
                <span className="text-gray-400">→</span>
                <span className={`px-3 py-1 rounded-full text-sm font-medium ${priority === '긴급' ? 'bg-red-100 text-red-700' : priority === '높음' ? 'bg-orange-100 text-orange-700' : priority === '일반' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-700'}`}>
                  작업지시: {priority === '긴급' ? '1순위' : priority === '높음' ? '3순위' : priority === '일반' ? '5순위' : '9순위'}
                </span>
              </div>
            </div>
          </div>

          {/* 메모 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">메모</label>
            <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={2} className="w-full px-3 py-2 border rounded-lg" placeholder="생산지시 관련 특이사항..." />
          </div>
        </div>
      </Card>

      {/* 생성될 작업지시 섹션 */}
      <Card title={`생성될 작업지시 (${previewWorkOrders.length}건)`}>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {previewWorkOrders.map((wo, idx) => (
            <div key={idx} className="border rounded-lg p-4 bg-gray-50">
              <div className="flex items-center justify-between mb-3">
                <span className={`px-2 py-1 rounded text-xs font-medium ${wo.processType === '스크린' ? 'bg-blue-100 text-blue-700' : wo.processType === '슬랫' ? 'bg-purple-100 text-purple-700' : 'bg-orange-100 text-orange-700'}`}>{wo.processType}</span>
                <span className="text-sm font-mono text-gray-600">{wo.workOrderNo}</span>
              </div>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between"><span className="text-gray-500">품목 수</span><span className="font-medium">{wo.itemCount}건</span></div>
                <div className="flex justify-between"><span className="text-gray-500">총 수량</span><span className="font-medium">{wo.totalQty}EA</span></div>
              </div>
              <div className="mt-3 pt-3 border-t">
                <p className="text-xs text-gray-500 mb-1">공정 순서</p>
                <div className="flex flex-wrap gap-1">{wo.steps.map((step, i) => <span key={i} className="px-2 py-0.5 bg-white rounded text-xs border">{i + 1}. {step}</span>)}</div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* 자재 소요량 섹션 */}
      <Card title="자재 소요량 및 재고 현황">
        {hasShortage && <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2 text-red-700"><AlertCircle className="w-5 h-5" /><span className="text-sm">일부 자재의 재고가 부족합니다. 구매 요청이 필요합니다.</span></div>}
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-50"><tr><th className="px-4 py-3 text-left">자재코드</th><th className="px-4 py-3 text-left">자재명</th><th className="px-4 py-3 text-center">단위</th><th className="px-4 py-3 text-right">소요량</th><th className="px-4 py-3 text-right">현재고</th><th className="px-4 py-3 text-center">상태</th></tr></thead>
            <tbody className="divide-y">
              {materialsWithStock.map((m, idx) => (
                <tr key={idx} className={m.isShort ? 'bg-red-50' : ''}>
                  <td className="px-4 py-3 font-mono text-gray-600">{m.code}</td>
                  <td className="px-4 py-3 font-medium">{m.name}</td>
                  <td className="px-4 py-3 text-center">{m.unit}</td>
                  <td className="px-4 py-3 text-right font-medium">{m.required.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right">{m.stock.toLocaleString()}</td>
                  <td className="px-4 py-3 text-center">{m.isShort ? <span className="px-2 py-1 bg-red-100 text-red-700 rounded text-xs">부족</span> : <span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs">충분</span>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      {/* 스크린 품목 상세 섹션 */}
      {screenItems.length > 0 && (
        <Card title={`스크린 품목 상세 (${screenItems.length}건)`}>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-50"><tr><th className="px-3 py-2 text-center">No</th><th className="px-3 py-2 text-left">품목명</th><th className="px-3 py-2 text-left">도번/위치</th><th className="px-3 py-2 text-center">개구폭</th><th className="px-3 py-2 text-center">개구높이</th><th className="px-3 py-2 text-center">제작폭</th><th className="px-3 py-2 text-center">제작높이</th><th className="px-3 py-2 text-center">가이드레일</th><th className="px-3 py-2 text-center">샤프트</th><th className="px-3 py-2 text-center">용량</th><th className="px-3 py-2 text-center">마감</th><th className="px-3 py-2 text-center">수량</th></tr></thead>
              <tbody className="divide-y">
                {screenItems.map((item, idx) => (
                  <tr key={idx} className="hover:bg-gray-50">
                    <td className="px-3 py-2 text-center font-mono">{item.seq}</td>
                    <td className="px-3 py-2 font-medium">{item.productName || '국민방화스크린셔터'}</td>
                    <td className="px-3 py-2 text-gray-600">{item.drawingNo}</td>
                    <td className="px-3 py-2 text-center">{item.openWidth.toLocaleString()}</td>
                    <td className="px-3 py-2 text-center">{item.openHeight.toLocaleString()}</td>
                    <td className="px-3 py-2 text-center font-medium text-blue-600">{item.prodWidth.toLocaleString()}</td>
                    <td className="px-3 py-2 text-center font-medium text-blue-600">{item.prodHeight.toLocaleString()}</td>
                    <td className="px-3 py-2 text-center">{item.guideRailType} {item.guideRailSpec}</td>
                    <td className="px-3 py-2 text-center">{item.shaft}"</td>
                    <td className="px-3 py-2 text-center">{item.capacity}kg</td>
                    <td className="px-3 py-2 text-center">{item.finish}</td>
                    <td className="px-3 py-2 text-center font-medium">{item.qty}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {/* 모터/전장품 섹션 - 수량 0보다 큰 항목만 표시 */}
      {(motorSpec.motors380V.some(m => m.qty > 0) || motorSpec.brackets.some(b => b.qty > 0)) && (
        <Card title="모터/전장품 사양">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {motorSpec.motors380V.filter(m => m.qty > 0).length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-3">모터 사양 (380V)</h4>
                <div className="space-y-2">{motorSpec.motors380V.filter(m => m.qty > 0).map((m, idx) => <div key={idx} className="flex justify-between items-center p-2 bg-gray-50 rounded"><span>{m.model}</span><span className="font-medium">{m.qty}대</span></div>)}</div>
              </div>
            )}
            {motorSpec.brackets.filter(b => b.qty > 0).length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-3">모터 브라켓</h4>
                <div className="space-y-2">{motorSpec.brackets.filter(b => b.qty > 0).map((b, idx) => <div key={idx} className="flex justify-between items-center p-2 bg-gray-50 rounded"><span>{b.spec}</span><span className="font-medium">{b.qty}개</span></div>)}</div>
              </div>
            )}
          </div>
        </Card>
      )}

      {/* 절곡물 BOM 섹션 */}
      <Card title="절곡물 BOM">
        <div className="space-y-6">
          {/* 가이드레일 */}
          <div>
            <h4 className="text-sm font-medium text-gray-700 mb-3">가이드레일</h4>
            <table className="w-full text-sm">
              <thead className="bg-gray-50"><tr><th className="px-4 py-2 text-left">형태</th><th className="px-4 py-2 text-left">규격</th><th className="px-4 py-2 text-left">코드</th><th className="px-4 py-2 text-center">길이</th><th className="px-4 py-2 text-center">수량</th></tr></thead>
              <tbody className="divide-y">{bomData.guideRails.items.map((item, idx) => <tr key={idx}><td className="px-4 py-2 font-medium">{item.type}</td><td className="px-4 py-2">{item.spec}</td><td className="px-4 py-2 font-mono text-gray-600">{item.code}</td><td className="px-4 py-2 text-center">{item.lengths[0]?.length}</td><td className="px-4 py-2 text-center font-medium">{item.lengths[0]?.qty}</td></tr>)}</tbody>
            </table>
          </div>
          {/* 케이스 */}
          <div>
            <h4 className="text-sm font-medium text-gray-700 mb-3">케이스(셔터박스) - 메인 규격: {bomData.cases.mainSpec}</h4>
            <table className="w-full text-sm">
              <thead className="bg-gray-50"><tr><th className="px-4 py-2 text-left">품목</th><th className="px-4 py-2 text-center">길이</th><th className="px-4 py-2 text-center">수량</th></tr></thead>
              <tbody className="divide-y">
                {bomData.cases.items.map((item, idx) => <tr key={idx}><td className="px-4 py-2">케이스 본체</td><td className="px-4 py-2 text-center">L: {item.length}</td><td className="px-4 py-2 text-center font-medium">{item.qty}</td></tr>)}
                <tr><td className="px-4 py-2">측면 덮개</td><td className="px-4 py-2 text-center">{bomData.cases.sideCover.spec}</td><td className="px-4 py-2 text-center font-medium">{bomData.cases.sideCover.qty}</td></tr>
              </tbody>
            </table>
          </div>
          {/* 하단 마감재 */}
          <div>
            <h4 className="text-sm font-medium text-gray-700 mb-3">하단 마감재</h4>
            <table className="w-full text-sm">
              <thead className="bg-gray-50"><tr><th className="px-4 py-2 text-left">품목</th><th className="px-4 py-2 text-left">규격</th><th className="px-4 py-2 text-center">길이</th><th className="px-4 py-2 text-center">수량</th></tr></thead>
              <tbody className="divide-y">{bomData.bottomFinish.items.map((item, idx) => <tr key={idx}><td className="px-4 py-2 font-medium">{item.name}</td><td className="px-4 py-2">{item.spec}</td><td className="px-4 py-2 text-center">L: {item.lengths[0]?.length}</td><td className="px-4 py-2 text-center font-medium">{item.lengths[0]?.qty}</td></tr>)}</tbody>
            </table>
          </div>
        </div>
      </Card>

      {/* 하단 확정 버튼 영역 */}
      <div className="bg-white border rounded-lg px-6 py-4 flex items-center justify-between">
        <div className="text-sm text-gray-500">
          {priority !== '일반' && <span className={`px-2 py-1 rounded mr-2 ${priority === '긴급' ? 'bg-red-100 text-red-700' : priority === '높음' ? 'bg-orange-100 text-orange-700' : 'bg-gray-100 text-gray-700'}`}>우선순위: {priority}</span>}
          {note && <span>메모: {note.substring(0, 50)}{note.length > 50 ? '...' : ''}</span>}
        </div>
        <div className="flex gap-3">
          <Button variant="outline" onClick={onBack}><ArrowLeft className="w-4 h-4" /> 수주상세로</Button>
          <Button variant="primary" onClick={handleConfirm}><Factory className="w-4 h-4" /> 생산지시 확정 ({previewWorkOrders.length}건)</Button>
        </div>
      </div>

      {/* ★ 생산지시 완료 확인 다이얼로그 */}
      {showCompleteDialog && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[100]">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 overflow-hidden">
            {/* 헤더 */}
            <div className="bg-green-50 px-6 py-4 border-b border-green-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-green-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">생산지시 완료</h3>
                  <p className="text-sm text-gray-600">작업지시가 성공적으로 생성되었습니다.</p>
                </div>
              </div>
            </div>

            {/* 내용 */}
            <div className="px-6 py-4">
              <div className="bg-gray-50 rounded-lg p-4 mb-4">
                <p className="text-sm font-medium text-gray-700 mb-2">
                  생성된 작업지시 ({completeInfo.workOrders?.length || 0}건)
                </p>
                <div className="space-y-2">
                  {completeInfo.workOrders?.map((wo, idx) => (
                    <div key={idx} className="flex items-center gap-2 text-sm">
                      <span className={`w-2 h-2 rounded-full ${wo.processType === '스크린' ? 'bg-blue-500' :
                          wo.processType === '슬랫' ? 'bg-green-500' :
                            wo.processType === '절곡' ? 'bg-orange-500' : 'bg-gray-500'
                        }`}></span>
                      <span className="text-gray-600">{wo.processType}:</span>
                      <span className="font-mono font-medium text-gray-900">{wo.workOrderNo}</span>
                    </div>
                  ))}
                </div>
              </div>

              {completeInfo.itemCount && (
                <p className="text-sm text-gray-500">
                  품목 수: <span className="font-medium">{completeInfo.itemCount}건</span>
                </p>
              )}
            </div>

            {/* 버튼 */}
            <div className="px-6 py-4 bg-gray-50 border-t flex justify-end gap-2">
              <Button
                variant="outline"
                onClick={() => {
                  setShowCompleteDialog(false);
                  onBack?.();
                }}
              >
                수주 상세로
              </Button>
              <Button
                variant="primary"
                onClick={() => {
                  setShowCompleteDialog(false);
                  onNavigate?.('work-order-list');
                }}
              >
                <ClipboardList className="w-4 h-4" />
                작업지시 목록 보기
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============ 생산지시서(발주서 양식) 출력 모달 ============
const ProductionOrderSheet = ({ workOrder, order, orderData, onClose, title = '생산지시서' }) => {
  const printRef = React.useRef(null);

  // 수주/작업지시 데이터에서 발주서 형식으로 변환
  const convertToSheetData = () => {
    // 외부에서 orderData가 제공되면 그대로 사용
    if (orderData) return orderData;

    // order(수주) 데이터가 있으면 변환
    const sourceOrder = order || workOrder;
    if (!sourceOrder) return sampleDetailedOrderData;

    // 스크린 아이템 변환
    const screenItems = (sourceOrder.items || []).map((item, idx) => {
      const spec = item.productionSpec || {};
      // spec 문자열에서 크기 파싱 (예: "7660×2550")
      const [openW, openH] = (item.spec || '0×0').split('×').map(s => parseInt(s) || 0);

      return {
        seq: idx + 1,
        type: spec.type || '와이어',
        drawingNo: spec.drawingNo || `${item.floor} ${item.location}`,
        openWidth: spec.openWidth || openW,
        openHeight: spec.openHeight || openH,
        prodWidth: spec.prodWidth || openW + 140,
        prodHeight: spec.prodHeight || 2950,
        guideRailType: spec.guideRailType || '백면형',
        guideRailSpec: spec.guideRailSpec || '120-70',
        shaft: spec.shaft || (openW > 6000 ? 5 : 4),
        caseSpec: spec.caseSpec || '500-330',
        motorBracket: spec.motorBracket || '380-180',
        capacity: spec.capacity || (openW > 6000 ? 300 : 160),
        finish: spec.finish || 'SUS마감',
      };
    });

    // 모터 스펙 (있으면 사용, 없으면 기본값)
    const motorSpec = sourceOrder.motorSpec || {
      motors220V: [
        { model: 'KD-150K', qty: 0 },
        { model: 'KD-300K', qty: 0 },
        { model: 'KD-400K', qty: 0 },
      ],
      motors380V: [
        { model: 'KD-150K', qty: screenItems.filter(i => i.capacity <= 160).length },
        { model: 'KD-300K', qty: screenItems.filter(i => i.capacity > 160).length },
        { model: 'KD-400K', qty: 0 },
      ],
      brackets: [
        { spec: '380-180 [2-4"]', qty: 0 },
        { spec: '380-180 [2-5"]', qty: screenItems.length },
      ],
      heatSinks: [
        { spec: '40-60', qty: screenItems.length * 2 },
        { spec: 'L-380', qty: 0 },
      ],
      controllers: [
        { type: '매입형', qty: 0 },
        { type: '노출형', qty: 0 },
        { type: '핫라스', qty: 0 },
      ],
    };

    // BOM 데이터 (있으면 사용, 없으면 자동 계산)
    const bomData = sourceOrder.bomData || {
      guideRails: {
        description: '가이드레일 - EGI 1.55T + 마감재 EGI 1.15T + 별도마감재 SUS 1.15T',
        items: [
          {
            type: '백면형', spec: '120-70', code: 'KSE01/KWE01', lengths: [
              { length: 3000, qty: screenItems.length * 2 },
            ]
          },
          {
            type: '측면형', spec: '120-120', code: 'KSS01', lengths: [
              { length: 4300, qty: 0 },
              { length: 4000, qty: 0 },
              { length: 3500, qty: 0 },
              { length: 3000, qty: 0 },
            ]
          },
          {
            type: '하부BASE', spec: '130-80', code: '', lengths: [
              { length: 0, qty: screenItems.length * 2 },
            ]
          },
        ],
        smokeBarrier: {
          spec: 'W80',
          lengths: [{ length: 2950, qty: screenItems.length * 2 }],
        },
      },
      cases: {
        description: '케이스(셔터박스) - EGI 1.55T',
        mainSpec: '500-330 (150,300,400/K용)',
        items: [
          { length: 4000, qty: Math.ceil(screenItems.length / 2) },
          { length: 3500, qty: Math.floor(screenItems.length / 2) },
        ],
        sideCover: { spec: '500-355', qty: screenItems.length * 2 },
        topCover: { qty: 0 },
        extension: { spec: '1219+무게', qty: screenItems.length * 3 },
        smokeBarrier: { spec: 'W80', length: 3000, qty: screenItems.length * 2 },
      },
      bottomFinish: {
        description: '하단마감재 - 마단마감재(EGI 1.55T) + 하단보강별바(EGI 1.55T) + 하단 보강횡철(EGI 1.15T) + 하단 부재횡철(50-12T)',
        items: [
          {
            name: '하단마감재', spec: '50-40', lengths: [
              { length: 4000, qty: screenItems.length },
              { length: 3000, qty: 0 },
            ]
          },
          {
            name: '하단보강빔바', spec: '80-17', lengths: [
              { length: 4000, qty: screenItems.length * 2 },
              { length: 3000, qty: 0 },
            ]
          },
          {
            name: '하단보강철', spec: '', lengths: [
              { length: 4000, qty: screenItems.length },
              { length: 3000, qty: 0 },
            ]
          },
          {
            name: '하단부재횡철', spec: '50-12T', lengths: [
              { length: 2000, qty: screenItems.length * 4 },
            ]
          },
        ],
      },
    };

    return {
      orderInfo: {
        lotNo: sourceOrder.orderNo || sourceOrder.workOrderNo || 'N/A',
        productName: '국민방화스크린셔터스테',
        productType: 'KWE01',
        certNo: 'FDS-OTS23-0117-4',
        orderDate: sourceOrder.orderDate || new Date().toISOString().split('T')[0],
        siteName: sourceOrder.siteName || '',
        customerName: sourceOrder.customerName || '',
        dueDate: sourceOrder.dueDate || '',
        receiverManager: sourceOrder.receiverName || sourceOrder.manager || '',
        receiverContact: sourceOrder.receiverPhone || sourceOrder.contact || '',
        orderManager: sourceOrder.manager || '',
        deliveryDate: sourceOrder.dueDate || '',
        totalQty: screenItems.length,
        deliveryMethod: sourceOrder.deliveryMethod || '상차',
        deliveryAddress: sourceOrder.deliveryAddress || '',
        // 결재라인 정보
        approval: sourceOrder.approval || {
          drafter: sourceOrder.createdBy ? {
            name: sourceOrder.createdBy.replace(/^(판매팀|생산팀|전진팀)\s*/, ''),
            date: sourceOrder.createdAt || sourceOrder.orderDate
          } : null,
          approver: sourceOrder.approvedBy ? {
            name: sourceOrder.approvedBy,
            date: sourceOrder.approvedAt
          } : null,
          cc: ['회계팀'], // 회계는 항상 참조
        },
      },
      screenItems,
      motorSpec,
      bomData,
    };
  };

  const data = convertToSheetData();

  const handlePrint = () => {
    window.print();
  };

  // PDF 다운로드 (브라우저 인쇄 기능 활용)
  const handleDownloadPDF = () => {
    // CSS로 인쇄 스타일 적용 후 브라우저 인쇄 다이얼로그에서 PDF 저장
    const printContent = printRef.current;
    if (!printContent) return;

    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <!DOCTYPE html>
      <html>
      <head>
        <title>생산지시서_${data.orderInfo.lotNo}</title>
        <style>
          * { margin: 0; padding: 0; box-sizing: border-box; }
          body { font-family: 'Malgun Gothic', Arial, sans-serif; font-size: 11px; }
          table { border-collapse: collapse; width: 100%; }
          th, td { border: 1px solid #333; padding: 4px 6px; }
          th { background-color: #fff3cd; }
          .header { display: flex; border: 2px solid #333; margin-bottom: 10px; }
          .logo { padding: 10px; font-weight: bold; color: #1a56db; font-size: 24px; }
          .title { font-size: 28px; font-weight: bold; text-align: center; padding: 20px; }
          .lot-no { font-family: monospace; color: #1a56db; font-weight: bold; }
          .red { color: #dc2626; font-weight: bold; }
          .green-bg { background-color: #dcfce7; }
          .red-bg { background-color: #fee2e2; }
          .blue-bg { background-color: #dbeafe; }
          .yellow-bg { background-color: #fef3c7; }
          .section-title { font-weight: bold; margin: 15px 0 5px 0; }
          .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0; border: 1px solid #666; margin-bottom: 10px; }
          .info-row { display: flex; border-bottom: 1px solid #666; }
          .info-label { background-color: #fffbeb; padding: 6px; width: 100px; border-right: 1px solid #666; }
          .info-value { padding: 6px; flex: 1; }
          @media print {
            body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
          }
        </style>
      </head>
      <body>
        ${printContent.innerHTML}
      </body>
      </html>
    `);
    printWindow.document.close();
    printWindow.focus();

    setTimeout(() => {
      printWindow.print();
      printWindow.close();
    }, 500);
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white w-full max-w-5xl rounded-xl flex flex-col" style={{ height: '700px' }}>
        {/* 컨트롤 바 (인쇄 시 숨김) - 고정 */}
        <div className="flex items-center justify-between p-4 border-b bg-gray-50 print:hidden" style={{ flexShrink: 0 }}>
          <div className="flex items-center gap-2">
            <FileText className="w-5 h-5 text-blue-600" />
            <h2 className="text-lg font-bold">{title}</h2>
            <span className="text-sm text-gray-500 font-mono">{data.orderInfo.lotNo}</span>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={handleDownloadPDF}>
              <Download className="w-4 h-4" /> PDF
            </Button>
            <Button variant="outline" onClick={handlePrint}>
              <Printer className="w-4 h-4" /> 인쇄
            </Button>
            <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
              ✕
            </button>
          </div>
        </div>

        {/* 발주서 본문 - 스크롤 */}
        <div ref={printRef} className="p-4 print:p-4" style={{ flex: 1, overflowY: 'auto', fontFamily: 'Arial, sans-serif' }}>
          <div className="space-y-4">

            {/* === 헤더 영역 === */}
            <div className="border-2 border-gray-800">
              {/* 상단 헤더 */}
              <div className="flex">
                {/* 회사 로고/정보 */}
                <div className="flex-1 p-3 border-r border-gray-800">
                  <div className="flex items-center gap-4">
                    <div className="text-2xl font-bold text-blue-700">KD</div>
                    <div>
                      <div className="font-bold">경동기업</div>
                      <div className="text-xs text-gray-600">
                        전화: 031-883-6130 | 팩스: 02-6911-6315 | 이메일: kd513@naver.com
                      </div>
                    </div>
                  </div>
                </div>
                {/* 발주서 타이틀 */}
                <div className="w-48 flex items-center justify-center border-r border-gray-800">
                  <h1 className="text-3xl font-bold">발 주 서</h1>
                </div>
                {/* 로트번호/결재라인 */}
                <div className="w-72 p-2">
                  <div className="flex border border-gray-600 text-xs">
                    <div className="bg-yellow-100 px-2 py-1 border-r border-gray-600 w-16 text-center font-medium">로트번호</div>
                    <div className="flex-1 px-2 py-1 font-mono font-bold text-blue-700">{data.orderInfo.lotNo}</div>
                  </div>
                  <div className="flex border border-t-0 border-gray-600 text-xs mt-0">
                    <div className="w-16 border-r border-gray-600"></div>
                    <div className="flex-1 flex">
                      <div className="flex-1 text-center border-r border-gray-600 py-1 bg-blue-50">작성</div>
                      <div className="flex-1 text-center border-r border-gray-600 py-1 bg-green-50">승인</div>
                      <div className="flex-1 text-center py-1 bg-gray-50">참조</div>
                    </div>
                  </div>
                  <div className="flex border border-t-0 border-gray-600 text-xs">
                    <div className="w-16 border-r border-gray-600 bg-gray-100 text-center py-2">결<br />재</div>
                    <div className="flex-1 flex">
                      <div className="flex-1 border-r border-gray-600 h-12 flex flex-col items-center justify-center bg-blue-50">
                        <span className="text-[10px] text-gray-500">판매/전진</span>
                        {data.orderInfo.approval?.drafter && (
                          <>
                            <span className="text-[10px] font-medium">{data.orderInfo.approval.drafter.name}</span>
                            <span className="text-[8px] text-gray-400">{data.orderInfo.approval.drafter.date}</span>
                          </>
                        )}
                      </div>
                      <div className="flex-1 border-r border-gray-600 h-12 flex flex-col items-center justify-center bg-green-50">
                        <span className="text-[10px] text-gray-500">생산관리</span>
                        {data.orderInfo.approval?.approver ? (
                          <>
                            <span className="text-[10px] font-medium">{data.orderInfo.approval.approver.name}</span>
                            <span className="text-[8px] text-gray-400">{data.orderInfo.approval.approver.date}</span>
                          </>
                        ) : (
                          <span className="text-[9px] text-orange-500">대기</span>
                        )}
                      </div>
                      <div className="flex-1 h-12 flex flex-col items-center justify-center bg-gray-50">
                        <span className="text-[10px] text-gray-500">회계</span>
                        <span className="text-[9px] text-gray-400">CC</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* 제품 정보 행 */}
              <div className="flex border-t border-gray-800 text-sm">
                <div className="flex items-center border-r border-gray-600">
                  <div className="bg-yellow-100 px-3 py-2 border-r border-gray-600 w-20">상품명</div>
                  <div className="px-3 py-2 w-48">{data.orderInfo.productName}</div>
                </div>
                <div className="flex items-center border-r border-gray-600">
                  <div className="bg-yellow-100 px-3 py-2 border-r border-gray-600 w-16">제품형</div>
                  <div className="px-3 py-2 w-20 font-mono">{data.orderInfo.productType}</div>
                </div>
                <div className="flex items-center flex-1">
                  <div className="bg-yellow-100 px-3 py-2 border-r border-gray-600 w-20">인정번호</div>
                  <div className="px-3 py-2 font-mono">{data.orderInfo.certNo}</div>
                </div>
              </div>
            </div>

            {/* === 신청 내용 === */}
            <div className="border border-gray-600">
              <div className="bg-blue-100 text-center py-1 border-b border-gray-600 font-medium text-sm">신 청 내 용</div>
              <div className="grid grid-cols-2 text-sm">
                {/* 좌측 */}
                <div className="border-r border-gray-600">
                  <div className="flex border-b border-gray-600">
                    <div className="bg-yellow-50 px-3 py-2 border-r border-gray-600 w-24">발 주 일</div>
                    <div className="px-3 py-2 flex-1">{data.orderInfo.orderDate}</div>
                    <div className="bg-yellow-50 px-3 py-2 border-l border-r border-gray-600 w-20">현 장 명</div>
                    <div className="px-3 py-2 flex-1 font-medium text-blue-700">{data.orderInfo.siteName}</div>
                  </div>
                  <div className="flex border-b border-gray-600">
                    <div className="bg-yellow-50 px-3 py-2 border-r border-gray-600 w-24">발 주 처</div>
                    <div className="px-3 py-2 flex-1">{data.orderInfo.customerName}</div>
                    <div className="bg-yellow-50 px-3 py-2 border-l border-r border-gray-600 w-20">납기요청일</div>
                    <div className="px-3 py-2 flex-1 text-red-600 font-medium">{data.orderInfo.dueDate}</div>
                  </div>
                  <div className="flex border-b border-gray-600">
                    <div className="bg-yellow-50 px-3 py-2 border-r border-gray-600 w-24">발주담당자</div>
                    <div className="px-3 py-2 flex-1">{data.orderInfo.orderManager}</div>
                    <div className="bg-yellow-50 px-3 py-2 border-l border-r border-gray-600 w-20">고 객</div>
                    <div className="px-3 py-2 flex-1">{data.orderInfo.deliveryDate}</div>
                  </div>
                  <div className="flex">
                    <div className="bg-yellow-50 px-3 py-2 border-r border-gray-600 w-24">담당자연락처</div>
                    <div className="px-3 py-2 flex-1">셔터총수량 <span className="font-bold">{data.orderInfo.totalQty}</span> 개소</div>
                    <div className="bg-yellow-50 px-3 py-2 border-l border-r border-gray-600 w-20">배 송 방 법</div>
                    <div className="px-3 py-2 flex-1">{data.orderInfo.deliveryMethod}</div>
                  </div>
                </div>
                {/* 우측 */}
                <div>
                  <div className="flex border-b border-gray-600">
                    <div className="bg-yellow-50 px-3 py-2 border-r border-gray-600 w-24">인수담당자</div>
                    <div className="px-3 py-2 flex-1">{data.orderInfo.receiverManager}</div>
                  </div>
                  <div className="flex border-b border-gray-600">
                    <div className="bg-yellow-50 px-3 py-2 border-r border-gray-600 w-24">인수자연락처</div>
                    <div className="px-3 py-2 flex-1">{data.orderInfo.receiverContact}</div>
                  </div>
                  <div className="flex">
                    <div className="bg-yellow-50 px-3 py-2 border-r border-gray-600 w-24">배송지주소</div>
                    <div className="px-3 py-2 flex-1 text-sm">{data.orderInfo.deliveryAddress}</div>
                  </div>
                </div>
              </div>
            </div>

            {/* 주의 문구 */}
            <div className="text-center text-sm text-red-600 py-2">
              아래와 같이 주문하오니 품질 및 납기일을 준수하여 주시기 바랍니다.
            </div>

            {/* === 1. 스크린 테이블 === */}
            <div>
              <div className="font-bold mb-2">1. 스크린</div>
              <div className="overflow-x-auto">
                <table className="w-full border-collapse text-xs">
                  <thead>
                    <tr className="bg-yellow-100">
                      <th rowSpan={2} className="border border-gray-600 px-2 py-1 w-12">일련<br />번호</th>
                      <th rowSpan={2} className="border border-gray-600 px-2 py-1 w-14">종류</th>
                      <th rowSpan={2} className="border border-gray-600 px-2 py-1 w-24">도면부호</th>
                      <th colSpan={2} className="border border-gray-600 px-2 py-1 bg-green-100">오픈사이즈(mm)</th>
                      <th colSpan={2} className="border border-gray-600 px-2 py-1 bg-red-100">제작사이즈(mm)</th>
                      <th rowSpan={2} className="border border-gray-600 px-2 py-1 w-20">가이드<br />레일유형</th>
                      <th rowSpan={2} className="border border-gray-600 px-2 py-1 w-14">샤프트<br />(인치)</th>
                      <th rowSpan={2} className="border border-gray-600 px-2 py-1 w-16">케이스<br />(규격)</th>
                      <th rowSpan={2} className="border border-gray-600 px-2 py-1 w-16">모터<br />브라켓</th>
                      <th rowSpan={2} className="border border-gray-600 px-2 py-1 w-14">용량<br />(KG)</th>
                      <th rowSpan={2} className="border border-gray-600 px-2 py-1 w-16">마감</th>
                    </tr>
                    <tr className="bg-yellow-100">
                      <th className="border border-gray-600 px-2 py-1 w-14 bg-green-100">가로</th>
                      <th className="border border-gray-600 px-2 py-1 w-14 bg-green-100">세로</th>
                      <th className="border border-gray-600 px-2 py-1 w-14 bg-red-100">가로</th>
                      <th className="border border-gray-600 px-2 py-1 w-14 bg-red-100">세로</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.screenItems.map((item, idx) => (
                      <tr key={idx} className={idx % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                        <td className="border border-gray-600 px-2 py-1 text-center">{String(item.seq).padStart(2, '0')}</td>
                        <td className="border border-gray-600 px-2 py-1 text-center">{item.type}</td>
                        <td className="border border-gray-600 px-2 py-1">{item.drawingNo}</td>
                        <td className="border border-gray-600 px-2 py-1 text-right bg-green-50">{item.openWidth.toLocaleString()}</td>
                        <td className="border border-gray-600 px-2 py-1 text-right bg-green-50">{item.openHeight.toLocaleString()}</td>
                        <td className="border border-gray-600 px-2 py-1 text-right font-bold text-red-600 bg-red-50">{item.prodWidth.toLocaleString()}</td>
                        <td className="border border-gray-600 px-2 py-1 text-right font-bold text-red-600 bg-red-50">{item.prodHeight.toLocaleString()}</td>
                        <td className="border border-gray-600 px-2 py-1 text-center">{item.guideRailType}<br />({item.guideRailSpec})</td>
                        <td className="border border-gray-600 px-2 py-1 text-center">{item.shaft}</td>
                        <td className="border border-gray-600 px-2 py-1 text-center">{item.caseSpec}</td>
                        <td className="border border-gray-600 px-2 py-1 text-center">{item.motorBracket}</td>
                        <td className="border border-gray-600 px-2 py-1 text-right">{item.capacity}</td>
                        <td className="border border-gray-600 px-2 py-1 text-center">{item.finish}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* === 2. 모터 테이블 === */}
            <div>
              <div className="font-bold mb-2">2. 모터</div>
              <div className="grid grid-cols-4 gap-2 text-xs">
                {/* 2-1. 모터(220V 단상) */}
                <div className="border border-gray-600">
                  <div className="bg-yellow-100 px-2 py-1 border-b border-gray-600 font-medium text-center">2-1. 모터(220V 단상)</div>
                  <table className="w-full">
                    <thead>
                      <tr className="bg-gray-100">
                        <th className="border-b border-r border-gray-600 px-2 py-1">모터용량</th>
                        <th className="border-b border-gray-600 px-2 py-1">수량</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.motorSpec.motors220V.map((m, idx) => (
                        <tr key={idx}>
                          <td className="border-b border-r border-gray-600 px-2 py-1">{m.model}</td>
                          <td className="border-b border-gray-600 px-2 py-1 text-center font-bold">{m.qty || ''}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* 2-2. 모터(380V 삼상) */}
                <div className="border border-gray-600">
                  <div className="bg-yellow-100 px-2 py-1 border-b border-gray-600 font-medium text-center">2-2. 모터(380V 삼상)</div>
                  <table className="w-full">
                    <thead>
                      <tr className="bg-gray-100">
                        <th className="border-b border-r border-gray-600 px-2 py-1">모터용량</th>
                        <th className="border-b border-gray-600 px-2 py-1">수량</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.motorSpec.motors380V.map((m, idx) => (
                        <tr key={idx}>
                          <td className="border-b border-r border-gray-600 px-2 py-1">{m.model}</td>
                          <td className="border-b border-gray-600 px-2 py-1 text-center font-bold text-red-600">{m.qty || ''}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* 2-3. 브라켓 */}
                <div className="border border-gray-600">
                  <div className="bg-yellow-100 px-2 py-1 border-b border-gray-600 font-medium text-center">2-3. 브라켓</div>
                  <table className="w-full">
                    <thead>
                      <tr className="bg-gray-100">
                        <th className="border-b border-r border-gray-600 px-2 py-1">브라켓</th>
                        <th className="border-b border-gray-600 px-2 py-1">수량</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.motorSpec.brackets.map((b, idx) => (
                        <tr key={idx}>
                          <td className="border-b border-r border-gray-600 px-2 py-1 text-xs">{b.spec}</td>
                          <td className="border-b border-gray-600 px-2 py-1 text-center font-bold">{b.qty || ''}</td>
                        </tr>
                      ))}
                      {data.motorSpec.heatSinks.map((h, idx) => (
                        <tr key={`h-${idx}`}>
                          <td className="border-b border-r border-gray-600 px-2 py-1">방열등 {h.spec}</td>
                          <td className="border-b border-gray-600 px-2 py-1 text-center font-bold text-red-600">{h.qty || ''}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* 2-4. 연동제어기 */}
                <div className="border border-gray-600">
                  <div className="bg-yellow-100 px-2 py-1 border-b border-gray-600 font-medium text-center">2-4. 연동제어기</div>
                  <table className="w-full">
                    <thead>
                      <tr className="bg-gray-100">
                        <th className="border-b border-r border-gray-600 px-2 py-1">용량</th>
                        <th className="border-b border-gray-600 px-2 py-1">수량</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.motorSpec.controllers.map((c, idx) => (
                        <tr key={idx}>
                          <td className="border-b border-r border-gray-600 px-2 py-1">{c.type}</td>
                          <td className="border-b border-gray-600 px-2 py-1 text-center font-bold">{c.qty || ''}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
              <div className="text-xs text-gray-500 mt-1">* 별도 추가사항</div>
            </div>

            {/* === 3. 절곡물 === */}
            <div className="border-t-2 border-gray-800 pt-4">
              <div className="font-bold mb-2">3. 절곡물</div>

              {/* 3-1. 가이드레일 */}
              <div className="mb-4">
                <div className="text-sm font-medium mb-1">3-1. {data.bomData.guideRails.description}</div>
                <div className="grid grid-cols-3 gap-2 text-xs">
                  {/* 백면형 */}
                  <div className="border border-gray-600">
                    <div className="bg-blue-100 px-2 py-1 border-b border-gray-600 text-center font-medium">백면형 (120-70)</div>
                    <table className="w-full">
                      <thead>
                        <tr className="bg-gray-100">
                          <th className="border-b border-r border-gray-600 px-2 py-1">코드</th>
                          <th className="border-b border-r border-gray-600 px-2 py-1">길이</th>
                          <th className="border-b border-gray-600 px-2 py-1">수량</th>
                        </tr>
                      </thead>
                      <tbody>
                        {data.bomData.guideRails.items
                          .filter(g => g.type === '백면형')
                          .flatMap(g => g.lengths.map((l, idx) => (
                            <tr key={`${g.code}-${idx}`}>
                              <td className="border-b border-r border-gray-600 px-2 py-1">{idx === 0 ? g.code : ''}</td>
                              <td className="border-b border-r border-gray-600 px-2 py-1 text-right">L : {l.length.toLocaleString()}</td>
                              <td className="border-b border-gray-600 px-2 py-1 text-center font-bold text-red-600">{l.qty || ''}</td>
                            </tr>
                          )))
                        }
                      </tbody>
                    </table>
                  </div>

                  {/* 측면형 */}
                  <div className="border border-gray-600">
                    <div className="bg-blue-100 px-2 py-1 border-b border-gray-600 text-center font-medium">측면형 (120-120)</div>
                    <table className="w-full">
                      <thead>
                        <tr className="bg-gray-100">
                          <th className="border-b border-r border-gray-600 px-2 py-1">길이</th>
                          <th className="border-b border-gray-600 px-2 py-1">수량</th>
                        </tr>
                      </thead>
                      <tbody>
                        {data.bomData.guideRails.items
                          .filter(g => g.type === '측면형')
                          .flatMap(g => g.lengths.map((l, idx) => (
                            <tr key={`side-${idx}`}>
                              <td className="border-b border-r border-gray-600 px-2 py-1 text-right">L : {l.length.toLocaleString()}</td>
                              <td className="border-b border-gray-600 px-2 py-1 text-center font-bold">{l.qty || ''}</td>
                            </tr>
                          )))
                        }
                      </tbody>
                    </table>
                  </div>

                  {/* 하부BASE + 연기차단재 */}
                  <div className="border border-gray-600">
                    <div className="bg-blue-100 px-2 py-1 border-b border-gray-600 text-center font-medium">하부BASE (130-80)</div>
                    <table className="w-full">
                      <tbody>
                        <tr>
                          <td className="border-b border-r border-gray-600 px-2 py-1">수량</td>
                          <td className="border-b border-gray-600 px-2 py-1 text-center font-bold text-red-600">
                            {data.bomData.guideRails.items.find(g => g.type === '하부BASE')?.lengths[0]?.qty || ''}
                          </td>
                        </tr>
                      </tbody>
                    </table>
                    <div className="bg-orange-100 px-2 py-1 border-b border-gray-600 text-center font-medium mt-2">연기차단재 (W80)</div>
                    <table className="w-full">
                      <tbody>
                        <tr>
                          <td className="border-b border-r border-gray-600 px-2 py-1">규격 L</td>
                          <td className="border-b border-gray-600 px-2 py-1 text-center">{data.bomData.guideRails.smokeBarrier.lengths[0]?.length}</td>
                        </tr>
                        <tr>
                          <td className="border-b border-r border-gray-600 px-2 py-1">수량</td>
                          <td className="border-b border-gray-600 px-2 py-1 text-center font-bold text-red-600">{data.bomData.guideRails.smokeBarrier.lengths[0]?.qty}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>

              {/* 3-2. 케이스(셔터박스) */}
              <div className="mb-4">
                <div className="text-sm font-medium mb-1">3-2. {data.bomData.cases.description}</div>
                <div className="grid grid-cols-3 gap-2 text-xs">
                  <div className="border border-gray-600 col-span-2">
                    <div className="flex">
                      <div className="w-32 bg-blue-100 px-2 py-1 border-r border-gray-600 text-center font-medium">규격</div>
                      <div className="flex-1 px-2 py-1">{data.bomData.cases.mainSpec}</div>
                    </div>
                    <table className="w-full">
                      <thead>
                        <tr className="bg-gray-100">
                          <th className="border-t border-b border-r border-gray-600 px-2 py-1">길이</th>
                          <th className="border-t border-b border-r border-gray-600 px-2 py-1">수량</th>
                          <th className="border-t border-b border-r border-gray-600 px-2 py-1">측면덮개</th>
                          <th className="border-t border-b border-gray-600 px-2 py-1">수량</th>
                        </tr>
                      </thead>
                      <tbody>
                        {data.bomData.cases.items.map((item, idx) => (
                          <tr key={idx}>
                            <td className="border-b border-r border-gray-600 px-2 py-1 text-right">L : {item.length.toLocaleString()}</td>
                            <td className="border-b border-r border-gray-600 px-2 py-1 text-center font-bold">{item.qty || ''}</td>
                            {idx === 0 && (
                              <>
                                <td rowSpan={3} className="border-b border-r border-gray-600 px-2 py-1 text-center">{data.bomData.cases.sideCover.spec}</td>
                                <td rowSpan={3} className="border-b border-gray-600 px-2 py-1 text-center font-bold text-red-600">{data.bomData.cases.sideCover.qty}</td>
                              </>
                            )}
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>

                  {/* 상부덮개/연기차단재 */}
                  <div className="border border-gray-600">
                    <div className="bg-orange-100 px-2 py-1 border-b border-gray-600 text-center font-medium">상부덮개</div>
                    <div className="px-2 py-2 text-center font-bold text-red-600 text-lg">{data.bomData.cases.topCover.qty}</div>
                    <div className="bg-orange-100 px-2 py-1 border-t border-b border-gray-600 text-center font-medium">연기차단재 (W80)</div>
                    <table className="w-full">
                      <tbody>
                        <tr>
                          <td className="border-b border-r border-gray-600 px-2 py-1">길이</td>
                          <td className="border-b border-gray-600 px-2 py-1 text-center">L : {data.bomData.cases.smokeBarrier.length.toLocaleString()}</td>
                        </tr>
                        <tr>
                          <td className="border-r border-gray-600 px-2 py-1">수량</td>
                          <td className="px-2 py-1 text-center font-bold text-red-600">{data.bomData.cases.smokeBarrier.qty}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>

              {/* 3-3. 하단마감재 */}
              <div>
                <div className="text-sm font-medium mb-1">3-3. {data.bomData.bottomFinish.description}</div>
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse text-xs">
                    <thead>
                      <tr className="bg-yellow-100">
                        <th className="border border-gray-600 px-2 py-1">구성품</th>
                        <th className="border border-gray-600 px-2 py-1">길이(mm)</th>
                        <th className="border border-gray-600 px-2 py-1">수량</th>
                        <th className="border border-gray-600 px-2 py-1">구성품</th>
                        <th className="border border-gray-600 px-2 py-1">길이</th>
                        <th className="border border-gray-600 px-2 py-1">수량</th>
                        <th className="border border-gray-600 px-2 py-1">구성품</th>
                        <th className="border border-gray-600 px-2 py-1">길이</th>
                        <th className="border border-gray-600 px-2 py-1">수량</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.bomData.bottomFinish.items.map((item, idx) => (
                        <tr key={idx}>
                          <td className="border border-gray-600 px-2 py-1">{item.name}<br />({item.spec})</td>
                          {item.lengths.map((l, lidx) => (
                            <React.Fragment key={lidx}>
                              <td className="border border-gray-600 px-2 py-1 text-right">L : {l.length.toLocaleString()}</td>
                              <td className="border border-gray-600 px-2 py-1 text-center font-bold text-red-600">{l.qty}</td>
                            </React.Fragment>
                          ))}
                          {/* 빈 셀 채우기 */}
                          {item.lengths.length < 3 && Array(3 - item.lengths.length).fill(0).map((_, i) => (
                            <React.Fragment key={`empty-${i}`}>
                              <td className="border border-gray-600 px-2 py-1"></td>
                              <td className="border border-gray-600 px-2 py-1"></td>
                            </React.Fragment>
                          ))}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            {/* 푸터 */}
            <div className="text-xs text-gray-500 text-center pt-4 border-t">
              생성일시: {new Date().toLocaleString('ko-KR')} | 작업지시번호: {workOrder?.workOrderNo || data.orderInfo.lotNo}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============ 작업일지 시스템 (공정별) ============

// 공정별 작업일지 초기 데이터 생성 (로컬 정의 - mesCompleteIntegration의 것보다 상세)
const createWorkLogDataLocal = (workOrder, order, processType) => {
  const items = workOrder?.items || order?.items || [];
  const itemCount = items.length;
  const process = processType || workOrder?.processType || '절곡';
  const materialInputs = workOrder?.materialInputs || []; // ★ 자재 투입 이력 (LOT 정보 포함)

  // 자재코드로 투입된 LOT 찾기 헬퍼 함수
  const findInputLotNo = (materialCode) => {
    const input = materialInputs.find(m => m.materialCode === materialCode);
    return input?.lotNo || '';
  };

  // 공통 헤더 정보
  const baseData = {
    processType: process,
    orderDate: order?.orderDate || workOrder?.orderDate || '',
    company: order?.customerName || workOrder?.customerName || '',
    manager: order?.manager || '',
    contact: order?.contact || '',
    siteName: order?.siteName || workOrder?.siteName || '',
    workDate: new Date().toISOString().split('T')[0],
    productLotNo: workOrder?.workOrderNo || '',
    productionManager: workOrder?.assignee || '',
    totalQty: workOrder?.totalQty || itemCount,
    remarks: '',
    approval: {
      writer: '',
      checker: '전진',
      approver: '',
    },
  };

  // 스크린 공정 작업일지
  if (process === '스크린') {
    // 스크린 공정 자재코드 매핑
    const screenMaterialMap = {
      '스크린원단': 'SCR-MAT-001',
      '미싱실': 'SCR-MAT-004',
      '앤드락': 'SCR-MAT-002',
      '하단바': 'SCR-MAT-003',
      '포장재': 'SCR-MAT-005',
    };

    return {
      ...baseData,
      department: '스크린 생산부서',
      // 원단 정보
      fabric: {
        type: '망사', // 망사, 암막 등
        color: '',
        width: '',
        inputLotNo: findInputLotNo(screenMaterialMap['스크린원단']), // ★ LOT 자동 연동
      },
      // 작업 내역 - ★ 투입된 LOT 자동 연동
      workItems: [
        { id: 1, step: '원단절단', material: '스크린원단', inputLotNo: findInputLotNo(screenMaterialMap['스크린원단']), qty: itemCount, unit: 'EA', note: '' },
        { id: 2, step: '미싱', material: '미싱실', inputLotNo: findInputLotNo(screenMaterialMap['미싱실']), qty: null, unit: 'M', note: '' },
        { id: 3, step: '앤드락작업', material: '앤드락', inputLotNo: findInputLotNo(screenMaterialMap['앤드락']), qty: itemCount * 2, unit: 'EA', note: '' },
        { id: 4, step: '하단바조립', material: '하단바', inputLotNo: findInputLotNo(screenMaterialMap['하단바']), qty: itemCount, unit: 'EA', note: '' },
        { id: 5, step: '중간검사', material: '-', inputLotNo: '', qty: itemCount, unit: 'EA', note: '' },
        { id: 6, step: '포장', material: '포장재', inputLotNo: findInputLotNo(screenMaterialMap['포장재']), qty: itemCount, unit: 'EA', note: '' },
      ],
      // 품목별 상세 (규격)
      itemDetails: items.map((item, idx) => ({
        id: idx + 1,
        floor: item.floor || '',
        location: item.location || '',
        width: item.width || '',
        height: item.height || '',
        qty: item.qty || 1,
        fabricLotNo: '',
        productLotNo: '',
        inspectionResult: '', // 합격/불합격
      })),
      // 생산 실적
      productionResult: {
        totalProduced: null,
        goodQty: null,
        defectQty: null,
        defectType: '',
      },
    };
  }

  // 슬랫 공정 작업일지
  if (process === '슬랫') {
    // 슬랫 공정 자재코드 매핑
    const slatMaterialMap = {
      '슬랫코일': 'SLT-MAT-001',
      '미미캡': 'SLT-MAT-002',
      '포장재': 'SCR-MAT-005',
    };

    return {
      ...baseData,
      department: '슬랫 생산부서',
      // 코일 정보
      coil: {
        type: '알루미늄', // 알루미늄, 스틸 등
        color: '',
        thickness: '',
        inputLotNo: findInputLotNo(slatMaterialMap['슬랫코일']), // ★ LOT 자동 연동
      },
      // 작업 내역 - ★ 투입된 LOT 자동 연동
      workItems: [
        { id: 1, step: '코일절단', material: '슬랫코일', inputLotNo: findInputLotNo(slatMaterialMap['슬랫코일']), length: '', qty: null, unit: 'EA', note: '' },
        { id: 2, step: '슬랫성형', material: '-', inputLotNo: '', length: '', qty: null, unit: 'EA', note: '' },
        { id: 3, step: '중간검사', material: '-', inputLotNo: '', length: '', qty: itemCount, unit: 'EA', note: '' },
        { id: 4, step: '미미작업', material: '미미캡', inputLotNo: findInputLotNo(slatMaterialMap['미미캡']), length: '', qty: itemCount * 2, unit: 'EA', note: '' },
        { id: 5, step: '조립', material: '연결부품', inputLotNo: '', length: '', qty: null, unit: 'SET', note: '' },
        { id: 6, step: '포장', material: '포장재', inputLotNo: findInputLotNo(slatMaterialMap['포장재']), length: '', qty: itemCount, unit: 'EA', note: '' },
      ],
      // 절단 상세
      cuttingDetails: [
        { id: 1, length: 'L:4,000', qty: null },
        { id: 2, length: 'L:3,500', qty: null },
        { id: 3, length: 'L:3,000', qty: null },
        { id: 4, length: 'L:2,500', qty: null },
        { id: 5, length: 'L:2,000', qty: null },
      ],
      // 생산 실적
      productionResult: {
        totalProduced: null,
        goodQty: null,
        defectQty: null,
        defectType: '',
        totalWeight: null, // kg
      },
    };
  }

  // 절곡 공정 작업일지 (기존)
  // 절곡 공정 자재코드 매핑
  const bendingMaterialMap = {
    'EGI1.55T': 'EGI-1.55T',
    'EGI1.15T': 'EGI-1.55T', // EGI 계열은 같은 코드 사용
    'SUS1.2T': 'SUS-1.2T',
    '연기차단재': 'BND-SMK-001',
  };

  return {
    ...baseData,
    department: '절곡 생산부서',
    productCode: items[0]?.productCode || 'KWE01',
    productType: '와이어',
    finishType: 'SUS마감',
    railType: '벽면형(120·70)',

    // ★ 전개도 및 전개 상세정보 (품목에서 등록한 절곡 부품 데이터 기준)
    developedParts: [
      { itemCode: 'SD30', itemName: '엘바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 4, weight: 0.9, dimensions: '75', note: '' },
      { itemCode: 'SD31', itemName: '하장바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 1.158, dimensions: '67→126→165→178→193', note: '' },
      { itemCode: 'SD32', itemName: '짜부가스켓', material: 'E.G.I 0.8T', totalWidth: 500, length: 3000, qty: 4, weight: 0.576, dimensions: '48', note: '80*4,50*8' },
      { itemCode: 'SD33', itemName: '50평철', material: 'E.G.I 1.2T', totalWidth: 500, length: 3000, qty: 2, weight: 0.3, dimensions: '50', note: '' },
      { itemCode: 'SD34', itemName: '500*380전면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.764, dimensions: '120→499→553→588', note: '' },
      { itemCode: 'SD35', itemName: 'S/BOX 린텔박스', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 0.504, dimensions: '84→138→168', note: '' },
      { itemCode: 'SD36', itemName: '500*380밑면 점검구', material: 'E.G.I 1.6T', totalWidth: 500, length: 2438, qty: 2, weight: 0.98, dimensions: '90→240→310', note: '점검구' },
      { itemCode: 'SD37', itemName: '후면코너부', material: 'E.G.I 1.2T', totalWidth: 500, length: 1219, qty: itemCount * 2, weight: 0.45, dimensions: '35→85→120', note: '' },
    ],

    // 1. 벽면형 (120·70) - ★ 투입된 LOT 자동 연동
    guideRail: [
      { id: 1, name: '마감재', material: 'EGI1.15T', inputLotNo: findInputLotNo(bendingMaterialMap['EGI1.15T']), spec: 'L:4,300', qty: null },
      { id: 2, name: '가이드레일', material: '', inputLotNo: '', spec: 'L:4,000', qty: null },
      { id: 3, name: 'C형', material: 'EGI1.55T', inputLotNo: findInputLotNo(bendingMaterialMap['EGI1.55T']), spec: 'L:3,500', qty: null },
      { id: 4, name: 'D형', material: '', inputLotNo: '', spec: 'L:3,000', qty: itemCount * 2 },
      { id: 5, name: '별도마감재', material: 'SUS1.2T', inputLotNo: findInputLotNo(bendingMaterialMap['SUS1.2T']), spec: 'L:2,438', qty: null },
      { id: 6, name: '하부BASE', material: 'EGI1.55T', inputLotNo: findInputLotNo(bendingMaterialMap['EGI1.55T']), spec: '하부BASE 130·80', qty: itemCount * 2 },
    ],

    // 2. 하단마감재 [60·40] - ★ 투입된 LOT 자동 연동
    bottomFinish: [
      {
        id: 1, name: '하단마감재', material: 'EGI1.55T', inputLotNo: findInputLotNo(bendingMaterialMap['EGI1.55T']), rows: [
          { spec: 'L:4,000', qty: Math.ceil(itemCount * 1.1) },
          { spec: 'L:3,000', qty: Math.ceil(itemCount * 0.8) },
        ]
      },
      {
        id: 2, name: '별도마감재', material: 'SUS1.2T', inputLotNo: findInputLotNo(bendingMaterialMap['SUS1.2T']), rows: [
          { spec: 'L:4,000', qty: Math.ceil(itemCount * 1.1) },
          { spec: 'L:3,000', qty: Math.ceil(itemCount * 0.8) },
        ]
      },
      {
        id: 3, name: '하단보강엘바', material: 'EGI1.55T', inputLotNo: findInputLotNo(bendingMaterialMap['EGI1.55T']), rows: [
          { spec: 'L:4,000', qty: Math.ceil(itemCount * 2.6) },
          { spec: 'L:3,000', qty: Math.ceil(itemCount * 1.2) },
        ]
      },
      {
        id: 4, name: '하단보강평철', material: 'EGI1.15T', inputLotNo: findInputLotNo(bendingMaterialMap['EGI1.15T']), rows: [
          { spec: 'L:4,000', qty: Math.ceil(itemCount * 1.3) },
          { spec: 'L:3,000', qty: Math.ceil(itemCount * 0.6) },
        ]
      },
    ],

    // 3. 케이스 [500*330] - ★ 투입된 LOT 자동 연동
    caseBox: {
      spec: '500*330',
      material: 'EGI1.55T',
      inputLotNo: findInputLotNo(bendingMaterialMap['EGI1.55T']),
      items: [
        {
          id: 1, name: '전면부', rows: [
            { spec: 'L:4,150', qty: 1 },
            { spec: 'L:4,000', qty: 7 },
          ]
        },
        {
          id: 2, name: '린텔부', rows: [
            { spec: 'L:3,500', qty: 5 },
            { spec: 'L:3,000', qty: 3 },
          ]
        },
        {
          id: 3, name: '하부점검구', rows: [
            { spec: 'L:2,438', qty: 3 },
            { spec: 'L:1,219', qty: null },
          ]
        },
        { id: 4, name: '후면코너부', spec: '상부덮개[1219·389]', qty: Math.ceil(itemCount * 5.9) },
        { id: 5, name: '상부덮개', spec: '마구리 505·335', qty: itemCount * 2 },
        { id: 6, name: '측면부(마구리)', spec: '', qty: null },
      ],
    },

    // 4. 연기차단재 - ★ 투입된 LOT 자동 연동
    smokeBarrier: {
      rail: {
        name: '레일용[W50]',
        material: 'EG0.8T + 화이바 글라스 코팅직물',
        inputLotNo: findInputLotNo(bendingMaterialMap['연기차단재']),
        rows: [
          { spec: 'L:4,300', qty: null },
          { spec: 'L:4,000', qty: null },
          { spec: 'L:3,500', qty: null },
          { spec: 'L:3,000', qty: Math.ceil(itemCount * 4.4) },
          { spec: 'L:2,438', qty: null },
        ]
      },
      caseItem: {
        name: '케이스용[W80]',
        inputLotNo: findInputLotNo(bendingMaterialMap['연기차단재']),
        spec: 'L:3,000',
        qty: Math.ceil(itemCount * 4.7)
      },
    },

    // 생산량 합계
    totalProduction: {
      sus: null,
      egi: null,
    },
  };
};

// ============ 스크린 작업일지 에디터 ============
const ScreenWorkLogEditor = ({ workOrder, order, workLog, onClose, onSave }) => {
  const [data, setData] = useState(workLog || createWorkLogDataLocal(workOrder, order, '스크린'));
  const [activeSection, setActiveSection] = useState('header');

  const sections = [
    { id: 'header', label: '기본정보' },
    { id: 'fabric', label: '원단정보' },
    { id: 'work', label: '투입자재' },
    { id: 'items', label: '규격매수 (자동계산)' },
    { id: 'result', label: '생산실적' },
  ];

  const handleSave = () => {
    onSave?.(data);
    alert('✅ 스크린 작업일지가 저장되었습니다.');
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl w-full max-w-5xl max-h-[90vh] flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b bg-blue-50">
          <div className="flex items-center gap-3">
            <Clipboard className="w-6 h-6 text-blue-600" />
            <div>
              <h2 className="text-lg font-bold">스크린 작업일지</h2>
              <p className="text-sm text-gray-500">{workOrder?.workOrderNo}</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-blue-100 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
            ✕
          </button>
        </div>

        {/* 섹션 탭 */}
        <div className="flex border-b overflow-x-auto">
          {sections.map(section => (
            <button
              key={section.id}
              onClick={() => setActiveSection(section.id)}
              className={`px-4 py-2 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${activeSection === section.id
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
                }`}
            >
              {section.label}
            </button>
          ))}
        </div>

        {/* 콘텐츠 */}
        <div className="flex-1 overflow-y-auto p-4">
          {/* 기본정보 */}
          {activeSection === 'header' && (
            <div className="grid grid-cols-2 gap-6">
              <Card title="신청업체">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">발주일</label>
                    <input type="date" value={data.orderDate} onChange={(e) => setData({ ...data, orderDate: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">업체명</label>
                    <input type="text" value={data.company} onChange={(e) => setData({ ...data, company: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">담당자</label>
                    <input type="text" value={data.manager} onChange={(e) => setData({ ...data, manager: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">연락처</label>
                    <input type="text" value={data.contact} onChange={(e) => setData({ ...data, contact: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                </div>
              </Card>
              <Card title="신청내용">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">현장명</label>
                    <input type="text" value={data.siteName} onChange={(e) => setData({ ...data, siteName: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">작업일자</label>
                    <input type="date" value={data.workDate} onChange={(e) => setData({ ...data, workDate: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">제품 LOT NO</label>
                    <input type="text" value={data.productLotNo} onChange={(e) => setData({ ...data, productLotNo: e.target.value })} className="w-full px-3 py-2 border rounded-lg font-mono" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">생산담당자</label>
                    <input type="text" value={data.productionManager} onChange={(e) => setData({ ...data, productionManager: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                </div>
              </Card>
            </div>
          )}

          {/* 원단정보 */}
          {activeSection === 'fabric' && (
            <Card title="원단 정보">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">원단유형</label>
                  <select value={data.fabric.type} onChange={(e) => setData({ ...data, fabric: { ...data.fabric, type: e.target.value } })} className="w-full px-3 py-2 border rounded-lg">
                    <option>망사</option>
                    <option>암막</option>
                    <option>반투명</option>
                    <option>방염</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">색상</label>
                  <input type="text" value={data.fabric.color} onChange={(e) => setData({ ...data, fabric: { ...data.fabric, color: e.target.value } })} placeholder="예: 아이보리" className="w-full px-3 py-2 border rounded-lg" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">폭(mm)</label>
                  <input type="text" value={data.fabric.width} onChange={(e) => setData({ ...data, fabric: { ...data.fabric, width: e.target.value } })} placeholder="예: 3000" className="w-full px-3 py-2 border rounded-lg" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">입고 LOT NO</label>
                  <input type="text" value={data.fabric.inputLotNo} onChange={(e) => setData({ ...data, fabric: { ...data.fabric, inputLotNo: e.target.value } })} placeholder="LOT 번호" className="w-full px-3 py-2 border rounded-lg font-mono" />
                </div>
              </div>
            </Card>
          )}

          {/* 작업내역 */}
          {activeSection === 'work' && (
            <Card title="작업 내역">
              <table className="w-full text-sm">
                <thead className="bg-blue-50">
                  <tr>
                    <th className="px-3 py-2 text-left">공정</th>
                    <th className="px-3 py-2 text-left">투입자재</th>
                    <th className="px-3 py-2 text-left">입고 LOT NO</th>
                    <th className="px-3 py-2 text-right">수량</th>
                    <th className="px-3 py-2 text-left">단위</th>
                    <th className="px-3 py-2 text-left">비고</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {data.workItems.map((item, idx) => (
                    <tr key={item.id} className={item.step === '중간검사' ? 'bg-yellow-50' : ''}>
                      <td className="px-3 py-2 font-medium">{item.step}</td>
                      <td className="px-3 py-2 text-gray-600">{item.material}</td>
                      <td className="px-3 py-2">
                        <input
                          type="text"
                          value={item.inputLotNo}
                          onChange={(e) => {
                            const newItems = [...data.workItems];
                            newItems[idx].inputLotNo = e.target.value;
                            setData({ ...data, workItems: newItems });
                          }}
                          placeholder="LOT"
                          className="w-full px-2 py-1 border rounded text-sm font-mono"
                        />
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="number"
                          value={item.qty || ''}
                          onChange={(e) => {
                            const newItems = [...data.workItems];
                            newItems[idx].qty = e.target.value ? parseInt(e.target.value) : null;
                            setData({ ...data, workItems: newItems });
                          }}
                          className="w-20 px-2 py-1 border rounded text-right"
                        />
                      </td>
                      <td className="px-3 py-2 text-gray-500">{item.unit}</td>
                      <td className="px-3 py-2">
                        <input
                          type="text"
                          value={item.note}
                          onChange={(e) => {
                            const newItems = [...data.workItems];
                            newItems[idx].note = e.target.value;
                            setData({ ...data, workItems: newItems });
                          }}
                          placeholder="메모"
                          className="w-full px-2 py-1 border rounded text-sm"
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </Card>
          )}

          {/* 품목상세 - 규격매수 계산 테이블 (문서양식관리 TBL-WORKLOG-SCREEN 기준) */}
          {activeSection === 'items' && (
            <Card title="■ 작업 내역 (규격매수 자동계산)">
              {/* 규격매수 계산 공식 안내 */}
              <div className="mb-4 p-3 bg-blue-50 rounded-lg text-xs">
                <p className="font-medium text-blue-800 mb-1">자동 계산 공식</p>
                <p className="text-blue-600">• 규격 1210: 가로 크기에 따라 매수 자동 계산 (1070~1970→1매, 1970~3140→2매, ...)</p>
                <p className="text-blue-600">• 규격 300~900: 나머지높이에 따라 분배 (0~300→300, 300~400→400, 400~600→600, 600~900→900)</p>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm border-collapse">
                  <thead>
                    <tr className="bg-gray-200">
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs">일련<br />번호</th>
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs">입고 LOT NO.</th>
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs">제품명</th>
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs">부호</th>
                      <th colSpan={3} className="px-2 py-1 border text-center text-xs bg-gray-300">제작사이즈(mm)</th>
                      <th colSpan={5} className="px-2 py-1 border text-center text-xs bg-yellow-100">규격(매수)</th>
                    </tr>
                    <tr className="bg-gray-200">
                      <th className="px-2 py-1 border text-center text-xs w-16">가로</th>
                      <th className="px-2 py-1 border text-center text-xs w-16">세로</th>
                      <th className="px-2 py-1 border text-center text-xs w-16 bg-red-100">나머지<br />높이</th>
                      <th className="px-2 py-1 border text-center text-xs w-12 bg-yellow-100">1210</th>
                      <th className="px-2 py-1 border text-center text-xs w-12 bg-yellow-100">900</th>
                      <th className="px-2 py-1 border text-center text-xs w-12 bg-yellow-100">600</th>
                      <th className="px-2 py-1 border text-center text-xs w-12 bg-yellow-100">400</th>
                      <th className="px-2 py-1 border text-center text-xs w-12 bg-yellow-100">300</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.itemDetails.map((item, idx) => {
                      // ★ 규격매수 자동 계산 공식 (documentTemplateConfig.js TBL-WORKLOG-SCREEN 기준)
                      const calculateSpec = (width, remainHeight) => {
                        // 가로 기준 1210 규격 매수 계산
                        let spec1210 = 0;
                        const ranges = [
                          { min: 0, max: 1070, count: 0 },
                          { min: 1070, max: 1970, count: 1 },
                          { min: 1970, max: 3140, count: 2 },
                          { min: 3140, max: 4310, count: 3 },
                          { min: 4310, max: 5480, count: 4 },
                          { min: 5480, max: 6650, count: 5 },
                          { min: 6650, max: 7820, count: 6 },
                          { min: 7820, max: 8990, count: 7 },
                          { min: 8990, max: 10160, count: 8 },
                          { min: 10160, max: 99999, count: 9 },
                        ];
                        for (const range of ranges) {
                          if (width > range.min && width <= range.max) {
                            spec1210 = range.count;
                            break;
                          }
                        }
                        // 나머지높이 기준 규격 분배
                        const specs = { spec1210, spec900: 0, spec600: 0, spec400: 0, spec300: 0 };
                        if (remainHeight > 0 && remainHeight <= 300) specs.spec300 = 1;
                        else if (remainHeight > 300 && remainHeight <= 400) specs.spec400 = 1;
                        else if (remainHeight > 400 && remainHeight <= 600) specs.spec600 = 1;
                        else if (remainHeight > 600 && remainHeight <= 900) specs.spec900 = 1;
                        return specs;
                      };
                      const specs = calculateSpec(item.width || 0, item.remainHeight || 0);
                      return (
                        <tr key={item.id} className="hover:bg-gray-50">
                          <td className="px-2 py-2 border text-center text-gray-500">{item.id}</td>
                          <td className="px-2 py-2 border">
                            <input type="text" value={item.fabricLotNo || ''} onChange={(e) => {
                              const newItems = [...data.itemDetails];
                              newItems[idx].fabricLotNo = e.target.value;
                              setData({ ...data, itemDetails: newItems });
                            }} placeholder="LOT" className="w-full px-1 py-1 border rounded text-xs font-mono" />
                          </td>
                          <td className="px-2 py-2 border text-center">{item.productName || '방화스크린'}</td>
                          <td className="px-2 py-2 border text-center">{item.location}</td>
                          <td className="px-2 py-2 border bg-yellow-50">
                            <input type="number" value={item.width || ''} onChange={(e) => {
                              const newItems = [...data.itemDetails];
                              newItems[idx].width = e.target.value ? parseInt(e.target.value) : null;
                              setData({ ...data, itemDetails: newItems });
                            }} className="w-full px-1 py-1 border rounded text-xs text-center" />
                          </td>
                          <td className="px-2 py-2 border bg-yellow-50">
                            <input type="number" value={item.height || ''} onChange={(e) => {
                              const newItems = [...data.itemDetails];
                              newItems[idx].height = e.target.value ? parseInt(e.target.value) : null;
                              setData({ ...data, itemDetails: newItems });
                            }} className="w-full px-1 py-1 border rounded text-xs text-center" />
                          </td>
                          <td className="px-2 py-2 border bg-red-50">
                            <input type="number" value={item.remainHeight || ''} onChange={(e) => {
                              const newItems = [...data.itemDetails];
                              newItems[idx].remainHeight = e.target.value ? parseInt(e.target.value) : null;
                              setData({ ...data, itemDetails: newItems });
                            }} className="w-full px-1 py-1 border rounded text-xs text-center" />
                          </td>
                          <td className="px-2 py-2 border text-center font-bold bg-blue-50">{specs.spec1210 || '-'}</td>
                          <td className="px-2 py-2 border text-center font-bold bg-blue-50">{specs.spec900 || '-'}</td>
                          <td className="px-2 py-2 border text-center font-bold bg-blue-50">{specs.spec600 || '-'}</td>
                          <td className="px-2 py-2 border text-center font-bold bg-blue-50">{specs.spec400 || '-'}</td>
                          <td className="px-2 py-2 border text-center font-bold bg-blue-50">{specs.spec300 || '-'}</td>
                        </tr>
                      );
                    })}
                    {/* 합계 행 */}
                    <tr className="bg-gray-100 font-bold">
                      <td colSpan={7} className="px-2 py-2 border text-right">합계</td>
                      <td className="px-2 py-2 border text-center">
                        {data.itemDetails.reduce((sum, item) => {
                          const spec = item.width > 1070 ? (item.width <= 1970 ? 1 : item.width <= 3140 ? 2 : item.width <= 4310 ? 3 : item.width <= 5480 ? 4 : item.width <= 6650 ? 5 : item.width <= 7820 ? 6 : item.width <= 8990 ? 7 : item.width <= 10160 ? 8 : 9) : 0;
                          return sum + spec;
                        }, 0)}
                      </td>
                      <td className="px-2 py-2 border text-center">
                        {data.itemDetails.filter(i => i.remainHeight > 600 && i.remainHeight <= 900).length}
                      </td>
                      <td className="px-2 py-2 border text-center">
                        {data.itemDetails.filter(i => i.remainHeight > 400 && i.remainHeight <= 600).length}
                      </td>
                      <td className="px-2 py-2 border text-center">
                        {data.itemDetails.filter(i => i.remainHeight > 300 && i.remainHeight <= 400).length}
                      </td>
                      <td className="px-2 py-2 border text-center">
                        {data.itemDetails.filter(i => i.remainHeight > 0 && i.remainHeight <= 300).length}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
              {/* 사용량 요약 */}
              <div className="mt-4 grid grid-cols-2 gap-4">
                <div className="p-3 bg-gray-50 rounded-lg">
                  <p className="text-sm font-medium text-gray-700 mb-2">사용량(M) - 규격별</p>
                  <div className="grid grid-cols-5 gap-2 text-xs">
                    <div className="text-center">
                      <span className="block text-gray-500">1210</span>
                      <span className="font-bold">{(data.itemDetails.reduce((sum, item) => {
                        const spec = item.width > 1070 ? (item.width <= 1970 ? 1 : item.width <= 3140 ? 2 : item.width <= 4310 ? 3 : item.width <= 5480 ? 4 : item.width <= 6650 ? 5 : item.width <= 7820 ? 6 : item.width <= 8990 ? 7 : 8) : 0;
                        return sum + (spec * 1.21 * (item.height || 0) / 1000);
                      }, 0)).toFixed(2)}</span>
                    </div>
                    <div className="text-center">
                      <span className="block text-gray-500">900</span>
                      <span className="font-bold">{(data.itemDetails.filter(i => i.remainHeight > 600 && i.remainHeight <= 900).reduce((sum, i) => sum + 0.9 * (i.height || 0) / 1000, 0)).toFixed(2)}</span>
                    </div>
                    <div className="text-center">
                      <span className="block text-gray-500">600</span>
                      <span className="font-bold">{(data.itemDetails.filter(i => i.remainHeight > 400 && i.remainHeight <= 600).reduce((sum, i) => sum + 0.6 * (i.height || 0) / 1000, 0)).toFixed(2)}</span>
                    </div>
                    <div className="text-center">
                      <span className="block text-gray-500">400</span>
                      <span className="font-bold">{(data.itemDetails.filter(i => i.remainHeight > 300 && i.remainHeight <= 400).reduce((sum, i) => sum + 0.4 * (i.height || 0) / 1000, 0)).toFixed(2)}</span>
                    </div>
                    <div className="text-center">
                      <span className="block text-gray-500">300</span>
                      <span className="font-bold">{(data.itemDetails.filter(i => i.remainHeight > 0 && i.remainHeight <= 300).reduce((sum, i) => sum + 0.3 * (i.height || 0) / 1000, 0)).toFixed(2)}</span>
                    </div>
                  </div>
                </div>
                <div className="p-3 bg-blue-50 rounded-lg flex items-center justify-center">
                  <div className="text-center">
                    <p className="text-sm font-medium text-blue-700 mb-1">총 사용량 (m²)</p>
                    <p className="text-2xl font-bold text-blue-800">
                      {(data.itemDetails.reduce((sum, item) => sum + ((item.width || 0) * (item.height || 0) / 1000000), 0)).toFixed(2)}
                    </p>
                  </div>
                </div>
              </div>
            </Card>
          )}

          {/* 생산실적 */}
          {activeSection === 'result' && (
            <div className="space-y-6">
              <Card title="생산 실적">
                <div className="grid grid-cols-4 gap-6">
                  <div className="p-4 bg-blue-50 rounded-lg text-center">
                    <label className="block text-sm text-blue-600 mb-2">총 생산수량</label>
                    <input
                      type="number"
                      value={data.productionResult.totalProduced || ''}
                      onChange={(e) => setData({ ...data, productionResult: { ...data.productionResult, totalProduced: e.target.value ? parseInt(e.target.value) : null } })}
                      className="w-24 px-3 py-2 border rounded-lg text-xl font-bold text-center mx-auto"
                    />
                  </div>
                  <div className="p-4 bg-green-50 rounded-lg text-center">
                    <label className="block text-sm text-green-600 mb-2">양품수량</label>
                    <input
                      type="number"
                      value={data.productionResult.goodQty || ''}
                      onChange={(e) => setData({ ...data, productionResult: { ...data.productionResult, goodQty: e.target.value ? parseInt(e.target.value) : null } })}
                      className="w-24 px-3 py-2 border rounded-lg text-xl font-bold text-center mx-auto"
                    />
                  </div>
                  <div className="p-4 bg-red-50 rounded-lg text-center">
                    <label className="block text-sm text-red-600 mb-2">불량수량</label>
                    <input
                      type="number"
                      value={data.productionResult.defectQty || ''}
                      onChange={(e) => setData({ ...data, productionResult: { ...data.productionResult, defectQty: e.target.value ? parseInt(e.target.value) : null } })}
                      className="w-24 px-3 py-2 border rounded-lg text-xl font-bold text-center mx-auto"
                    />
                  </div>
                  <div className="p-4 bg-gray-50 rounded-lg">
                    <label className="block text-sm text-gray-600 mb-2">불량유형</label>
                    <select
                      value={data.productionResult.defectType}
                      onChange={(e) => setData({ ...data, productionResult: { ...data.productionResult, defectType: e.target.value } })}
                      className="w-full px-3 py-2 border rounded-lg"
                    >
                      <option value="">선택</option>
                      <option>치수불량</option>
                      <option>봉제불량</option>
                      <option>원단불량</option>
                      <option>오염</option>
                      <option>기타</option>
                    </select>
                  </div>
                </div>
              </Card>
              <Card title="비고">
                <textarea
                  value={data.remarks}
                  onChange={(e) => setData({ ...data, remarks: e.target.value })}
                  rows={4}
                  placeholder="특이사항이나 메모를 입력하세요..."
                  className="w-full px-3 py-2 border rounded-lg"
                />
              </Card>
            </div>
          )}
        </div>

        {/* 하단 버튼 */}
        <div className="flex gap-2 p-4 border-t bg-gray-50">
          <Button variant="outline" onClick={onClose}>취소</Button>
          <Button variant="primary" className="flex-1" onClick={handleSave}>
            <Check className="w-4 h-4" /> 저장
          </Button>
        </div>
      </div>
    </div>
  );
};

// ============ 슬랫 작업일지 에디터 ============
const SlatWorkLogEditor = ({ workOrder, order, workLog, onClose, onSave }) => {
  const [data, setData] = useState(workLog || createWorkLogDataLocal(workOrder, order, '슬랫'));
  const [activeSection, setActiveSection] = useState('header');

  const sections = [
    { id: 'header', label: '기본정보' },
    { id: 'coil', label: '코일정보' },
    { id: 'cutting', label: '슬랫 생산 (자동계산)' },
    { id: 'work', label: '투입자재' },
    { id: 'result', label: '생산실적' },
  ];

  const handleSave = () => {
    onSave?.(data);
    alert('✅ 슬랫 작업일지가 저장되었습니다.');
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl w-full max-w-5xl max-h-[90vh] flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b bg-purple-50">
          <div className="flex items-center gap-3">
            <Clipboard className="w-6 h-6 text-purple-600" />
            <div>
              <h2 className="text-lg font-bold">슬랫 작업일지</h2>
              <p className="text-sm text-gray-500">{workOrder?.workOrderNo}</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-purple-100 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
            ✕
          </button>
        </div>

        {/* 섹션 탭 */}
        <div className="flex border-b overflow-x-auto">
          {sections.map(section => (
            <button
              key={section.id}
              onClick={() => setActiveSection(section.id)}
              className={`px-4 py-2 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${activeSection === section.id
                  ? 'border-purple-500 text-purple-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
                }`}
            >
              {section.label}
            </button>
          ))}
        </div>

        {/* 콘텐츠 */}
        <div className="flex-1 overflow-y-auto p-4">
          {/* 기본정보 */}
          {activeSection === 'header' && (
            <div className="grid grid-cols-2 gap-6">
              <Card title="신청업체">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">발주일</label>
                    <input type="date" value={data.orderDate} onChange={(e) => setData({ ...data, orderDate: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">업체명</label>
                    <input type="text" value={data.company} onChange={(e) => setData({ ...data, company: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">담당자</label>
                    <input type="text" value={data.manager} onChange={(e) => setData({ ...data, manager: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">연락처</label>
                    <input type="text" value={data.contact} onChange={(e) => setData({ ...data, contact: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                </div>
              </Card>
              <Card title="신청내용">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">현장명</label>
                    <input type="text" value={data.siteName} onChange={(e) => setData({ ...data, siteName: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">작업일자</label>
                    <input type="date" value={data.workDate} onChange={(e) => setData({ ...data, workDate: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">제품 LOT NO</label>
                    <input type="text" value={data.productLotNo} onChange={(e) => setData({ ...data, productLotNo: e.target.value })} className="w-full px-3 py-2 border rounded-lg font-mono" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">생산담당자</label>
                    <input type="text" value={data.productionManager} onChange={(e) => setData({ ...data, productionManager: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
                  </div>
                </div>
              </Card>
            </div>
          )}

          {/* 코일정보 */}
          {activeSection === 'coil' && (
            <Card title="코일 정보">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">코일유형</label>
                  <select value={data.coil.type} onChange={(e) => setData({ ...data, coil: { ...data.coil, type: e.target.value } })} className="w-full px-3 py-2 border rounded-lg">
                    <option>알루미늄</option>
                    <option>스틸</option>
                    <option>스테인리스</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">색상</label>
                  <input type="text" value={data.coil.color} onChange={(e) => setData({ ...data, coil: { ...data.coil, color: e.target.value } })} placeholder="예: 실버" className="w-full px-3 py-2 border rounded-lg" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">두께(T)</label>
                  <input type="text" value={data.coil.thickness} onChange={(e) => setData({ ...data, coil: { ...data.coil, thickness: e.target.value } })} placeholder="예: 0.5T" className="w-full px-3 py-2 border rounded-lg" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">입고 LOT NO</label>
                  <input type="text" value={data.coil.inputLotNo} onChange={(e) => setData({ ...data, coil: { ...data.coil, inputLotNo: e.target.value } })} placeholder="LOT 번호" className="w-full px-3 py-2 border rounded-lg font-mono" />
                </div>
              </div>
            </Card>
          )}

          {/* 절단내역 - 슬랫 생산내역 계산 테이블 (문서양식관리 TBL-WORKLOG-SLAT 기준) */}
          {activeSection === 'cutting' && (
            <Card title="■ 작업 내역 (슬랫 생산 - 자동계산)">
              {/* 슬랫 계산 공식 안내 */}
              <div className="mb-4 p-3 bg-purple-50 rounded-lg text-xs">
                <p className="font-medium text-purple-800 mb-1">자동 계산 공식</p>
                <p className="text-purple-600">• 매수(세로) = ROUNDDOWN(세로/72+1, 0) - 슬랫 피치 72mm 기준</p>
                <p className="text-purple-600">• 조인트바 수량 = 매수 ÷ 10 (올림)</p>
                <p className="text-purple-600">• 코일사용량 = (가로 × 세로 / 1,000,000) × 14.33</p>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm border-collapse">
                  <thead>
                    <tr className="bg-gray-200">
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs">일련<br />번호</th>
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs">입고 LOT NO.</th>
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs">제품명</th>
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs">부호</th>
                      <th colSpan={2} className="px-2 py-1 border text-center text-xs bg-gray-300">제작사이즈(mm)</th>
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs bg-green-100">매수<br />(세로)</th>
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs bg-blue-100">조인트바</th>
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs bg-green-100">방화유리<br />수량</th>
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs bg-yellow-100">코일<br />사용량</th>
                      <th rowSpan={2} className="px-2 py-2 border text-center text-xs">설치층/<br />부호</th>
                    </tr>
                    <tr className="bg-gray-200">
                      <th className="px-2 py-1 border text-center text-xs w-16">가로</th>
                      <th className="px-2 py-1 border text-center text-xs w-16">세로</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(data.slatItems || data.cuttingDetails || []).map((item, idx) => {
                      // ★ 슬랫 자동 계산 공식 (documentTemplateConfig.js slateCalculation 기준)
                      const height = item.height || item.length || 0;
                      const width = item.width || 0;
                      // 매수(세로) = ROUNDDOWN(세로/72+1, 0)
                      const sheetCount = height > 0 ? Math.floor(height / 72 + 1) : 0;
                      // 조인트바 수량 = 매수 ÷ 10 (올림)
                      const jointBarQty = sheetCount > 0 ? Math.ceil(sheetCount / 10) : 0;
                      // 코일사용량 = (가로 × 세로 / 1,000,000) × 14.33
                      const coilUsage = width > 0 && height > 0 ? Math.round((width * height / 1000000) * 14.33 * 10) / 10 : 0;
                      return (
                        <tr key={item.id || idx} className="hover:bg-gray-50">
                          <td className="px-2 py-2 border text-center text-gray-500">{idx + 1}</td>
                          <td className="px-2 py-2 border">
                            <input type="text" value={item.inputLotNo || ''} onChange={(e) => {
                              const key = data.slatItems ? 'slatItems' : 'cuttingDetails';
                              const newItems = [...(data[key] || [])];
                              newItems[idx] = { ...newItems[idx], inputLotNo: e.target.value };
                              setData({ ...data, [key]: newItems });
                            }} placeholder="LOT" className="w-full px-1 py-1 border rounded text-xs font-mono" />
                          </td>
                          <td className="px-2 py-2 border text-center">{item.productName || '방화셔터'}</td>
                          <td className="px-2 py-2 border">
                            <input type="text" value={item.partCode || item.location || ''} onChange={(e) => {
                              const key = data.slatItems ? 'slatItems' : 'cuttingDetails';
                              const newItems = [...(data[key] || [])];
                              newItems[idx] = { ...newItems[idx], partCode: e.target.value };
                              setData({ ...data, [key]: newItems });
                            }} placeholder="부호" className="w-full px-1 py-1 border rounded text-xs text-center" />
                          </td>
                          <td className="px-2 py-2 border bg-yellow-50">
                            <input type="number" value={width || ''} onChange={(e) => {
                              const key = data.slatItems ? 'slatItems' : 'cuttingDetails';
                              const newItems = [...(data[key] || [])];
                              newItems[idx] = { ...newItems[idx], width: e.target.value ? parseInt(e.target.value) : null };
                              setData({ ...data, [key]: newItems });
                            }} className="w-full px-1 py-1 border rounded text-xs text-center" />
                          </td>
                          <td className="px-2 py-2 border bg-yellow-50">
                            <input type="number" value={height || ''} onChange={(e) => {
                              const key = data.slatItems ? 'slatItems' : 'cuttingDetails';
                              const newItems = [...(data[key] || [])];
                              newItems[idx] = { ...newItems[idx], height: e.target.value ? parseInt(e.target.value) : null, length: e.target.value ? parseInt(e.target.value) : null };
                              setData({ ...data, [key]: newItems });
                            }} className="w-full px-1 py-1 border rounded text-xs text-center" />
                          </td>
                          <td className="px-2 py-2 border text-center font-bold bg-green-50">{sheetCount || '-'}</td>
                          <td className="px-2 py-2 border text-center font-bold bg-blue-50">{jointBarQty || '-'}</td>
                          <td className="px-2 py-2 border bg-green-50">
                            <input type="number" value={item.fireGlassQty || ''} onChange={(e) => {
                              const key = data.slatItems ? 'slatItems' : 'cuttingDetails';
                              const newItems = [...(data[key] || [])];
                              newItems[idx] = { ...newItems[idx], fireGlassQty: e.target.value ? parseInt(e.target.value) : null };
                              setData({ ...data, [key]: newItems });
                            }} className="w-full px-1 py-1 border rounded text-xs text-center" />
                          </td>
                          <td className="px-2 py-2 border text-center font-bold bg-yellow-50">{coilUsage || '-'}</td>
                          <td className="px-2 py-2 border">
                            <input type="text" value={item.installFloor || ''} onChange={(e) => {
                              const key = data.slatItems ? 'slatItems' : 'cuttingDetails';
                              const newItems = [...(data[key] || [])];
                              newItems[idx] = { ...newItems[idx], installFloor: e.target.value };
                              setData({ ...data, [key]: newItems });
                            }} placeholder="층/부호" className="w-full px-1 py-1 border rounded text-xs text-center" />
                          </td>
                        </tr>
                      );
                    })}
                    {/* 합계 행 */}
                    <tr className="bg-gray-100 font-bold">
                      <td colSpan={6} className="px-2 py-2 border text-right">합계</td>
                      <td className="px-2 py-2 border text-center">
                        {(data.slatItems || data.cuttingDetails || []).reduce((sum, item) => {
                          const height = item.height || item.length || 0;
                          return sum + (height > 0 ? Math.floor(height / 72 + 1) : 0);
                        }, 0)}
                      </td>
                      <td className="px-2 py-2 border text-center">
                        {(data.slatItems || data.cuttingDetails || []).reduce((sum, item) => {
                          const height = item.height || item.length || 0;
                          const sheetCount = height > 0 ? Math.floor(height / 72 + 1) : 0;
                          return sum + Math.ceil(sheetCount / 10);
                        }, 0)}
                      </td>
                      <td className="px-2 py-2 border text-center">
                        {(data.slatItems || data.cuttingDetails || []).reduce((sum, item) => sum + (item.fireGlassQty || 0), 0)}
                      </td>
                      <td className="px-2 py-2 border text-center">
                        {((data.slatItems || data.cuttingDetails || []).reduce((sum, item) => {
                          const width = item.width || 0;
                          const height = item.height || item.length || 0;
                          return sum + (width > 0 && height > 0 ? (width * height / 1000000) * 14.33 : 0);
                        }, 0)).toFixed(1)}
                      </td>
                      <td className="px-2 py-2 border"></td>
                    </tr>
                  </tbody>
                </table>
              </div>
              {/* 생산량 요약 */}
              <div className="mt-4 grid grid-cols-3 gap-4">
                <div className="p-3 bg-green-50 rounded-lg text-center">
                  <p className="text-sm font-medium text-green-700 mb-1">매수 합계</p>
                  <p className="text-2xl font-bold text-green-800">
                    {(data.slatItems || data.cuttingDetails || []).reduce((sum, item) => {
                      const height = item.height || item.length || 0;
                      return sum + (height > 0 ? Math.floor(height / 72 + 1) : 0);
                    }, 0)} 매
                  </p>
                </div>
                <div className="p-3 bg-blue-50 rounded-lg text-center">
                  <p className="text-sm font-medium text-blue-700 mb-1">조인트바 합계</p>
                  <p className="text-2xl font-bold text-blue-800">
                    {(data.slatItems || data.cuttingDetails || []).reduce((sum, item) => {
                      const height = item.height || item.length || 0;
                      const sheetCount = height > 0 ? Math.floor(height / 72 + 1) : 0;
                      return sum + Math.ceil(sheetCount / 10);
                    }, 0)} 개
                  </p>
                </div>
                <div className="p-3 bg-purple-50 rounded-lg text-center">
                  <p className="text-sm font-medium text-purple-700 mb-1">생산량 (m²)</p>
                  <p className="text-2xl font-bold text-purple-800">
                    {((data.slatItems || data.cuttingDetails || []).reduce((sum, item) => {
                      const width = item.width || 0;
                      const height = item.height || item.length || 0;
                      return sum + (width * height / 1000000);
                    }, 0)).toFixed(2)}
                  </p>
                </div>
              </div>
            </Card>
          )}

          {/* 작업내역 */}
          {activeSection === 'work' && (
            <Card title="작업 내역">
              <table className="w-full text-sm">
                <thead className="bg-purple-50">
                  <tr>
                    <th className="px-3 py-2 text-left">공정</th>
                    <th className="px-3 py-2 text-left">투입자재</th>
                    <th className="px-3 py-2 text-left">입고 LOT NO</th>
                    <th className="px-3 py-2 text-right">수량</th>
                    <th className="px-3 py-2 text-left">단위</th>
                    <th className="px-3 py-2 text-left">비고</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {data.workItems.map((item, idx) => (
                    <tr key={item.id} className={item.step === '중간검사' ? 'bg-yellow-50' : ''}>
                      <td className="px-3 py-2 font-medium">{item.step}</td>
                      <td className="px-3 py-2 text-gray-600">{item.material}</td>
                      <td className="px-3 py-2">
                        <input
                          type="text"
                          value={item.inputLotNo}
                          onChange={(e) => {
                            const newItems = [...data.workItems];
                            newItems[idx].inputLotNo = e.target.value;
                            setData({ ...data, workItems: newItems });
                          }}
                          placeholder="LOT"
                          className="w-full px-2 py-1 border rounded text-sm font-mono"
                        />
                      </td>
                      <td className="px-3 py-2">
                        <input
                          type="number"
                          value={item.qty || ''}
                          onChange={(e) => {
                            const newItems = [...data.workItems];
                            newItems[idx].qty = e.target.value ? parseInt(e.target.value) : null;
                            setData({ ...data, workItems: newItems });
                          }}
                          className="w-20 px-2 py-1 border rounded text-right"
                        />
                      </td>
                      <td className="px-3 py-2 text-gray-500">{item.unit}</td>
                      <td className="px-3 py-2">
                        <input
                          type="text"
                          value={item.note}
                          onChange={(e) => {
                            const newItems = [...data.workItems];
                            newItems[idx].note = e.target.value;
                            setData({ ...data, workItems: newItems });
                          }}
                          placeholder="메모"
                          className="w-full px-2 py-1 border rounded text-sm"
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </Card>
          )}

          {/* 생산실적 */}
          {activeSection === 'result' && (
            <div className="space-y-6">
              <Card title="생산 실적">
                <div className="grid grid-cols-5 gap-4">
                  <div className="p-4 bg-purple-50 rounded-lg text-center">
                    <label className="block text-sm text-purple-600 mb-2">총 생산수량</label>
                    <input
                      type="number"
                      value={data.productionResult.totalProduced || ''}
                      onChange={(e) => setData({ ...data, productionResult: { ...data.productionResult, totalProduced: e.target.value ? parseInt(e.target.value) : null } })}
                      className="w-20 px-2 py-2 border rounded-lg text-xl font-bold text-center mx-auto"
                    />
                  </div>
                  <div className="p-4 bg-green-50 rounded-lg text-center">
                    <label className="block text-sm text-green-600 mb-2">양품수량</label>
                    <input
                      type="number"
                      value={data.productionResult.goodQty || ''}
                      onChange={(e) => setData({ ...data, productionResult: { ...data.productionResult, goodQty: e.target.value ? parseInt(e.target.value) : null } })}
                      className="w-20 px-2 py-2 border rounded-lg text-xl font-bold text-center mx-auto"
                    />
                  </div>
                  <div className="p-4 bg-red-50 rounded-lg text-center">
                    <label className="block text-sm text-red-600 mb-2">불량수량</label>
                    <input
                      type="number"
                      value={data.productionResult.defectQty || ''}
                      onChange={(e) => setData({ ...data, productionResult: { ...data.productionResult, defectQty: e.target.value ? parseInt(e.target.value) : null } })}
                      className="w-20 px-2 py-2 border rounded-lg text-xl font-bold text-center mx-auto"
                    />
                  </div>
                  <div className="p-4 bg-gray-50 rounded-lg">
                    <label className="block text-sm text-gray-600 mb-2">불량유형</label>
                    <select
                      value={data.productionResult.defectType}
                      onChange={(e) => setData({ ...data, productionResult: { ...data.productionResult, defectType: e.target.value } })}
                      className="w-full px-2 py-2 border rounded-lg"
                    >
                      <option value="">선택</option>
                      <option>치수불량</option>
                      <option>성형불량</option>
                      <option>표면불량</option>
                      <option>기타</option>
                    </select>
                  </div>
                  <div className="p-4 bg-yellow-50 rounded-lg text-center">
                    <label className="block text-sm text-yellow-600 mb-2">총 중량(kg)</label>
                    <input
                      type="number"
                      value={data.productionResult.totalWeight || ''}
                      onChange={(e) => setData({ ...data, productionResult: { ...data.productionResult, totalWeight: e.target.value ? parseFloat(e.target.value) : null } })}
                      className="w-20 px-2 py-2 border rounded-lg text-xl font-bold text-center mx-auto"
                    />
                  </div>
                </div>
              </Card>
              <Card title="비고">
                <textarea
                  value={data.remarks}
                  onChange={(e) => setData({ ...data, remarks: e.target.value })}
                  rows={4}
                  placeholder="특이사항이나 메모를 입력하세요..."
                  className="w-full px-3 py-2 border rounded-lg"
                />
              </Card>
            </div>
          )}
        </div>

        {/* 하단 버튼 */}
        <div className="flex gap-2 p-4 border-t bg-gray-50">
          <Button variant="outline" onClick={onClose}>취소</Button>
          <Button variant="primary" className="flex-1" onClick={handleSave}>
            <Check className="w-4 h-4" /> 저장
          </Button>
        </div>
      </div>
    </div>
  );
};

// ============ 절곡 작업일지 에디터 ============
const BendingWorkLogEditor = ({ workOrder, order, workLog, onClose, onSave }) => {
  const [data, setData] = useState(workLog || createWorkLogDataLocal(workOrder, order, '절곡'));
  const [activeSection, setActiveSection] = useState('header');

  // ★ 투입자재에서 LOT 정보 가져오기 함수
  const getMaterialLotByCode = (materialCode) => {
    const materialInputs = workOrder?.materialInputs || [];
    const input = materialInputs.find(m => m.materialCode === materialCode);
    return input?.lotNo || '';
  };

  // ★ 재질별 LOT 매핑 (EGI/SUS)
  const getEgiLot = () => getMaterialLotByCode('EGI-1.55T') || getMaterialLotByCode('EGI-1.6T') || getMaterialLotByCode('EGI-1.2T');
  const getSusLot = () => getMaterialLotByCode('SUS-1.2T') || getMaterialLotByCode('SUS-1.5T');

  // ★ 투입자재 LOT 자동 반영 (컴포넌트 마운트 시)
  useEffect(() => {
    const materialInputs = workOrder?.materialInputs || [];
    if (materialInputs.length > 0 && !workLog) {
      const egiLot = getEgiLot();
      const susLot = getSusLot();

      setData(prev => {
        const updated = { ...prev };

        // 가이드레일 LOT 자동 입력
        if (updated.guideRail) {
          updated.guideRail = updated.guideRail.map(item => ({
            ...item,
            inputLotNo: item.inputLotNo || (item.material?.includes('SUS') ? susLot : egiLot)
          }));
        }

        // 하단마감재 LOT 자동 입력
        if (updated.bottomFinish) {
          updated.bottomFinish = updated.bottomFinish.map(item => ({
            ...item,
            inputLotNo: item.inputLotNo || (item.material?.includes('SUS') ? susLot : egiLot)
          }));
        }

        // 케이스 LOT 자동 입력
        if (updated.caseBox) {
          updated.caseBox = {
            ...updated.caseBox,
            inputLotNo: updated.caseBox.inputLotNo || (updated.caseBox.material?.includes('SUS') ? susLot : egiLot)
          };
        }

        // 연기차단재 LOT 자동 입력
        if (updated.smokeBarrier) {
          updated.smokeBarrier = updated.smokeBarrier.map(item => ({
            ...item,
            inputLotNo: item.inputLotNo || getMaterialLotByCode('SM-SMOKE-01') || egiLot
          }));
        }

        return updated;
      });
    }
  }, [workOrder?.materialInputs]);

  const sections = [
    { id: 'header', label: '기본정보' },
    { id: 'developedParts', label: '전개도 상세' },
    { id: 'developedDrawing', label: '전개도 도면' },
    { id: 'guideRail', label: '1. 벽면형' },
    { id: 'bottomFinish', label: '2. 하단마감재' },
    { id: 'caseBox', label: '3. 케이스' },
    { id: 'smokeBarrier', label: '4. 연기차단재' },
    { id: 'summary', label: '생산량 합계' },
  ];

  const updateField = (path, value) => {
    setData(prev => {
      const newData = { ...prev };
      const keys = path.split('.');
      let current = newData;
      for (let i = 0; i < keys.length - 1; i++) {
        if (keys[i].includes('[')) {
          const [key, idx] = keys[i].split('[');
          current = current[key][parseInt(idx.replace(']', ''))];
        } else {
          current = current[keys[i]];
        }
      }
      const lastKey = keys[keys.length - 1];
      if (lastKey.includes('[')) {
        const [key, idx] = lastKey.split('[');
        current[key][parseInt(idx.replace(']', ''))] = value;
      } else {
        current[lastKey] = value;
      }
      return newData;
    });
  };

  const handleSave = () => {
    onSave?.(data);
    alert('✅ 작업일지가 저장되었습니다.');
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl w-full max-w-5xl max-h-[90vh] flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b bg-gray-50">
          <div className="flex items-center gap-3">
            <Clipboard className="w-6 h-6 text-blue-600" />
            <div>
              <h2 className="text-lg font-bold">작업일지 입력</h2>
              <p className="text-sm text-gray-500">{workOrder?.workOrderNo} · 절곡 공정</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-gray-200 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
            ✕
          </button>
        </div>

        {/* 섹션 탭 */}
        <div className="flex border-b overflow-x-auto">
          {sections.map(section => (
            <button
              key={section.id}
              onClick={() => setActiveSection(section.id)}
              className={`px-4 py-2 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${activeSection === section.id
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
                }`}
            >
              {section.label}
            </button>
          ))}
        </div>

        {/* 콘텐츠 */}
        <div className="flex-1 overflow-y-auto p-4">
          {/* 기본정보 섹션 */}
          {activeSection === 'header' && (
            <div className="space-y-6">
              <div className="grid grid-cols-2 gap-6">
                <Card title="신청업체">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">발주일</label>
                      <input
                        type="date"
                        value={data.orderDate}
                        onChange={(e) => updateField('orderDate', e.target.value)}
                        className="w-full px-3 py-2 border rounded-lg"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">업체명</label>
                      <input
                        type="text"
                        value={data.company}
                        onChange={(e) => updateField('company', e.target.value)}
                        className="w-full px-3 py-2 border rounded-lg"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">담당자</label>
                      <input
                        type="text"
                        value={data.manager}
                        onChange={(e) => updateField('manager', e.target.value)}
                        className="w-full px-3 py-2 border rounded-lg"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">연락처</label>
                      <input
                        type="text"
                        value={data.contact}
                        onChange={(e) => updateField('contact', e.target.value)}
                        className="w-full px-3 py-2 border rounded-lg"
                      />
                    </div>
                  </div>
                </Card>

                <Card title="신청내용">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">현장명</label>
                      <input
                        type="text"
                        value={data.siteName}
                        onChange={(e) => updateField('siteName', e.target.value)}
                        className="w-full px-3 py-2 border rounded-lg"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">작업일자</label>
                      <input
                        type="date"
                        value={data.workDate}
                        onChange={(e) => updateField('workDate', e.target.value)}
                        className="w-full px-3 py-2 border rounded-lg"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">제품 LOT NO</label>
                      <input
                        type="text"
                        value={data.productLotNo}
                        onChange={(e) => updateField('productLotNo', e.target.value)}
                        className="w-full px-3 py-2 border rounded-lg font-mono"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">생산담당자</label>
                      <input
                        type="text"
                        value={data.productionManager}
                        onChange={(e) => updateField('productionManager', e.target.value)}
                        className="w-full px-3 py-2 border rounded-lg"
                      />
                    </div>
                  </div>
                </Card>
              </div>

              <Card title="제품정보">
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">제품명</label>
                    <input
                      type="text"
                      value={data.productCode}
                      onChange={(e) => updateField('productCode', e.target.value)}
                      className="w-full px-3 py-2 border rounded-lg"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">제품유형</label>
                    <select
                      value={data.productType}
                      onChange={(e) => updateField('productType', e.target.value)}
                      className="w-full px-3 py-2 border rounded-lg"
                    >
                      <option>와이어</option>
                      <option>체인</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">마감유형</label>
                    <select
                      value={data.finishType}
                      onChange={(e) => updateField('finishType', e.target.value)}
                      className="w-full px-3 py-2 border rounded-lg"
                    >
                      <option>SUS마감</option>
                      <option>EGI마감</option>
                      <option>도장마감</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">레일유형</label>
                    <select
                      value={data.railType}
                      onChange={(e) => updateField('railType', e.target.value)}
                      className="w-full px-3 py-2 border rounded-lg"
                    >
                      <option>벽면형(120·70)</option>
                      <option>측면형(120·120)</option>
                    </select>
                  </div>
                </div>
              </Card>
            </div>
          )}

          {/* 전개도 상세 섹션 */}
          {activeSection === 'developedParts' && (
            <Card title="전개도 상세정보">
              <p className="text-sm text-gray-500 mb-4">품목 등록 기준 절곡 부품 전개 치수</p>
              <div className="overflow-x-auto">
                <table className="w-full text-sm border">
                  <thead className="bg-gray-100">
                    <tr>
                      <th className="px-3 py-2 text-left text-xs font-medium border">품번</th>
                      <th className="px-3 py-2 text-left text-xs font-medium border">품명</th>
                      <th className="px-3 py-2 text-left text-xs font-medium border">재질</th>
                      <th className="px-3 py-2 text-center text-xs font-medium border">전개폭</th>
                      <th className="px-3 py-2 text-center text-xs font-medium border">길이</th>
                      <th className="px-3 py-2 text-center text-xs font-medium border">수량</th>
                      <th className="px-3 py-2 text-center text-xs font-medium border">중량(kg)</th>
                      <th className="px-3 py-2 text-left text-xs font-medium border">전개치수</th>
                      <th className="px-3 py-2 text-left text-xs font-medium border">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(data.developedParts || [
                      { itemCode: 'SD30', itemName: '엘바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 4, weight: 0.9, dimensions: '75', note: '' },
                      { itemCode: 'SD31', itemName: '하장바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 1.158, dimensions: '67→126→165→178→193', note: '' },
                      { itemCode: 'SD32', itemName: '짜부가스켓', material: 'E.G.I 0.8T', totalWidth: 500, length: 3000, qty: 4, weight: 0.576, dimensions: '48', note: '80*4,50*8' },
                      { itemCode: 'SD33', itemName: '50평철', material: 'E.G.I 1.2T', totalWidth: 500, length: 3000, qty: 2, weight: 0.3, dimensions: '50', note: '' },
                      { itemCode: 'SD34', itemName: '전면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.764, dimensions: '120→499→553→588', note: '500*380' },
                      { itemCode: 'SD35', itemName: '린텔박스', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 0.504, dimensions: '84→138→168', note: 'S/BOX' },
                      { itemCode: 'SD36', itemName: '밑면 점검구', material: 'E.G.I 1.6T', totalWidth: 500, length: 2438, qty: 2, weight: 0.98, dimensions: '90→240→310', note: '500*380' },
                      { itemCode: 'SD37', itemName: '후면코너부', material: 'E.G.I 1.2T', totalWidth: 500, length: 1219, qty: 4, weight: 0.45, dimensions: '35→85→120', note: '' },
                    ]).map((part, idx) => (
                      <tr key={idx} className="hover:bg-gray-50">
                        <td className="px-3 py-2 border font-mono text-xs">{part.itemCode}</td>
                        <td className="px-3 py-2 border">{part.itemName}</td>
                        <td className="px-3 py-2 border text-gray-600">{part.material}</td>
                        <td className="px-3 py-2 border text-center">{part.totalWidth}</td>
                        <td className="px-3 py-2 border text-center">{part.length}</td>
                        <td className="px-3 py-2 border text-center font-medium">{part.qty}</td>
                        <td className="px-3 py-2 border text-center">{part.weight}</td>
                        <td className="px-3 py-2 border text-xs text-blue-600">{part.dimensions}</td>
                        <td className="px-3 py-2 border text-gray-500 text-xs">{part.note}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </Card>
          )}

          {/* 전개도 도면 섹션 */}
          {activeSection === 'developedDrawing' && (
            <Card title="전개도 도면">
              <p className="text-sm text-gray-500 mb-4">절곡 부품별 전개도 (바라시)</p>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                {/* 엘바 전개도 */}
                <div className="border rounded-lg p-3 bg-gray-50">
                  <p className="text-xs font-medium text-gray-700 mb-2">엘바 (SD30)</p>
                  <div className="bg-white border rounded p-2 h-24 flex items-center justify-center">
                    <svg viewBox="0 0 100 60" className="w-full h-full">
                      <rect x="10" y="20" width="80" height="20" fill="none" stroke="#333" strokeWidth="1" />
                      <line x1="10" y1="25" x2="90" y2="25" stroke="#666" strokeWidth="0.5" strokeDasharray="2,2" />
                      <text x="50" y="50" textAnchor="middle" fontSize="6" fill="#666">75</text>
                    </svg>
                  </div>
                  <p className="text-xs text-gray-500 mt-1 text-center">E.G.I 1.6T / L:3000</p>
                </div>

                {/* 하장바 전개도 */}
                <div className="border rounded-lg p-3 bg-gray-50">
                  <p className="text-xs font-medium text-gray-700 mb-2">하장바 (SD31)</p>
                  <div className="bg-white border rounded p-2 h-24 flex items-center justify-center">
                    <svg viewBox="0 0 100 60" className="w-full h-full">
                      <path d="M10,40 L20,40 L20,20 L40,20 L40,30 L60,30 L60,20 L80,20 L80,40 L90,40" fill="none" stroke="#333" strokeWidth="1" />
                      <text x="50" y="55" textAnchor="middle" fontSize="5" fill="#666">67→126→165→178→193</text>
                    </svg>
                  </div>
                  <p className="text-xs text-gray-500 mt-1 text-center">E.G.I 1.6T / L:3000</p>
                </div>

                {/* 전면판 전개도 */}
                <div className="border rounded-lg p-3 bg-gray-50">
                  <p className="text-xs font-medium text-gray-700 mb-2">전면판 (SD34)</p>
                  <div className="bg-white border rounded p-2 h-24 flex items-center justify-center">
                    <svg viewBox="0 0 100 60" className="w-full h-full">
                      <path d="M10,45 L10,15 L25,15 L25,25 L75,25 L75,15 L90,15 L90,45 Z" fill="none" stroke="#333" strokeWidth="1" />
                      <text x="50" y="55" textAnchor="middle" fontSize="5" fill="#666">120→499→553→588</text>
                    </svg>
                  </div>
                  <p className="text-xs text-gray-500 mt-1 text-center">E.G.I 1.6T / L:3000</p>
                </div>

                {/* 린텔박스 전개도 */}
                <div className="border rounded-lg p-3 bg-gray-50">
                  <p className="text-xs font-medium text-gray-700 mb-2">린텔박스 (SD35)</p>
                  <div className="bg-white border rounded p-2 h-24 flex items-center justify-center">
                    <svg viewBox="0 0 100 60" className="w-full h-full">
                      <path d="M15,40 L15,20 L35,20 L35,30 L65,30 L65,20 L85,20 L85,40" fill="none" stroke="#333" strokeWidth="1" />
                      <text x="50" y="55" textAnchor="middle" fontSize="5" fill="#666">84→138→168</text>
                    </svg>
                  </div>
                  <p className="text-xs text-gray-500 mt-1 text-center">E.G.I 1.6T / L:3000</p>
                </div>

                {/* 짜부가스켓 전개도 */}
                <div className="border rounded-lg p-3 bg-gray-50">
                  <p className="text-xs font-medium text-gray-700 mb-2">짜부가스켓 (SD32)</p>
                  <div className="bg-white border rounded p-2 h-24 flex items-center justify-center">
                    <svg viewBox="0 0 100 60" className="w-full h-full">
                      <rect x="20" y="20" width="60" height="20" fill="none" stroke="#333" strokeWidth="1" />
                      <text x="50" y="50" textAnchor="middle" fontSize="6" fill="#666">48</text>
                    </svg>
                  </div>
                  <p className="text-xs text-gray-500 mt-1 text-center">E.G.I 0.8T / L:3000</p>
                </div>

                {/* 50평철 전개도 */}
                <div className="border rounded-lg p-3 bg-gray-50">
                  <p className="text-xs font-medium text-gray-700 mb-2">50평철 (SD33)</p>
                  <div className="bg-white border rounded p-2 h-24 flex items-center justify-center">
                    <svg viewBox="0 0 100 60" className="w-full h-full">
                      <rect x="15" y="22" width="70" height="16" fill="none" stroke="#333" strokeWidth="1" />
                      <text x="50" y="50" textAnchor="middle" fontSize="6" fill="#666">50</text>
                    </svg>
                  </div>
                  <p className="text-xs text-gray-500 mt-1 text-center">E.G.I 1.2T / L:3000</p>
                </div>

                {/* 밑면 점검구 전개도 */}
                <div className="border rounded-lg p-3 bg-gray-50">
                  <p className="text-xs font-medium text-gray-700 mb-2">밑면 점검구 (SD36)</p>
                  <div className="bg-white border rounded p-2 h-24 flex items-center justify-center">
                    <svg viewBox="0 0 100 60" className="w-full h-full">
                      <path d="M10,40 L10,25 L30,25 L30,15 L70,15 L70,25 L90,25 L90,40" fill="none" stroke="#333" strokeWidth="1" />
                      <text x="50" y="55" textAnchor="middle" fontSize="5" fill="#666">90→240→310</text>
                    </svg>
                  </div>
                  <p className="text-xs text-gray-500 mt-1 text-center">E.G.I 1.6T / L:2438</p>
                </div>

                {/* 후면코너부 전개도 */}
                <div className="border rounded-lg p-3 bg-gray-50">
                  <p className="text-xs font-medium text-gray-700 mb-2">후면코너부 (SD37)</p>
                  <div className="bg-white border rounded p-2 h-24 flex items-center justify-center">
                    <svg viewBox="0 0 100 60" className="w-full h-full">
                      <path d="M20,40 L20,25 L40,25 L40,15 L60,15 L60,25 L80,25 L80,40" fill="none" stroke="#333" strokeWidth="1" />
                      <text x="50" y="55" textAnchor="middle" fontSize="5" fill="#666">35→85→120</text>
                    </svg>
                  </div>
                  <p className="text-xs text-gray-500 mt-1 text-center">E.G.I 1.2T / L:1219</p>
                </div>
              </div>
            </Card>
          )}

          {/* 1. 벽면형 섹션 */}
          {activeSection === 'guideRail' && (
            <Card title="1. 작업 내역 - 벽면형 (120·70)">
              <p className="text-sm text-gray-500 mb-4">절곡 상세도면 참조</p>
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-3 py-2 text-left">세부품명</th>
                    <th className="px-3 py-2 text-left">재질</th>
                    <th className="px-3 py-2 text-left">입고 & 생산 LOT NO</th>
                    <th className="px-3 py-2 text-left">길이/규격</th>
                    <th className="px-3 py-2 text-right">수량</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {data.guideRail.map((item, idx) => (
                    <tr key={item.id}>
                      <td className="px-3 py-2 font-medium">{item.name}</td>
                      <td className="px-3 py-2 text-gray-600">{item.material}</td>
                      <td className="px-3 py-2">
                        <input
                          type="text"
                          value={item.inputLotNo}
                          onChange={(e) => {
                            const newGuideRail = [...data.guideRail];
                            newGuideRail[idx].inputLotNo = e.target.value;
                            setData({ ...data, guideRail: newGuideRail });
                          }}
                          placeholder="LOT 번호 입력"
                          className="w-full px-2 py-1 border rounded text-sm font-mono"
                        />
                      </td>
                      <td className="px-3 py-2 text-gray-600">{item.spec}</td>
                      <td className="px-3 py-2">
                        <input
                          type="number"
                          value={item.qty || ''}
                          onChange={(e) => {
                            const newGuideRail = [...data.guideRail];
                            newGuideRail[idx].qty = e.target.value ? parseInt(e.target.value) : null;
                            setData({ ...data, guideRail: newGuideRail });
                          }}
                          className="w-20 px-2 py-1 border rounded text-right"
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </Card>
          )}

          {/* 2. 하단마감재 섹션 */}
          {activeSection === 'bottomFinish' && (
            <Card title="2. 하단마감재 [60·40]">
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-3 py-2 text-left">세부품명</th>
                    <th className="px-3 py-2 text-left">재질</th>
                    <th className="px-3 py-2 text-left">입고 & 생산 LOT NO</th>
                    <th className="px-3 py-2 text-center" colSpan={2}>길이/규격</th>
                    <th className="px-3 py-2 text-center" colSpan={2}>수량</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {data.bottomFinish.map((item, idx) => (
                    <tr key={item.id}>
                      <td className="px-3 py-2 font-medium">{item.name}</td>
                      <td className="px-3 py-2 text-gray-600">{item.material}</td>
                      <td className="px-3 py-2">
                        <input
                          type="text"
                          value={item.inputLotNo}
                          onChange={(e) => {
                            const newData = [...data.bottomFinish];
                            newData[idx].inputLotNo = e.target.value;
                            setData({ ...data, bottomFinish: newData });
                          }}
                          placeholder="LOT 번호"
                          className="w-full px-2 py-1 border rounded text-sm font-mono"
                        />
                      </td>
                      {item.rows.map((row, ridx) => (
                        <React.Fragment key={ridx}>
                          <td className="px-2 py-2 text-gray-600 text-center">{row.spec}</td>
                          <td className="px-2 py-2">
                            <input
                              type="number"
                              value={row.qty || ''}
                              onChange={(e) => {
                                const newData = [...data.bottomFinish];
                                newData[idx].rows[ridx].qty = e.target.value ? parseInt(e.target.value) : null;
                                setData({ ...data, bottomFinish: newData });
                              }}
                              className="w-16 px-2 py-1 border rounded text-right"
                            />
                          </td>
                        </React.Fragment>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </Card>
          )}

          {/* 3. 케이스 섹션 */}
          {activeSection === 'caseBox' && (
            <Card title={`3.1 케이스 [${data.caseBox.spec}]`}>
              <div className="mb-4 grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">재질</label>
                  <input
                    type="text"
                    value={data.caseBox.material}
                    onChange={(e) => setData({ ...data, caseBox: { ...data.caseBox, material: e.target.value } })}
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">입고 & 생산 LOT NO</label>
                  <input
                    type="text"
                    value={data.caseBox.inputLotNo}
                    onChange={(e) => setData({ ...data, caseBox: { ...data.caseBox, inputLotNo: e.target.value } })}
                    placeholder="LOT 번호 입력"
                    className="w-full px-3 py-2 border rounded-lg font-mono"
                  />
                </div>
              </div>
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-3 py-2 text-left">세부품명</th>
                    <th className="px-3 py-2 text-center">길이/규격</th>
                    <th className="px-3 py-2 text-right">수량</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {data.caseBox.items.map((item, idx) => (
                    item.rows ? (
                      item.rows.map((row, ridx) => (
                        <tr key={`${item.id}-${ridx}`}>
                          {ridx === 0 && <td className="px-3 py-2 font-medium" rowSpan={item.rows.length}>{item.name}</td>}
                          <td className="px-3 py-2 text-center text-gray-600">{row.spec}</td>
                          <td className="px-3 py-2">
                            <input
                              type="number"
                              value={row.qty || ''}
                              onChange={(e) => {
                                const newItems = [...data.caseBox.items];
                                newItems[idx].rows[ridx].qty = e.target.value ? parseInt(e.target.value) : null;
                                setData({ ...data, caseBox: { ...data.caseBox, items: newItems } });
                              }}
                              className="w-20 px-2 py-1 border rounded text-right float-right"
                            />
                          </td>
                        </tr>
                      ))
                    ) : (
                      <tr key={item.id}>
                        <td className="px-3 py-2 font-medium">{item.name}</td>
                        <td className="px-3 py-2 text-center text-gray-600">{item.spec}</td>
                        <td className="px-3 py-2">
                          <input
                            type="number"
                            value={item.qty || ''}
                            onChange={(e) => {
                              const newItems = [...data.caseBox.items];
                              newItems[idx].qty = e.target.value ? parseInt(e.target.value) : null;
                              setData({ ...data, caseBox: { ...data.caseBox, items: newItems } });
                            }}
                            className="w-20 px-2 py-1 border rounded text-right float-right"
                          />
                        </td>
                      </tr>
                    )
                  ))}
                </tbody>
              </table>
            </Card>
          )}

          {/* 4. 연기차단재 섹션 */}
          {activeSection === 'smokeBarrier' && (
            <Card title="4. 연기차단재">
              <div className="space-y-6">
                {/* 레일용 */}
                <div>
                  <h4 className="font-medium mb-2">{data.smokeBarrier.rail.name}</h4>
                  <div className="grid grid-cols-2 gap-4 mb-3">
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">재질</label>
                      <input
                        type="text"
                        value={data.smokeBarrier.rail.material}
                        readOnly
                        className="w-full px-3 py-2 border rounded-lg bg-gray-50"
                      />
                    </div>
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">입고 LOT NO</label>
                      <input
                        type="text"
                        value={data.smokeBarrier.rail.inputLotNo}
                        onChange={(e) => setData({
                          ...data,
                          smokeBarrier: {
                            ...data.smokeBarrier,
                            rail: { ...data.smokeBarrier.rail, inputLotNo: e.target.value }
                          }
                        })}
                        placeholder="LOT 번호 입력"
                        className="w-full px-3 py-2 border rounded-lg font-mono"
                      />
                    </div>
                  </div>
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-3 py-2 text-left">길이</th>
                        <th className="px-3 py-2 text-right">수량</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {data.smokeBarrier.rail.rows.map((row, idx) => (
                        <tr key={idx}>
                          <td className="px-3 py-2">{row.spec}</td>
                          <td className="px-3 py-2">
                            <input
                              type="number"
                              value={row.qty || ''}
                              onChange={(e) => {
                                const newRows = [...data.smokeBarrier.rail.rows];
                                newRows[idx].qty = e.target.value ? parseInt(e.target.value) : null;
                                setData({
                                  ...data,
                                  smokeBarrier: {
                                    ...data.smokeBarrier,
                                    rail: { ...data.smokeBarrier.rail, rows: newRows }
                                  }
                                });
                              }}
                              className="w-20 px-2 py-1 border rounded text-right float-right"
                            />
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* 케이스용 */}
                <div>
                  <h4 className="font-medium mb-2">{data.smokeBarrier.caseItem.name}</h4>
                  <div className="grid grid-cols-3 gap-4">
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">입고 LOT NO</label>
                      <input
                        type="text"
                        value={data.smokeBarrier.caseItem.inputLotNo}
                        onChange={(e) => setData({
                          ...data,
                          smokeBarrier: {
                            ...data.smokeBarrier,
                            caseItem: { ...data.smokeBarrier.caseItem, inputLotNo: e.target.value }
                          }
                        })}
                        placeholder="LOT 번호 입력"
                        className="w-full px-3 py-2 border rounded-lg font-mono"
                      />
                    </div>
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">규격</label>
                      <input
                        type="text"
                        value={data.smokeBarrier.caseItem.spec}
                        readOnly
                        className="w-full px-3 py-2 border rounded-lg bg-gray-50"
                      />
                    </div>
                    <div>
                      <label className="block text-sm text-gray-600 mb-1">수량</label>
                      <input
                        type="number"
                        value={data.smokeBarrier.caseItem.qty || ''}
                        onChange={(e) => setData({
                          ...data,
                          smokeBarrier: {
                            ...data.smokeBarrier,
                            caseItem: { ...data.smokeBarrier.caseItem, qty: e.target.value ? parseInt(e.target.value) : null }
                          }
                        })}
                        className="w-full px-3 py-2 border rounded-lg text-right"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </Card>
          )}

          {/* 생산량 합계 섹션 */}
          {activeSection === 'summary' && (
            <div className="space-y-6">
              <Card title="생산량 합계 (kg)">
                <div className="grid grid-cols-2 gap-6">
                  <div className="p-6 bg-gray-50 rounded-lg text-center">
                    <label className="block text-sm font-medium text-gray-700 mb-2">SUS</label>
                    <input
                      type="number"
                      value={data.totalProduction.sus || ''}
                      onChange={(e) => setData({
                        ...data,
                        totalProduction: { ...data.totalProduction, sus: e.target.value ? parseFloat(e.target.value) : null }
                      })}
                      placeholder="0"
                      className="w-32 px-4 py-3 border rounded-lg text-2xl font-bold text-center mx-auto"
                    />
                    <span className="text-gray-500 ml-2">kg</span>
                  </div>
                  <div className="p-6 bg-green-50 rounded-lg text-center">
                    <label className="block text-sm font-medium text-gray-700 mb-2">EGI</label>
                    <input
                      type="number"
                      value={data.totalProduction.egi || ''}
                      onChange={(e) => setData({
                        ...data,
                        totalProduction: { ...data.totalProduction, egi: e.target.value ? parseFloat(e.target.value) : null }
                      })}
                      placeholder="0"
                      className="w-32 px-4 py-3 border rounded-lg text-2xl font-bold text-center mx-auto"
                    />
                    <span className="text-gray-500 ml-2">kg</span>
                  </div>
                </div>
              </Card>

              <Card title="비고">
                <textarea
                  value={data.remarks}
                  onChange={(e) => setData({ ...data, remarks: e.target.value })}
                  rows={4}
                  placeholder="특이사항이나 메모를 입력하세요..."
                  className="w-full px-3 py-2 border rounded-lg"
                />
              </Card>
            </div>
          )}
        </div>

        {/* 하단 버튼 */}
        <div className="flex gap-2 p-4 border-t bg-gray-50">
          <Button variant="outline" onClick={onClose}>취소</Button>
          <Button variant="outline" onClick={() => alert('인쇄 미리보기')}>
            <Printer className="w-4 h-4" /> 미리보기
          </Button>
          <Button variant="primary" className="flex-1" onClick={handleSave}>
            <Check className="w-4 h-4" /> 저장
          </Button>
        </div>
      </div>
    </div>
  );
};

// ★ 작업일지 템플릿 선택/미리보기 모달 (공정별 ISO 인증용 문서 양식 연결)
const WorkLogTemplateModal = ({ workOrder, order, workLog, workResults, onClose }) => {
  const processType = workOrder?.processType || workOrder?.processName || '절곡';

  // 공정별 작업일지 템플릿 매핑 (문서양식관리 코드와 동일)
  const templateOptions = {
    '절곡': { code: 'WL-FLD', name: '절곡 작업일지', dept: '절곡 생산부서' },
    '슬랫': { code: 'WL-SLT', name: '슬랫 작업일지', dept: '슬랫 생산부서' },
    '스크린': { code: 'WL-SCR', name: '스크린 작업일지', dept: '스크린 생산부서' },
    '재고생산': { code: 'WL-STK', name: '절곡품 재고생산 작업일지', dept: '절곡 생산부서' },
    '포밍': { code: 'WL-STK', name: '포밍 작업일지', dept: '포밍 생산부서' },
    '포장': { code: 'WL-PKG', name: '포장 작업일지', dept: '포장 생산부서' },
  };

  const currentTemplate = templateOptions[processType] || templateOptions['절곡'];

  // 작업일지 데이터 생성
  const generateWorkLogDataFromWorkOrder = () => {
    const now = new Date();
    const materialInputs = workOrder?.materialInputs || []; // ★ 투입 자재 LOT 정보

    // LOT 번호 조회 헬퍼 함수
    const getInputLotNo = (materialCode) => {
      const input = materialInputs.find(m => m.materialCode === materialCode);
      return input?.lotNo || '';
    };

    return {
      workLogNo: `WL-${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}-${workOrder.workOrderNo?.split('-').pop() || '001'}`,
      workOrderNo: workOrder.workOrderNo,
      productLotNo: workOrder.productionLot || workOrder.lotNo || `LOT-${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}-001`,
      customerName: workOrder.customerName || order?.customerName || '경동건설',
      siteName: workOrder.siteName || order?.siteName || '강남현장',
      processType: processType,
      workDate: now.toISOString().split('T')[0],
      writer: workOrder.assignee || '작업자',
      totalQty: workOrder.totalQty || workOrder.items?.reduce((sum, i) => sum + (i.qty || 0), 0) || 50,
      goodQty: workOrder.goodQty || workOrder.totalQty || 50,
      // ★ 투입 자재 LOT 정보
      materialInputs: materialInputs,
      inputLotNos: {
        '스크린원단': getInputLotNo('SCR-MAT-001'),
        '미싱실': getInputLotNo('SCR-MAT-004'),
        '앤드락': getInputLotNo('SCR-MAT-002'),
        '슬랫코일': getInputLotNo('SLT-MAT-001'),
        'EGI철판': getInputLotNo('EGI-1.55T'),
        'SUS철판': getInputLotNo('SUS-1.2T'),
        '연기차단재': getInputLotNo('BND-SMK-001'),
      },
      defectQty: workOrder.defectQty || 0,
      yieldRate: 98.5,
      // 공정별 상세 데이터
      items: workOrder.items || [
        { itemNo: 1, itemName: '케이스-전면부', spec: 'EGI 1.55T', qty: 16, unit: 'EA' },
        { itemNo: 2, itemName: '케이스-후면부', spec: 'EGI 1.55T', qty: 16, unit: 'EA' },
      ],
      // 결재라인
      approvalLine: {
        writer: { name: workOrder.assignee || '작업자', date: now.toISOString().split('T')[0], signed: true },
        reviewer: { name: '검토자', date: '', signed: false },
        approver: { name: '승인자', date: '', signed: false },
      },
      // 검사 데이터
      inspectionData: {
        appearance: '양호',
        dimensions: '합격',
        judgment: '합격',
      },
      // ★ 스크린 공정: 망규격×폭규격 매트릭스 자동 계산 (수주 데이터 기반)
      screenProductionMatrix: (() => {
        if (processType !== '스크린') return null;
        // 망규격 (원단 폭): 1016, 1270, 1524, 1780
        // 폭규격 (제품 폭): 900, 1000, 1100, 1200, 1300, 1400, 1500
        const meshSizes = ['1016', '1270', '1524', '1780'];
        const widthSizes = ['900', '1000', '1100', '1200', '1300', '1400', '1500'];
        const matrix = {};

        // 수주 품목에서 규격 분석 (W, H 기준)
        const items = workOrder.items || order?.items || [];
        items.forEach(item => {
          // productionSpec 필드 우선 참조 (수주 품목 구조)
          const spec = item.productionSpec || {};
          const w = spec.prodWidth || spec.openWidth || item.width || item.productionSizeW ||
            (item.spec ? parseInt(item.spec.split('×')[0]) : 0) || 0;
          const h = spec.prodHeight || spec.openHeight || item.height || item.productionSizeH ||
            (item.spec ? parseInt(item.spec.split('×')[1]) : 0) || 0;
          const qty = item.qty || 1;

          // 원단 폭 선택 (높이 기준 - 원단을 세로로 사용)
          let meshSize = '1016';
          if (h > 1600) meshSize = '1780';
          else if (h > 1400) meshSize = '1524';
          else if (h > 1100) meshSize = '1270';

          // 제품 폭 선택 (가장 가까운 값)
          let widthSize = '900';
          for (const ws of widthSizes) {
            if (w <= parseInt(ws) + 50) {
              widthSize = ws;
              break;
            }
          }
          if (w > 1500) widthSize = '1500';

          const key = `${meshSize}_${widthSize}`;
          matrix[key] = (matrix[key] || 0) + qty;
        });

        // 샘플 데이터 (수주 품목이 없는 경우)
        if (Object.keys(matrix).length === 0) {
          matrix['1016_1200'] = 12;
          matrix['1270_1100'] = 8;
        }

        return matrix;
      })(),
      // ★ 슬랫 공정: LOT별 생산내역 자동 계산
      slatProductionLots: (() => {
        if (processType !== '슬랫') return null;
        const items = workOrder.items || order?.items || [];
        const lots = [];

        // 수주 품목에서 슬랫 수량 계산 (높이 기반 절단매수)
        items.forEach((item, idx) => {
          // productionSpec 필드 우선 참조 (수주 품목 구조)
          const spec = item.productionSpec || {};
          const h = spec.prodHeight || spec.openHeight || item.height || item.productionSizeH ||
            (item.spec ? parseInt(item.spec.split('×')[1]) : 0) || 3000;
          const qty = item.qty || 1;
          const slatHeight = 75; // 슬랫 높이 (mm)
          const slatCount = Math.ceil(h / slatHeight) * qty;

          lots.push({
            lotNo: item.lotNo || `LOT-SLT-${now.getFullYear()}-${String(idx + 1).padStart(3, '0')}`,
            spec: '100mm',
            color: item.color || '백색',
            productionQty: slatCount,
            defectQty: Math.floor(slatCount * 0.004), // 0.4% 불량
            yieldRate: 99.6,
          });
        });

        // 샘플 데이터 (수주 품목이 없는 경우)
        if (lots.length === 0) {
          lots.push({
            lotNo: `LOT-SLT-${now.getFullYear()}-001`,
            spec: '100mm',
            color: '백색',
            productionQty: 450,
            defectQty: 2,
            yieldRate: 99.6,
          });
        }

        return lots;
      })(),
    };
  };

  const handlePrint = () => {
    // 실제 문서양식관리의 템플릿을 사용하여 출력
    const printContent = document.getElementById('work-log-template-preview');
    if (printContent) {
      const printWindow = window.open('', '_blank');
      printWindow.document.write(`
        <html>
          <head>
            <title>${currentTemplate.name} - ${workOrder.workOrderNo}</title>
            <style>
              @page { size: A4; margin: 8mm; }
              @media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; } }
              body { font-family: 'Malgun Gothic', sans-serif; font-size: 10px; margin: 0; padding: 0; }
              table { border-collapse: collapse; width: 100%; }
              th, td { border: 1px solid #000; padding: 4px 6px; }
              .bg-gray-100 { background-color: #f3f4f6 !important; }
              .bg-gray-200 { background-color: #e5e7eb !important; }
              .bg-yellow-300 { background-color: #fcd34d !important; }
              .font-bold { font-weight: bold; }
              .text-center { text-align: center; }
            </style>
          </head>
          <body>${printContent.innerHTML}</body>
        </html>
      `);
      printWindow.document.close();
      printWindow.print();
    }
  };

  const data = workLog || generateWorkLogDataFromWorkOrder();

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-2 md:p-4">
      <div className="bg-white rounded-xl w-full max-w-5xl max-h-[95vh] flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b">
          <div className="flex items-center gap-3">
            <Clipboard className="w-6 h-6 text-blue-500" />
            <div>
              <h3 className="font-bold text-gray-900">{currentTemplate.name}</h3>
              <p className="text-xs text-gray-500">{currentTemplate.code} · {currentTemplate.dept}</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="primary" onClick={handlePrint}>
              <Printer className="w-4 h-4" /> 출력
            </Button>
            <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg">
              <X className="w-5 h-5 text-gray-500" />
            </button>
          </div>
        </div>

        {/* 작업 정보 요약 */}
        <div className="p-4 bg-gray-50 border-b">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div>
              <span className="text-gray-500">작업지시번호</span>
              <p className="font-mono font-bold">{workOrder.workOrderNo}</p>
            </div>
            <div>
              <span className="text-gray-500">공정</span>
              <p className="font-bold">{processType}</p>
            </div>
            <div>
              <span className="text-gray-500">발주처</span>
              <p className="font-medium">{data.customerName}</p>
            </div>
            <div>
              <span className="text-gray-500">현장명</span>
              <p className="font-medium">{data.siteName}</p>
            </div>
          </div>
        </div>

        {/* 미리보기 영역 - 공정별 전용 템플릿 */}
        <div className="flex-1 overflow-auto p-4" id="work-log-template-preview">
          {/* 절곡 작업일지 템플릿 (WL-FLD 스타일 - 문서양식관리 동일) */}
          {processType === '절곡' && (
            <div className="bg-white mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '8mm', fontSize: '11px' }}>
              {/* 문서 헤더 */}
              <div className="text-center mb-4">
                <h1 className="text-2xl font-bold tracking-widest">절 곡 작 업 일 지</h1>
                <p className="text-sm text-gray-500 mt-1">{data.workLogNo}</p>
              </div>

              {/* 결재라인 (우측 상단) - APR-2LINE 스타일 */}
              <div className="flex justify-end mb-4">
                <table className="border-collapse border border-gray-400 text-sm">
                  <thead>
                    <tr className="bg-gray-100">
                      <th className="border border-gray-400 px-4 py-1 font-medium w-20">작성</th>
                      <th className="border border-gray-400 px-4 py-1 font-medium w-20">검토</th>
                      <th className="border border-gray-400 px-4 py-1 font-medium w-20">승인</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td className="border border-gray-400 px-4 py-3 h-16 text-center align-middle">
                        {data.approvalLine.writer.signed ? (
                          <div className="text-center">
                            <span className="text-red-500 font-bold">{data.approvalLine.writer.name}</span>
                            <p className="text-xs text-gray-500">{data.approvalLine.writer.date}</p>
                          </div>
                        ) : (
                          <span className="text-gray-300">(인)</span>
                        )}
                      </td>
                      <td className="border border-gray-400 px-4 py-3 h-16 text-center align-middle">
                        <span className="text-gray-300">(인)</span>
                      </td>
                      <td className="border border-gray-400 px-4 py-3 h-16 text-center align-middle">
                        <span className="text-gray-300">(인)</span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>

              {/* 기본 정보 테이블 (WL-HEADER-INFO 블록) */}
              <table className="w-full border-collapse border border-gray-400 mb-4 text-sm">
                <tbody>
                  <tr>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 w-24 text-left font-medium">신청업체</th>
                    <td className="border border-gray-400 px-3 py-2">{data.customerName}</td>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 w-24 text-left font-medium">작성일</th>
                    <td className="border border-gray-400 px-3 py-2">{data.workDate}</td>
                  </tr>
                  <tr>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">현장명</th>
                    <td className="border border-gray-400 px-3 py-2">{data.siteName}</td>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">작성자</th>
                    <td className="border border-gray-400 px-3 py-2">{data.writer}</td>
                  </tr>
                  <tr>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">작업지시번호</th>
                    <td className="border border-gray-400 px-3 py-2" colSpan={3}>{data.workOrderNo}</td>
                  </tr>
                  <tr>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">LOT번호</th>
                    <td className="border border-gray-400 px-3 py-2" colSpan={3}>{data.productLotNo}</td>
                  </tr>
                </tbody>
              </table>

              {/* ★ 부품 작업 내역 (FoldWorkLogTable 스타일) */}
              <div className="mb-4">
                <div className="bg-black text-white px-3 py-1 font-bold text-sm">부 품 작 업 내 역</div>
                <table className="w-full border-collapse text-xs">
                  <thead>
                    <tr className="bg-gray-100">
                      <th className="border border-gray-400 px-2 py-1 font-bold w-10">NO</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-20">품목코드</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold">품명</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-24">재질</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-16">전폭</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-16">길이</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-14">수량</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-16">중량(kg)</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold">전개치수</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(workOrder.developedParts || data.developedParts || [
                      { itemCode: 'SD30', itemName: '엘바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 4, weight: 0.9, dimensions: '75' },
                      { itemCode: 'SD31', itemName: '하장바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 1.158, dimensions: '67→126→165→178→193' },
                      { itemCode: 'SD32', itemName: '짜부가스켓', material: 'E.G.I 0.8T', totalWidth: 500, length: 3000, qty: 4, weight: 0.576, dimensions: '48' },
                    ]).map((part, idx) => (
                      <tr key={idx}>
                        <td className="border border-gray-400 px-2 py-1 text-center">{idx + 1}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center font-mono">{part.itemCode}</td>
                        <td className="border border-gray-400 px-2 py-1">{part.itemName}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center">{part.material}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center">{part.totalWidth}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center">{part.length}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center font-bold bg-yellow-50">{part.qty}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center">{part.weight}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center font-mono text-xs bg-yellow-50">{part.dimensions}</td>
                      </tr>
                    ))}
                    <tr className="bg-blue-100">
                      <td colSpan={6} className="border border-gray-400 px-2 py-1 text-right font-bold">총 생산량:</td>
                      <td className="border border-gray-400 px-2 py-1 text-center font-bold text-lg">
                        {(workOrder.developedParts || data.developedParts || []).reduce((sum, p) => sum + (p.qty || 0), 0) || 14}
                      </td>
                      <td className="border border-gray-400 px-2 py-1 text-center font-bold">
                        {(workOrder.developedParts || data.developedParts || []).reduce((sum, p) => sum + (p.weight || 0), 0).toFixed(2) || '5.20'} kg
                      </td>
                      <td className="border border-gray-400 px-2 py-1 text-center font-bold">EA</td>
                    </tr>
                  </tbody>
                </table>
              </div>

              {/* 생산실적 요약 (WL-SUMMARY 블록) */}
              <div className="mb-4">
                <div className="bg-black text-white px-3 py-1 font-bold text-sm">생 산 실 적 요 약</div>
                <div className="grid grid-cols-4 gap-0">
                  <div className="border border-gray-400 p-3 text-center">
                    <div className="text-xs text-gray-500">총 생산량</div>
                    <div className="text-xl font-bold">{data.totalQty}</div>
                  </div>
                  <div className="border border-gray-400 p-3 text-center">
                    <div className="text-xs text-gray-500">양품 수량</div>
                    <div className="text-xl font-bold text-green-600">{data.goodQty}</div>
                  </div>
                  <div className="border border-gray-400 p-3 text-center">
                    <div className="text-xs text-gray-500">불량 수량</div>
                    <div className="text-xl font-bold text-red-600">{data.defectQty}</div>
                  </div>
                  <div className="border border-gray-400 p-3 text-center">
                    <div className="text-xs text-gray-500">양품율</div>
                    <div className="text-xl font-bold">{data.yieldRate}%</div>
                  </div>
                </div>
              </div>

              {/* 철판 사용 내역 (WL-MATERIAL-USAGE 블록) - ★ 실제 투입 LOT 데이터 표시 */}
              <div className="mb-4">
                <div className="bg-black text-white px-3 py-1 font-bold text-sm">철 판 사 용 내 역 (입고 LOT 정보)</div>
                <table className="w-full border-collapse text-xs">
                  <thead>
                    <tr className="bg-gray-100">
                      <th className="border border-gray-400 px-2 py-1 font-bold w-10">NO</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold">자재명</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-24">규격</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-24">입고LOT</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-16">사용량</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-12">단위</th>
                    </tr>
                  </thead>
                  <tbody>
                    {/* ★ 실제 materialInputs 데이터 또는 샘플 데이터 표시 */}
                    {(data.materialInputs?.length > 0 ? data.materialInputs : [
                      { materialName: 'E.G.I 철판', spec: '1.6T × 4\' × 8\'', lotNo: 'LOT-241201-01', qty: 5, unit: '매' },
                      { materialName: 'E.G.I 철판', spec: '1.2T × 4\' × 8\'', lotNo: 'LOT-241201-02', qty: 2, unit: '매' },
                      { materialName: 'E.G.I 철판', spec: '0.8T × 4\' × 8\'', lotNo: 'LOT-241201-03', qty: 3, unit: '매' },
                    ]).map((input, idx) => (
                      <tr key={idx}>
                        <td className="border border-gray-400 px-2 py-1 text-center">{idx + 1}</td>
                        <td className="border border-gray-400 px-2 py-1">{input.materialName}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center">{input.spec || '-'}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center font-mono text-blue-600">{input.lotNo}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center font-bold bg-yellow-50">{input.qty}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center">{input.unit || '매'}</td>
                      </tr>
                    ))}
                    <tr className="bg-blue-100">
                      <td colSpan={4} className="border border-gray-400 px-2 py-1 text-right font-bold">합 계:</td>
                      <td className="border border-gray-400 px-2 py-1 text-center font-bold text-lg">
                        {(data.materialInputs?.length > 0 ? data.materialInputs : [{ qty: 5 }, { qty: 2 }, { qty: 3 }]).reduce((sum, i) => sum + (i.qty || 0), 0)}
                      </td>
                      <td className="border border-gray-400 px-2 py-1 text-center font-bold">매</td>
                    </tr>
                  </tbody>
                </table>
              </div>

              {/* 특기사항 */}
              <div className="mb-4">
                <div className="bg-black text-white px-3 py-1 font-bold text-sm">특 기 사 항</div>
                <div className="border border-gray-400 p-3 min-h-[60px] text-sm">
                  <p className="text-gray-500">특이사항 없음</p>
                </div>
              </div>
            </div>
          )}

          {/* 슬랫 작업일지 템플릿 (WL-SLT 스타일 - 문서양식관리 동일) */}
          {processType === '슬랫' && (
            <div className="bg-white mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '8mm', fontSize: '11px' }}>
              {/* 문서 헤더 */}
              <div className="text-center mb-4">
                <h1 className="text-2xl font-bold tracking-widest">슬 랫 작 업 일 지</h1>
                <p className="text-sm text-gray-500 mt-1">{data.workLogNo}</p>
              </div>

              {/* 결재라인 (우측 상단) - APR-2LINE 스타일 */}
              <div className="flex justify-end mb-4">
                <table className="border-collapse border border-gray-400 text-sm">
                  <thead>
                    <tr className="bg-gray-100">
                      <th className="border border-gray-400 px-4 py-1 font-medium w-20">작성</th>
                      <th className="border border-gray-400 px-4 py-1 font-medium w-20">검토</th>
                      <th className="border border-gray-400 px-4 py-1 font-medium w-20">승인</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td className="border border-gray-400 px-4 py-3 h-16 text-center align-middle">
                        {data.approvalLine.writer.signed ? (
                          <div className="text-center">
                            <span className="text-red-500 font-bold">{data.approvalLine.writer.name}</span>
                            <p className="text-xs text-gray-500">{data.approvalLine.writer.date}</p>
                          </div>
                        ) : (
                          <span className="text-gray-300">(인)</span>
                        )}
                      </td>
                      <td className="border border-gray-400 px-4 py-3 h-16 text-center align-middle">
                        <span className="text-gray-300">(인)</span>
                      </td>
                      <td className="border border-gray-400 px-4 py-3 h-16 text-center align-middle">
                        <span className="text-gray-300">(인)</span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>

              {/* 기본 정보 테이블 (WL-HEADER-INFO 블록) */}
              <table className="w-full border-collapse border border-gray-400 mb-4 text-sm">
                <tbody>
                  <tr>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 w-24 text-left font-medium">신청업체</th>
                    <td className="border border-gray-400 px-3 py-2">{data.customerName}</td>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 w-24 text-left font-medium">작성일</th>
                    <td className="border border-gray-400 px-3 py-2">{data.workDate}</td>
                  </tr>
                  <tr>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">현장명</th>
                    <td className="border border-gray-400 px-3 py-2">{data.siteName}</td>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">작성자</th>
                    <td className="border border-gray-400 px-3 py-2">{data.writer}</td>
                  </tr>
                  <tr>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">작업지시번호</th>
                    <td className="border border-gray-400 px-3 py-2" colSpan={3}>{data.workOrderNo}</td>
                  </tr>
                  <tr>
                    <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-left font-medium">LOT번호</th>
                    <td className="border border-gray-400 px-3 py-2" colSpan={3}>{data.productLotNo}</td>
                  </tr>
                </tbody>
              </table>

              {/* ★ LOT별 생산내역 (SlatWorkLogTable 스타일) */}
              <div className="mb-4">
                <div className="bg-black text-white px-3 py-1 font-bold text-sm">L O T 별 생 산 내 역</div>
                <table className="w-full border-collapse text-xs">
                  <thead>
                    <tr className="bg-gray-100">
                      <th className="border border-gray-400 px-2 py-1 font-bold w-10">NO</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold">LOT번호</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-20">규격</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-16">색상</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-16">생산량</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-14">불량</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-14">양품</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-14">양품율</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(data.slatProductionLots || [
                      { lotNo: 'SLT-241210-01', spec: '100mm', color: '화이트', productionQty: 500, defectQty: 5 },
                      { lotNo: 'SLT-241210-02', spec: '100mm', color: '아이보리', productionQty: 300, defectQty: 3 },
                    ]).map((lot, idx) => {
                      const good = lot.productionQty - lot.defectQty;
                      const rate = lot.productionQty > 0 ? Math.round((good / lot.productionQty) * 100) : 0;
                      return (
                        <tr key={lot.lotNo}>
                          <td className="border border-gray-400 px-2 py-1 text-center">{idx + 1}</td>
                          <td className="border border-gray-400 px-2 py-1 font-mono">{lot.lotNo}</td>
                          <td className="border border-gray-400 px-2 py-1 text-center">{lot.spec}</td>
                          <td className="border border-gray-400 px-2 py-1 text-center">{lot.color}</td>
                          <td className="border border-gray-400 px-2 py-1 text-center font-bold bg-yellow-50">{lot.productionQty}</td>
                          <td className="border border-gray-400 px-2 py-1 text-center text-red-600">{lot.defectQty}</td>
                          <td className="border border-gray-400 px-2 py-1 text-center text-green-600">{good}</td>
                          <td className="border border-gray-400 px-2 py-1 text-center">{rate}%</td>
                        </tr>
                      );
                    })}
                    <tr className="bg-blue-100 font-bold">
                      <td colSpan={4} className="border border-gray-400 px-2 py-1 text-right">합 계:</td>
                      <td className="border border-gray-400 px-2 py-1 text-center">
                        {(data.slatProductionLots || [{ productionQty: 500 }, { productionQty: 300 }]).reduce((sum, l) => sum + (l.productionQty || 0), 0)}
                      </td>
                      <td className="border border-gray-400 px-2 py-1 text-center text-red-600">
                        {(data.slatProductionLots || [{ defectQty: 5 }, { defectQty: 3 }]).reduce((sum, l) => sum + (l.defectQty || 0), 0)}
                      </td>
                      <td className="border border-gray-400 px-2 py-1 text-center text-green-600">
                        {(() => {
                          const lots = data.slatProductionLots || [{ productionQty: 500, defectQty: 5 }, { productionQty: 300, defectQty: 3 }];
                          const totalProd = lots.reduce((sum, l) => sum + (l.productionQty || 0), 0);
                          const totalDefect = lots.reduce((sum, l) => sum + (l.defectQty || 0), 0);
                          return totalProd - totalDefect;
                        })()}
                      </td>
                      <td className="border border-gray-400 px-2 py-1 text-center text-lg">
                        {(() => {
                          const lots = data.slatProductionLots || [{ productionQty: 500, defectQty: 5 }, { productionQty: 300, defectQty: 3 }];
                          const totalProd = lots.reduce((sum, l) => sum + (l.productionQty || 0), 0);
                          const totalDefect = lots.reduce((sum, l) => sum + (l.defectQty || 0), 0);
                          return totalProd > 0 ? Math.round(((totalProd - totalDefect) / totalProd) * 100) : 0;
                        })()}%
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>

              {/* 생산실적 요약 (WL-SUMMARY 블록) */}
              <div className="mb-4">
                <div className="bg-black text-white px-3 py-1 font-bold text-sm">생 산 실 적 요 약</div>
                <div className="grid grid-cols-4 gap-0">
                  <div className="border border-gray-400 p-3 text-center">
                    <div className="text-xs text-gray-500">총 생산량</div>
                    <div className="text-xl font-bold">{data.totalQty}</div>
                  </div>
                  <div className="border border-gray-400 p-3 text-center">
                    <div className="text-xs text-gray-500">양품 수량</div>
                    <div className="text-xl font-bold text-green-600">{data.goodQty}</div>
                  </div>
                  <div className="border border-gray-400 p-3 text-center">
                    <div className="text-xs text-gray-500">불량 수량</div>
                    <div className="text-xl font-bold text-red-600">{data.defectQty}</div>
                  </div>
                  <div className="border border-gray-400 p-3 text-center">
                    <div className="text-xs text-gray-500">양품율</div>
                    <div className="text-xl font-bold">{data.yieldRate}%</div>
                  </div>
                </div>
              </div>

              {/* 슬랫 자재 사용 내역 (WL-MATERIAL-USAGE 블록) - ★ 실제 투입 LOT 데이터 표시 */}
              <div className="mb-4">
                <div className="bg-black text-white px-3 py-1 font-bold text-sm">슬 랫 자 재 사 용 내 역 (입고 LOT 정보)</div>
                <table className="w-full border-collapse text-xs">
                  <thead>
                    <tr className="bg-gray-100">
                      <th className="border border-gray-400 px-2 py-1 font-bold w-10">NO</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold">자재명</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-24">규격</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-24">입고LOT</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-16">사용량</th>
                      <th className="border border-gray-400 px-2 py-1 font-bold w-12">단위</th>
                    </tr>
                  </thead>
                  <tbody>
                    {/* ★ 실제 materialInputs 데이터 또는 샘플 데이터 표시 */}
                    {(data.materialInputs?.length > 0 ? data.materialInputs : [
                      { materialName: '슬랫 원자재', spec: '100mm × 6M', lotNo: 'LOT-SLT-RAW-01', qty: 50, unit: 'EA' },
                      { materialName: '슬랫 캡', spec: '100mm', lotNo: 'LOT-CAP-01', qty: 100, unit: 'EA' },
                    ]).map((input, idx) => (
                      <tr key={idx}>
                        <td className="border border-gray-400 px-2 py-1 text-center">{idx + 1}</td>
                        <td className="border border-gray-400 px-2 py-1">{input.materialName}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center">{input.spec || '-'}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center font-mono text-blue-600">{input.lotNo}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center font-bold bg-yellow-50">{input.qty}</td>
                        <td className="border border-gray-400 px-2 py-1 text-center">{input.unit || 'EA'}</td>
                      </tr>
                    ))}
                    <tr className="bg-blue-100">
                      <td colSpan={4} className="border border-gray-400 px-2 py-1 text-right font-bold">합 계:</td>
                      <td className="border border-gray-400 px-2 py-1 text-center font-bold text-lg">
                        {(data.materialInputs?.length > 0 ? data.materialInputs : [{ qty: 50 }, { qty: 100 }]).reduce((sum, i) => sum + (i.qty || 0), 0)}
                      </td>
                      <td className="border border-gray-400 px-2 py-1 text-center font-bold">EA</td>
                    </tr>
                  </tbody>
                </table>
              </div>

              {/* 특기사항 */}
              <div className="mb-4">
                <div className="bg-black text-white px-3 py-1 font-bold text-sm">특 기 사 항</div>
                <div className="border border-gray-400 p-3 min-h-[60px] text-sm">
                  <p className="text-gray-500">특이사항 없음</p>
                </div>
              </div>
            </div>
          )}

          {/* 스크린 작업일지 템플릿 (WL-SCR 스타일 - 엑셀 양식 기반 업데이트) */}
          {processType === '스크린' && (
            <div className="bg-white mx-auto" style={{ width: '297mm', minHeight: '210mm', padding: '6mm', fontSize: '10px' }}>
              {/* ===== 문서 헤더: KD 로고 + 타이틀 + 결재란 ===== */}
              <table className="w-full border-collapse mb-2" style={{ border: '2px solid black' }}>
                <tbody>
                  <tr>
                    {/* KD 로고 */}
                    <td rowSpan={3} className="text-center align-middle p-2" style={{ width: '90px', borderRight: '1px solid black' }}>
                      <div className="text-3xl font-black text-blue-700">KD</div>
                      <div className="text-xs font-bold">경동기업</div>
                      <div style={{ fontSize: '7px' }} className="text-gray-500">KYUNGDONG COMPANY</div>
                    </td>
                    {/* 타이틀 + 부서 */}
                    <td rowSpan={3} className="text-center align-middle" style={{ borderRight: '1px solid black' }}>
                      <div className="text-3xl font-black tracking-widest">작 업 일 지</div>
                      <div className="text-sm text-gray-600 mt-1">WL-SCR</div>
                      <div className="bg-green-200 text-green-800 text-sm font-bold px-3 py-1 inline-block mt-1">스크린 생산부서</div>
                    </td>
                    {/* 결재란 헤더 */}
                    <td rowSpan={3} className="text-center align-middle font-bold" style={{ width: '25px', borderRight: '1px solid black' }}>
                      <div className="text-sm">결</div>
                      <div className="text-sm mt-3">재</div>
                    </td>
                    {/* 결재란 - 작성/검토/승인 */}
                    <td className="text-center text-xs font-semibold py-1 bg-gray-100" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>작성</td>
                    <td className="text-center text-xs font-semibold py-1 bg-gray-100" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검토</td>
                    <td className="text-center text-xs font-semibold py-1 bg-gray-100" style={{ width: '60px', borderBottom: '1px solid black' }}>승인</td>
                  </tr>
                  <tr>
                    <td className="text-center py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black', fontSize: '10px' }}>
                      {data.approvalLine?.writer?.name || '손금주'}
                    </td>
                    <td className="text-center py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black', fontSize: '10px' }}></td>
                    <td className="text-center py-2" style={{ borderBottom: '1px solid black', fontSize: '10px' }}></td>
                  </tr>
                  <tr>
                    <td className="text-center py-1" style={{ borderRight: '1px solid black', fontSize: '9px' }}>
                      <span className="text-blue-600 font-medium">판매/손금주</span>
                    </td>
                    <td className="text-center py-1" style={{ borderRight: '1px solid black', fontSize: '9px' }}>
                      <span>생산</span>
                    </td>
                    <td className="text-center py-1" style={{ fontSize: '9px' }}>
                      <span className="bg-yellow-200 px-2 py-0.5 font-bold">품질</span>
                    </td>
                  </tr>
                </tbody>
              </table>

              {/* ===== 신청업체 + 신청내용 ===== */}
              <table className="w-full border-collapse mb-2" style={{ fontSize: '10px', border: '2px solid black' }}>
                <tbody>
                  <tr>
                    <td colSpan={4} className="bg-gray-200 text-center font-bold py-1" style={{ borderBottom: '1px solid black', letterSpacing: '8px' }}>신 청 업 체</td>
                    <td colSpan={4} className="bg-gray-200 text-center font-bold py-1" style={{ borderBottom: '1px solid black', letterSpacing: '8px' }}>신 청 내 용</td>
                  </tr>
                  <tr>
                    <td className="bg-gray-100 text-center font-medium py-1.5" style={{ width: '8%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 일</td>
                    <td className="py-1.5 px-2" style={{ width: '17%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                      {(() => {
                        const d = new Date(data.workDate || new Date());
                        const days = ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'];
                        return `${d.getFullYear()}년 ${d.getMonth() + 1}월 ${d.getDate()}일 ${days[d.getDay()]}`;
                      })()}
                    </td>
                    <td className="bg-gray-100 text-center font-medium py-1.5" style={{ width: '8%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>현 장 명</td>
                    <td className="py-1.5 px-2" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                      <span className="text-blue-600 font-bold">{data.siteName || '은행동 현장 A동'}</span>
                    </td>
                  </tr>
                  <tr>
                    <td className="bg-gray-100 text-center font-medium py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>업 체 명</td>
                    <td className="py-1.5 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{data.customerName || '대운기업'}</td>
                    <td className="bg-gray-100 text-center font-medium py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>작 업 일 자</td>
                    <td className="py-1.5 px-2" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                      {data.workDate || '2025.    .   '}
                    </td>
                  </tr>
                  <tr>
                    <td className="bg-gray-100 text-center font-medium py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>담 당 자</td>
                    <td className="py-1.5 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{data.manager || '이양게 소장'}</td>
                    <td className="bg-yellow-200 text-center font-bold py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>제품 LOT NO</td>
                    <td className="py-1.5 px-2 font-bold text-blue-600" colSpan={2} style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                      {data.productLotNo || 'KD-SA-251203-07'}
                    </td>
                  </tr>
                  <tr>
                    <td className="bg-gray-100 text-center font-medium py-1.5" style={{ borderRight: '1px solid black' }}>연 락 처</td>
                    <td className="py-1.5 px-2" style={{ borderRight: '1px solid black' }}>{data.contact || ''}</td>
                    <td className="bg-gray-100 text-center font-medium py-1.5" style={{ borderRight: '1px solid black' }}>생산담당자</td>
                    <td className="py-1.5 px-2" colSpan={2}>{data.writer || ''}</td>
                  </tr>
                </tbody>
              </table>

              {/* ===== ■ 작업 내역 테이블 (엑셀 양식) ===== */}
              <div className="mb-2">
                <div className="font-bold text-sm mb-1">■ 작업 내역</div>
                <table className="w-full border-collapse" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <thead>
                    <tr>
                      <th rowSpan={2} className="bg-gray-100 text-center font-bold px-1 py-1" style={{ width: '5%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>일련<br />번호</th>
                      <th rowSpan={2} className="bg-gray-100 text-center font-bold px-1 py-1" style={{ width: '10%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>입고 LOT NO.</th>
                      <th rowSpan={2} className="bg-gray-100 text-center font-bold px-1 py-1" style={{ width: '8%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>제품명</th>
                      <th rowSpan={2} className="bg-gray-100 text-center font-bold px-1 py-1" style={{ width: '10%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>부호</th>
                      <th colSpan={3} className="bg-gray-100 text-center font-bold px-1 py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>제작사이즈(mm)</th>
                      <th colSpan={5} className="bg-gray-100 text-center font-bold px-1 py-1" style={{ borderBottom: '1px solid black' }}>규격(매수)</th>
                    </tr>
                    <tr>
                      <th className="bg-yellow-100 text-center font-bold px-1 py-1" style={{ width: '8%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>가로</th>
                      <th className="bg-yellow-100 text-center font-bold px-1 py-1" style={{ width: '8%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>세로</th>
                      <th className="bg-yellow-100 text-center font-bold px-1 py-1" style={{ width: '6%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>나머지<br />높이</th>
                      <th className="bg-pink-100 text-center font-bold px-1 py-1" style={{ width: '7%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>1220</th>
                      <th className="bg-gray-100 text-center font-bold px-1 py-1" style={{ width: '7%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>900</th>
                      <th className="bg-gray-100 text-center font-bold px-1 py-1" style={{ width: '7%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>600</th>
                      <th className="bg-gray-100 text-center font-bold px-1 py-1" style={{ width: '7%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>400</th>
                      <th className="bg-gray-100 text-center font-bold px-1 py-1" style={{ width: '7%', borderBottom: '1px solid black' }}>300</th>
                    </tr>
                  </thead>
                  <tbody>
                    {/* 작업 데이터 행 - 샘플 또는 실제 데이터 */}
                    {(data.workItems?.length > 0 ? data.workItems : [
                      { seq: '01', lotNo: '', productName: '실리카', code: 'A동 FSS-01', width: 6240, height: 3250, remainHeight: 1030, qty1220: 2, qty900: 0, qty600: 0, qty400: 0, qty300: 0 },
                      { seq: '02', lotNo: '', productName: '실리카', code: 'A동 FSS-02', width: 7960, height: 3250, remainHeight: 1030, qty1220: 2, qty900: 0, qty600: 0, qty400: 0, qty300: 0 },
                      { seq: '03', lotNo: '', productName: '실리카', code: 'A동 FSS-03', width: 3650, height: 3250, remainHeight: 1030, qty1220: 2, qty900: 0, qty600: 0, qty400: 0, qty300: 0 },
                      { seq: '04', lotNo: '', productName: '실리카', code: 'A동 FSS-04', width: 4130, height: 3250, remainHeight: 1030, qty1220: 2, qty900: 0, qty600: 0, qty400: 0, qty300: 0 },
                      { seq: '05', lotNo: '', productName: '실리카', code: 'A동 FSS-05', width: 4130, height: 3250, remainHeight: 1030, qty1220: 2, qty900: 0, qty600: 0, qty400: 0, qty300: 0 },
                    ]).map((item, idx) => (
                      <tr key={idx}>
                        <td className="text-center py-2 font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.seq || String(idx + 1).padStart(2, '0')}</td>
                        <td className="text-center py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.lotNo || ''}</td>
                        <td className="text-center py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.productName}</td>
                        <td className="text-center py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.code}</td>
                        <td className="text-center py-2 font-bold text-green-600 bg-yellow-50" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.width}</td>
                        <td className="text-center py-2 font-bold text-green-600 bg-yellow-50" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.height}</td>
                        <td className="text-center py-2 font-bold text-red-600 bg-yellow-50" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.remainHeight}</td>
                        <td className="text-center py-2 font-bold bg-pink-50" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.qty1220 || ''}</td>
                        <td className="text-center py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.qty900 || ''}</td>
                        <td className="text-center py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.qty600 || ''}</td>
                        <td className="text-center py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.qty400 || ''}</td>
                        <td className="text-center py-2" style={{ borderBottom: '1px solid black' }}>{item.qty300 || ''}</td>
                      </tr>
                    ))}
                    {/* 합계 행 */}
                    <tr className="bg-yellow-100">
                      <td colSpan={7} className="text-center font-bold py-2" style={{ borderRight: '1px solid black', letterSpacing: '8px' }}>합 계</td>
                      <td className="text-center font-bold py-2 text-lg" style={{ borderRight: '1px solid black' }}>
                        {(data.workItems?.length > 0 ? data.workItems : [{ qty1220: 2 }, { qty1220: 2 }, { qty1220: 2 }, { qty1220: 2 }, { qty1220: 2 }]).reduce((sum, i) => sum + (i.qty1220 || 0), 0) || 10}
                      </td>
                      <td className="text-center font-bold py-2" style={{ borderRight: '1px solid black' }}>
                        {(data.workItems || []).reduce((sum, i) => sum + (i.qty900 || 0), 0) || ''}
                      </td>
                      <td className="text-center font-bold py-2" style={{ borderRight: '1px solid black' }}>
                        {(data.workItems || []).reduce((sum, i) => sum + (i.qty600 || 0), 0) || ''}
                      </td>
                      <td className="text-center font-bold py-2" style={{ borderRight: '1px solid black' }}>
                        {(data.workItems || []).reduce((sum, i) => sum + (i.qty400 || 0), 0) || ''}
                      </td>
                      <td className="text-center font-bold py-2">
                        {(data.workItems || []).reduce((sum, i) => sum + (i.qty300 || 0), 0) || ''}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>

              {/* ===== 내화실 입고 LOT.NO + 사용량 ===== */}
              <div className="flex gap-2 mb-2">
                {/* 내화실 입고 LOT.NO */}
                <div style={{ width: '40%' }}>
                  <table className="w-full border-collapse" style={{ fontSize: '9px', border: '2px solid black' }}>
                    <tbody>
                      <tr>
                        <td className="bg-yellow-200 font-bold px-2 py-2">내화실 입고 LOT.NO</td>
                        <td className="px-2 py-2">{data.fireLotNo || ''}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>

                {/* 사용량(M) + 사용량(㎡) */}
                <div style={{ width: '60%' }}>
                  <table className="w-full border-collapse" style={{ fontSize: '9px', border: '2px solid black' }}>
                    <tbody>
                      <tr>
                        <td rowSpan={3} className="bg-gray-100 text-center font-bold px-2 py-1" style={{ width: '18%', borderRight: '1px solid black' }}>사용량<br />(M)</td>
                        <td className="text-center px-2 py-1" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>1220</td>
                        <td className="text-center px-2 py-1 font-bold" style={{ width: '20%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                          {data.usage1220m || '52.22'}
                        </td>
                        <td className="text-center px-2 py-1" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>400</td>
                        <td className="text-center px-2 py-1" style={{ width: '20%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>{data.usage400m || ''}</td>
                        <td rowSpan={3} className="bg-orange-100 text-center font-bold px-2 py-1" style={{ width: '18%', borderLeft: '2px solid black' }}>
                          사용량<br />(㎡)<br /><span className="text-lg">{data.totalUsageM2 || '63.71'}</span>
                        </td>
                      </tr>
                      <tr>
                        <td className="text-center px-2 py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>900</td>
                        <td className="text-center px-2 py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{data.usage900m || ''}</td>
                        <td className="text-center px-2 py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>300</td>
                        <td className="text-center px-2 py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{data.usage300m || ''}</td>
                      </tr>
                      <tr>
                        <td className="text-center px-2 py-1" style={{ borderRight: '1px solid black' }}>600</td>
                        <td className="text-center px-2 py-1" style={{ borderRight: '1px solid black' }}>{data.usage600m || ''}</td>
                        <td className="text-center px-2 py-1" style={{ borderRight: '1px solid black' }}></td>
                        <td className="text-center px-2 py-1" style={{ borderRight: '1px solid black' }}></td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

              {/* ===== 비고 (노란색 배너) ===== */}
              <div className="bg-yellow-400 text-center py-3 font-bold text-lg" style={{ border: '2px solid black' }}>
                [비 고] {data.note || '사이즈 착오없이 부탁드립니다'}
              </div>
            </div>
          )}

          {/* 재고생산 작업일지 템플릿 (WL-STK 스타일) */}
          {processType === '재고생산' && (
            <div className="bg-white mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '8mm', fontSize: '10px' }}>
              {/* 헤더 */}
              <table className="w-full border-collapse mb-2" style={{ border: '2px solid black' }}>
                <tbody>
                  <tr>
                    <td rowSpan="3" className="text-center align-middle p-2" style={{ width: '100px', borderRight: '1px solid black' }}>
                      <div className="text-3xl font-black text-blue-700">KD</div>
                      <div className="text-sm font-bold">경동기업</div>
                      <div style={{ fontSize: '8px' }} className="text-gray-500">KD FIRE DOOR COMPANY</div>
                    </td>
                    <td rowSpan="3" className="text-center align-middle" style={{ borderRight: '1px solid black' }}>
                      <div className="text-2xl font-black tracking-widest">절곡품 재고생산 작업일지</div>
                      <div className="text-base text-gray-600 mt-1">중간검사성적서</div>
                    </td>
                    <td rowSpan="3" className="text-center align-middle font-bold" style={{ width: '25px', borderRight: '1px solid black' }}>
                      <div className="text-sm">결</div>
                      <div className="text-sm mt-3">재</div>
                    </td>
                    <td className="text-center text-xs font-semibold py-1.5 bg-gray-100" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>작성</td>
                    <td className="text-center text-xs font-semibold py-1.5 bg-gray-100" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검토</td>
                    <td className="text-center text-xs font-semibold py-1.5 bg-gray-100" style={{ width: '70px', borderBottom: '1px solid black' }}>승인</td>
                  </tr>
                  <tr>
                    <td className="text-center py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black', fontSize: '10px' }}>{data.writer}<br />{data.workDate?.slice(5, 10).replace('-', '/')}</td>
                    <td className="text-center py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black', fontSize: '10px' }}></td>
                    <td className="text-center py-2" style={{ borderBottom: '1px solid black', fontSize: '10px' }}></td>
                  </tr>
                  <tr>
                    <td className="text-center py-1.5" style={{ borderRight: '1px solid black', fontSize: '10px' }}>
                      <span className="text-blue-600 font-bold">판매/개발자</span>
                    </td>
                    <td className="text-center py-1.5" style={{ borderRight: '1px solid black', fontSize: '10px' }}>
                      <span>생산</span>
                    </td>
                    <td className="text-center py-1.5" style={{ fontSize: '10px' }}>
                      <span className="bg-yellow-200 px-2 py-0.5 font-bold">품질</span>
                    </td>
                  </tr>
                </tbody>
              </table>

              {/* 제품 기본정보 */}
              <table className="w-full border-collapse mb-2" style={{ fontSize: '11px', border: '2px solid black' }}>
                <tbody>
                  <tr>
                    <td className="text-center bg-gray-200 font-bold py-2" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>품명</td>
                    <td className="px-3 py-2" style={{ width: '28%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>케이스 - 전면부</td>
                    <td className="text-center bg-yellow-300 font-bold py-2" style={{ width: '12%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>생산 LOT NO</td>
                    <td className="px-3 py-2 font-bold" style={{ borderBottom: '1px solid black' }}>{data.productLotNo}</td>
                  </tr>
                  <tr>
                    <td className="text-center bg-gray-200 font-bold py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>규격</td>
                    <td className="px-3 py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>EGI 1.55T (W576)</td>
                    <td className="text-center bg-gray-200 font-bold py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>로트크기</td>
                    <td className="px-3 py-2" style={{ borderBottom: '1px solid black' }}>{data.totalQty} EA</td>
                  </tr>
                  <tr>
                    <td className="text-center bg-gray-200 font-bold py-2" style={{ borderRight: '1px solid black' }}>검사일자</td>
                    <td className="px-3 py-2" style={{ borderRight: '1px solid black' }}>{data.workDate}</td>
                    <td className="text-center bg-gray-200 font-bold py-2" style={{ borderRight: '1px solid black' }}>검사자</td>
                    <td className="px-3 py-2">{data.writer}</td>
                  </tr>
                </tbody>
              </table>

              {/* 종합판정 */}
              <table className="w-full border-collapse" style={{ fontSize: '10px', border: '2px solid black' }}>
                <tbody>
                  <tr>
                    <td className="py-3 px-3" style={{ width: '70%', borderRight: '1px solid black', height: '60px', verticalAlign: 'top' }}>
                      <span className="font-bold">[부적합 내용]</span>
                    </td>
                    <td style={{ verticalAlign: 'top', padding: 0 }}>
                      <table className="w-full border-collapse">
                        <tbody>
                          <tr>
                            <td className="text-center bg-gray-100 font-bold py-1" style={{ borderBottom: '1px solid black' }}>종합판정</td>
                          </tr>
                          <tr>
                            <td className="text-center py-3">
                              <span className="text-2xl font-bold">합격</span>
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* 푸터 */}
        <div className="p-4 border-t bg-gray-50">
          <div className="flex items-center justify-between">
            <div className="text-xs text-gray-500">
              📋 문서코드: {currentTemplate.code} | ISO 인증용 작업일지
            </div>
            <div className="flex items-center gap-2">
              <Button variant="outline" onClick={onClose}>닫기</Button>
              <Button variant="primary" onClick={handlePrint}>
                <Printer className="w-4 h-4" /> 인쇄
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// 작업일지 출력용 시트
const WorkLogSheet = ({ workOrder, order, workLog, onClose }) => {
  const printRef = React.useRef(null);
  const processType = workOrder?.processType || workLog?.processType || '절곡';
  const data = workLog || createWorkLogDataLocal(workOrder, order, processType);

  const handlePrint = () => {
    const content = printRef.current;
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <html>
        <head>
          <title>작업일지 - ${data.productLotNo}</title>
          <style>
            @page { size: A4; margin: 10mm; }
            body { font-family: 'Malgun Gothic', sans-serif; font-size: 10px; margin: 0; padding: 10px; }
            table { border-collapse: collapse; width: 100%; margin-bottom: 10px; }
            th, td { border: 1px solid #000; padding: 4px 6px; text-align: center; }
            th { background-color: #f0f0f0; font-weight: bold; }
            .header { font-size: 18px; font-weight: bold; text-align: center; margin-bottom: 10px; }
            .section-title { background-color: #fff3cd; font-weight: bold; }
            .highlight { background-color: #ffff00; }
            .text-left { text-align: left; }
            .text-right { text-align: right; }
            .logo { font-size: 14px; font-weight: bold; }
          </style>
        </head>
        <body>${content.innerHTML}</body>
      </html>
    `);
    printWindow.document.close();
    printWindow.print();
  };

  const getDepartmentName = () => {
    switch (processType) {
      case '스크린': return '스크린 생산부서';
      case '슬랫': return '슬랫 생산부서';
      case '절곡': return '절곡 생산부서';
      case '재고생산': return '절곡 생산부서';
      default: return '생산부서';
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl w-full max-w-5xl max-h-[95vh] flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b">
          <h2 className="text-lg font-bold flex items-center gap-2">
            {processType === '재고생산' ? '재고생산 작업일지 (중간검사성적서)' : '작업일지 출력'}
            <span className={`text-sm px-2 py-1 rounded ${processType === '스크린' ? 'bg-blue-100 text-blue-700' :
                processType === '슬랫' ? 'bg-purple-100 text-purple-700' :
                  processType === '재고생산' ? 'bg-green-100 text-green-700' :
                    'bg-orange-100 text-orange-700'
              }`}>{processType}</span>
          </h2>
          <div className="flex gap-2">
            <Button variant="primary" onClick={handlePrint}>
              <Printer className="w-4 h-4" /> 인쇄
            </Button>
            <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg text-gray-400 hover:text-gray-600 text-xl font-bold">
              ✕
            </button>
          </div>
        </div>

        {/* 출력 미리보기 */}
        <div className="flex-1 overflow-auto p-4 bg-gray-100">
          <div ref={printRef} className="bg-white p-6 mx-auto" style={{ maxWidth: '210mm', minHeight: '297mm' }}>
            {/* 문서 헤더 (공통) */}
            <table className="mb-4">
              <tbody>
                <tr>
                  <td rowSpan="3" className="w-24 text-center border-2 border-black">
                    <div className="text-lg font-bold">[KD]</div>
                    <div className="text-xs">경동기업</div>
                  </td>
                  <td rowSpan="3" className="text-center border-2 border-black" style={{ width: '60%' }}>
                    <div className="text-2xl font-bold">
                      {processType === '재고생산' ? '절곡품 재고생산 작업일지' : '작 업 일 지'}
                    </div>
                    {processType === '재고생산' && (
                      <div className="text-sm text-gray-600 mt-1">(중간검사성적서)</div>
                    )}
                  </td>
                  <td className="text-center text-xs border border-black w-12">작성</td>
                  <td className="text-center text-xs border border-black w-12">검토</td>
                  <td className="text-center text-xs border border-black w-12">승인</td>
                </tr>
                <tr>
                  <td className="text-center border border-black h-8">{data.approval?.writer}</td>
                  <td className="text-center border border-black">{data.approval?.checker}</td>
                  <td className="text-center border border-black">{data.approval?.approver}</td>
                </tr>
                <tr>
                  <td colSpan="3" className="text-center text-xs border border-black">
                    <span className="text-blue-600">{processType === '재고생산' ? '판매/개발자' : '판매/전진'}</span> | 생산 | <span className="bg-yellow-200 px-1">품질</span>
                  </td>
                </tr>
              </tbody>
            </table>

            {/* 부서 */}
            <div className={`text-center font-bold mb-2 py-1 border border-black ${processType === '스크린' ? 'bg-blue-100' :
                processType === '슬랫' ? 'bg-purple-100' :
                  processType === '재고생산' ? 'bg-green-100' :
                    'bg-orange-100'
              }`}>
              {getDepartmentName()}
            </div>

            {/* 신청업체 / 신청내용 (공통) */}
            <table className="mb-2">
              <tbody>
                <tr className="bg-blue-100">
                  <td colSpan="2" className="font-bold text-center border border-black">신 청 업 체</td>
                  <td colSpan="2" className="font-bold text-center border border-black">신 청 내 용</td>
                </tr>
                <tr>
                  <td className="border border-black w-20 text-center bg-gray-50">발 주 일</td>
                  <td className="border border-black">{data.orderDate}</td>
                  <td className="border border-black w-20 text-center bg-gray-50">현 장 명</td>
                  <td className="border border-black font-bold">{data.siteName}</td>
                </tr>
                <tr>
                  <td className="border border-black text-center bg-gray-50">업 체 명</td>
                  <td className="border border-black">{data.company}</td>
                  <td className="border border-black text-center bg-gray-50">작업일자</td>
                  <td className="border border-black">{data.workDate}</td>
                </tr>
                <tr>
                  <td className="border border-black text-center bg-gray-50">담 당 자</td>
                  <td className="border border-black">{data.manager}</td>
                  <td className="border border-black text-center bg-gray-50">제품 LOT NO.</td>
                  <td className="border border-black font-mono">{data.productLotNo}</td>
                </tr>
                <tr>
                  <td className="border border-black text-center bg-gray-50">연 락 처</td>
                  <td className="border border-black">{data.contact}</td>
                  <td className="border border-black text-center bg-gray-50">생산담당자</td>
                  <td className="border border-black">{data.productionManager}</td>
                </tr>
              </tbody>
            </table>

            {/* 스크린 공정 내용 (첨부 이미지 기준 - 규격별 매수 테이블) */}
            {processType === '스크린' && (
              <>
                {/* ■ 작업 내역 테이블 (첨부 이미지 기준) */}
                <div className="text-sm font-bold mb-2">■ 작업 내역</div>
                <table className="mb-4 text-xs">
                  <thead>
                    <tr>
                      <th rowSpan="2" className="border border-black bg-gray-200 w-10">일련<br />번호</th>
                      <th rowSpan="2" className="border border-black bg-gray-200">입고 LOT NO.</th>
                      <th rowSpan="2" className="border border-black bg-gray-200">제품명</th>
                      <th rowSpan="2" className="border border-black bg-gray-200">부호</th>
                      <th colSpan="3" className="border border-black bg-gray-200">제작사이즈(mm)</th>
                      <th colSpan="5" className="border border-black bg-yellow-100">규격(매수)</th>
                    </tr>
                    <tr>
                      <th className="border border-black bg-gray-200">가로</th>
                      <th className="border border-black bg-gray-200">세로</th>
                      <th className="border border-black bg-gray-200">나머지<br />높이</th>
                      <th className="border border-black bg-yellow-100">1180</th>
                      <th className="border border-black bg-yellow-100">900</th>
                      <th className="border border-black bg-yellow-100">600</th>
                      <th className="border border-black bg-yellow-100">400</th>
                      <th className="border border-black bg-yellow-100">300</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(data.screenWorkItems || [
                      { no: 1, lotNo: '', productName: '와이어', partCode: '4층 FSS17', width: 7400, height: 2950 },
                      { no: 2, lotNo: '', productName: '와이어', partCode: '4층 FSS5', width: 4700, height: 2950 },
                      { no: 3, lotNo: '', productName: '와이어', partCode: '4층 FSS17A', width: 6790, height: 2950 },
                    ]).map((item, idx) => {
                      // 스크린 규격별 장수 자동 계산: 높이를 규격(1180, 900, 600, 400, 300)으로 분할
                      const specCalc = item.spec1180 !== undefined ? item : calculateScreenSpecSheetCount(item.height);
                      return (
                        <tr key={idx}>
                          <td className="border border-black text-center">{item.no || idx + 1}</td>
                          <td className="border border-black text-center font-mono">{item.lotNo}</td>
                          <td className="border border-black text-center">{item.productName}</td>
                          <td className="border border-black text-center">{item.partCode}</td>
                          <td className="border border-black text-center bg-yellow-200 font-bold">{item.width}</td>
                          <td className="border border-black text-center bg-yellow-200 font-bold">{item.height}</td>
                          <td className="border border-black text-center bg-yellow-200 font-bold">{item.remainHeight || specCalc.remainHeight}</td>
                          <td className="border border-black text-center bg-cyan-100 font-bold">{specCalc.spec1180 || ''}</td>
                          <td className="border border-black text-center bg-cyan-100 font-bold">{specCalc.spec900 || ''}</td>
                          <td className="border border-black text-center">{specCalc.spec600 || ''}</td>
                          <td className="border border-black text-center">{specCalc.spec400 || ''}</td>
                          <td className="border border-black text-center">{specCalc.spec300 || ''}</td>
                        </tr>
                      );
                    })}
                    {/* 합계 행 */}
                    <tr className="bg-gray-100 font-bold">
                      <td colSpan="7" className="border border-black text-center">합 계</td>
                      <td className="border border-black text-center">{data.screenTotals?.spec1180 || '22'}</td>
                      <td className="border border-black text-center">{data.screenTotals?.spec900 || '11'}</td>
                      <td className="border border-black text-center">{data.screenTotals?.spec600 || ''}</td>
                      <td className="border border-black text-center">{data.screenTotals?.spec400 || ''}</td>
                      <td className="border border-black text-center">{data.screenTotals?.spec300 || ''}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 내화실 입고 LOT.NO / 사용량 */}
                <table className="mb-4 text-xs">
                  <tbody>
                    <tr>
                      <td className="border border-black w-32 bg-blue-100 font-bold text-center">내화실 입고 LOT.NO</td>
                      <td className="border border-black" colSpan="5">{data.fireRoomLotNo || ''}</td>
                    </tr>
                    <tr>
                      <td rowSpan="2" className="border border-black bg-blue-100 font-bold text-center">사용량<br />(M)</td>
                      <td className="border border-black text-center w-16">1220</td>
                      <td className="border border-black text-center w-20">{data.usage?.['1220'] || '127.60'}</td>
                      <td className="border border-black text-center w-16">400</td>
                      <td className="border border-black text-center w-20">{data.usage?.['400'] || ''}</td>
                      <td rowSpan="2" className="border border-black bg-blue-50">
                        <div className="text-center">사용량<br />(m²)</div>
                        <div className="text-center font-bold text-lg">{data.totalUsageArea || '213.09'}</div>
                      </td>
                    </tr>
                    <tr>
                      <td className="border border-black text-center">900</td>
                      <td className="border border-black text-center">{data.usage?.['900'] || '63.8'}</td>
                      <td className="border border-black text-center">300</td>
                      <td className="border border-black text-center">{data.usage?.['300'] || ''}</td>
                    </tr>
                  </tbody>
                </table>
              </>
            )}

            {/* 슬랫 공정 내용 (첨부 이미지 기준 - 상세 작업내역 테이블) */}
            {processType === '슬랫' && (
              <>
                {/* ■ 작업내역 테이블 (첨부 이미지 기준) */}
                <div className="text-sm font-bold mb-2">■ 작업내역</div>
                <table className="mb-4 text-xs">
                  <thead>
                    <tr>
                      <th rowSpan="2" className="border border-black bg-yellow-100 w-10">일련<br />번호</th>
                      <th rowSpan="2" className="border border-black bg-yellow-100">입고 LOT NO.</th>
                      <th rowSpan="2" className="border border-black bg-yellow-100">방화유리<br />수량</th>
                      <th rowSpan="2" className="border border-black bg-yellow-100">품명</th>
                      <th colSpan="3" className="border border-black bg-gray-200">제작사이즈(mm) - 미미제외</th>
                      <th rowSpan="2" className="border border-black bg-yellow-100">조인트바<br />수량</th>
                      <th rowSpan="2" className="border border-black bg-yellow-100">코일<br />사용량</th>
                      <th rowSpan="2" className="border border-black bg-yellow-100">설치층/부호</th>
                    </tr>
                    <tr>
                      <th className="border border-black bg-gray-200">가로</th>
                      <th className="border border-black bg-gray-200">세로</th>
                      <th className="border border-black bg-gray-200">매수(세로)</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(data.slatWorkItems || [
                      { no: 1, lotNo: '250508-01i', itemName: '슬랫\n[EGI1.55T]', width: 3610, height: 4350, jointBarQty: 5, coilUsage: 225, installFloor: '/' },
                      { no: 2, lotNo: '250425-01i', itemName: '슬랫\n[EGI1.55T]', width: 3610, height: 4350, jointBarQty: 5, coilUsage: 225, installFloor: '/' },
                    ]).map((item, idx) => {
                      // 슬랫 매수 자동 계산: 코일길이(305m) ÷ 제품높이 = 절단매수
                      const calculatedSheetCount = item.sheetCount || calculateWorkLogSlatSheetCount(item);
                      return (
                        <tr key={idx}>
                          <td className="border border-black text-center">{item.no || idx + 1}</td>
                          <td className="border border-black text-center font-mono">{item.lotNo}</td>
                          <td className="border border-black text-center"></td>
                          <td className="border border-black text-center whitespace-pre-line text-xs">{item.itemName}</td>
                          <td className="border border-black text-center bg-yellow-200 font-bold">{item.width}</td>
                          <td className="border border-black text-center bg-yellow-200 font-bold">{item.height}</td>
                          <td className="border border-black text-center bg-yellow-200 font-bold">{calculatedSheetCount}</td>
                          <td className="border border-black text-center">{item.jointBarQty}</td>
                          <td className="border border-black text-center">{item.coilUsage}</td>
                          <td className="border border-black text-center">{item.installFloor}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>

                {/* 합계 테이블 */}
                <table className="mb-4">
                  <tbody>
                    <tr>
                      <td className="border border-black w-40 text-center bg-purple-100 font-bold">생산량 합계 (m²)</td>
                      <td className="border border-black w-24 text-center font-bold text-lg">{data.totalProduction?.area || '450'}</td>
                      <td className="border border-black w-40 text-center bg-purple-100 font-bold">조인트바 합계</td>
                      <td className="border border-black w-24 text-center font-bold text-lg">{data.totalProduction?.jointBar || '10'}</td>
                    </tr>
                  </tbody>
                </table>
              </>
            )}

            {/* 절곡 공정 내용 */}
            {processType === '절곡' && (
              <>
                {/* 제품정보 */}
                <table className="mb-4">
                  <tbody>
                    <tr>
                      <td className="border border-black w-20 text-center bg-gray-50">제품명</td>
                      <td className="border border-black font-bold">{data.productCode}</td>
                      <td className="border border-black">{data.productType}</td>
                      <td className="border border-black w-20 text-center bg-gray-50">마감유형</td>
                      <td className="border border-black bg-yellow-100 font-bold">{data.finishType}</td>
                      <td className="border border-black bg-yellow-100 font-bold">{data.railType}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 1. 벽면형 */}
                <div className="text-sm font-bold mb-1">1. 작업 내역 - 절곡 상세도면 참조</div>
                <table className="mb-4 text-xs">
                  <thead>
                    <tr className="bg-orange-50">
                      <th className="border border-black">세부품명</th>
                      <th className="border border-black">재질</th>
                      <th className="border border-black">입고 & 생산 LOT NO</th>
                      <th className="border border-black">길이/규격</th>
                      <th className="border border-black bg-yellow-50">수량</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(data.guideRail || generateBendingWorkLogParts({
                      productHeight: data.productHeight || 3000,
                      productWidth: data.productWidth || 3000,
                      qty: data.qty || 1
                    })).map((item, idx) => {
                      // 절곡 부품 수량 자동 계산 (수량이 없을 경우)
                      const calculatedQty = item.qty || calculateBendingPartQty(
                        item.name,
                        data.productHeight || 3000,
                        data.productWidth || 3000,
                        data.qty || 1
                      );
                      return (
                        <tr key={idx}>
                          <td className="border border-black text-left pl-2">
                            <span className="text-red-500">{idx < 9 ? '①②③④⑤⑥⑦⑧⑨'[idx] : '⑩'}</span>{item.name}
                          </td>
                          <td className="border border-black">{item.material}</td>
                          <td className="border border-black font-mono text-xs">{item.inputLotNo || ''}</td>
                          <td className="border border-black">{item.spec}</td>
                          <td className="border border-black font-bold bg-yellow-50">{calculatedQty}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>

                {/* 생산량 합계 */}
                <table className="mt-4">
                  <tbody>
                    <tr>
                      <td rowSpan="2" className="border border-black w-32 text-center bg-green-100 font-bold">생산량 합계 (kg)</td>
                      <td className="border border-black text-center bg-gray-50">SUS</td>
                      <td className="border border-black text-center bg-green-50">EGI</td>
                    </tr>
                    <tr>
                      <td className="border border-black text-center h-8">{data.totalProduction?.sus || ''}</td>
                      <td className="border border-black text-center">{data.totalProduction?.egi || ''}</td>
                    </tr>
                  </tbody>
                </table>
              </>
            )}

            {/* 재고생산 (중간검사성적서) */}
            {processType === '재고생산' && (
              <>
                {/* 제품 기본 정보 */}
                <table className="mb-4 text-xs">
                  <tbody>
                    <tr>
                      <td className="border border-black w-16 text-center bg-gray-100 font-bold">품명</td>
                      <td className="border border-black px-2">{data.productName || '가이드 레일(GR-120-14)'}</td>
                      <td className="border border-black w-16 text-center bg-gray-100 font-bold">규격</td>
                      <td className="border border-black px-2">{data.spec || '120 x 14 x 2500'}</td>
                      <td className="border border-black w-16 text-center bg-gray-100 font-bold">길이</td>
                      <td className="border border-black px-2">{data.length || '2500'}</td>
                    </tr>
                    <tr>
                      <td className="border border-black text-center bg-gray-100 font-bold">입고<br />LOT NO</td>
                      <td className="border border-black px-2 font-mono">{data.inboundLotNo || 'LOT-2024-001'}</td>
                      <td className="border border-black text-center bg-gray-100 font-bold">생산<br />LOT NO</td>
                      <td className="border border-black px-2 font-mono">{data.productLotNo || 'PLT-2024-001'}</td>
                      <td className="border border-black text-center bg-gray-100 font-bold">로트<br />크기</td>
                      <td className="border border-black px-2">{data.lotSize || '100'}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 중간검사 기준서 */}
                <div className="text-sm font-bold mb-2 bg-gray-200 px-2 py-1 border border-black">■ 중간검사 기준서</div>
                <div className="mb-4 p-4 border border-black min-h-32 flex items-center justify-center">
                  <div className="text-center text-gray-400">
                    <div className="border-2 border-dashed border-gray-300 p-8 rounded-lg">
                      <div className="text-sm mb-2">[절곡 상세 도면]</div>
                      <div className="text-xs">제품 치수 및 형상 기준</div>
                      {data.drawingImage ? (
                        <img src={data.drawingImage} alt="절곡도면" className="max-w-full mt-2" />
                      ) : (
                        <div className="mt-4 space-y-1 text-xs text-left mx-auto max-w-xs">
                          <div>• 길이: {data.length || '2500'}mm</div>
                          <div>• 너비: {data.width || '120'}mm</div>
                          <div>• 간격: {data.interval || '14'}mm</div>
                        </div>
                      )}
                    </div>
                  </div>
                </div>

                {/* 중간검사 DATA 테이블 */}
                <div className="text-sm font-bold mb-2 bg-gray-200 px-2 py-1 border border-black">■ 중간검사 DATA</div>
                <table className="mb-4 text-xs">
                  <thead>
                    <tr className="bg-yellow-100">
                      <th rowSpan="2" className="border border-black w-20">검사항목</th>
                      <th className="border border-black">겉모양/절곡상태</th>
                      <th colSpan="3" className="border border-black">치수</th>
                      <th rowSpan="2" className="border border-black w-16">판정</th>
                    </tr>
                    <tr className="bg-yellow-50">
                      <th className="border border-black">육안검사</th>
                      <th className="border border-black">길이</th>
                      <th className="border border-black">너비</th>
                      <th className="border border-black">간격</th>
                    </tr>
                    <tr className="bg-gray-50">
                      <td className="border border-black text-center font-bold">기준값</td>
                      <td className="border border-black text-center">이상무</td>
                      <td className="border border-black text-center">{data.standardLength || '2500±3'}</td>
                      <td className="border border-black text-center">{data.standardWidth || '120±1'}</td>
                      <td className="border border-black text-center">{data.standardInterval || '14±0.5'}</td>
                      <td className="border border-black text-center">-</td>
                    </tr>
                  </thead>
                  <tbody>
                    {(data.inspectionData || [
                      { no: 1, appearance: '양호', length: 2501, width: 120, interval: 14.0, result: '합격' },
                      { no: 2, appearance: '양호', length: 2499, width: 119.8, interval: 14.1, result: '합격' },
                      { no: 3, appearance: '양호', length: 2500, width: 120.2, interval: 13.9, result: '합격' },
                      { no: 4, appearance: '양호', length: 2502, width: 120.0, interval: 14.0, result: '합격' },
                      { no: 5, appearance: '양호', length: 2498, width: 119.9, interval: 14.2, result: '합격' },
                    ]).map((item, idx) => (
                      <tr key={idx}>
                        <td className="border border-black text-center">{item.no || idx + 1}</td>
                        <td className="border border-black text-center">{item.appearance}</td>
                        <td className="border border-black text-center">{item.length}</td>
                        <td className="border border-black text-center">{item.width}</td>
                        <td className="border border-black text-center">{item.interval}</td>
                        <td className={`border border-black text-center font-bold ${item.result === '합격' ? 'text-blue-600' : 'text-red-600'}`}>
                          {item.result}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* 종합판정 */}
                <table className="mb-4">
                  <tbody>
                    <tr>
                      <td className="border-2 border-black w-24 text-center bg-gray-200 font-bold py-2">종합판정</td>
                      <td className="border-2 border-black text-center py-2">
                        <div className="flex items-center justify-center gap-8">
                          <label className="flex items-center gap-2 cursor-pointer">
                            <input
                              type="radio"
                              name="finalResult"
                              value="합격"
                              checked={data.finalResult !== '불합격'}
                              readOnly
                              className="w-5 h-5"
                            />
                            <span className="text-lg font-bold text-blue-600">합격</span>
                          </label>
                          <label className="flex items-center gap-2 cursor-pointer">
                            <input
                              type="radio"
                              name="finalResult"
                              value="불합격"
                              checked={data.finalResult === '불합격'}
                              readOnly
                              className="w-5 h-5"
                            />
                            <span className="text-lg font-bold text-red-600">불합격</span>
                          </label>
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>

                {/* 검사자 정보 */}
                <table className="mb-4 text-xs">
                  <tbody>
                    <tr>
                      <td className="border border-black w-20 text-center bg-gray-100">검사일자</td>
                      <td className="border border-black px-2">{data.inspectionDate || new Date().toLocaleDateString()}</td>
                      <td className="border border-black w-20 text-center bg-gray-100">검사자</td>
                      <td className="border border-black px-2">{data.inspector || ''}</td>
                    </tr>
                  </tbody>
                </table>
              </>
            )}

            {/* 비고 (공통) */}
            <div className="mt-4 border border-black p-2">
              <div className="font-bold mb-1">[비 고]</div>
              <div className="min-h-16">{data.remarks}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============ 재고 확인 모달 ============
const MaterialCheckModal = ({ workOrder, onClose }) => {
  // 샘플 BOM 데이터 (실제로는 품목별 BOM에서 가져옴)
  const bomData = [
    { id: 1, materialCode: 'SCR-MAT-001', materialName: '스크린 원단', unit: '㎡', required: 26, stock: 150, status: 'ok' },
    { id: 2, materialCode: 'SCR-MAT-002', materialName: '앤드락', unit: 'EA', required: 40, stock: 200, status: 'ok' },
    { id: 3, materialCode: 'SCR-MAT-003', materialName: '하단바', unit: 'EA', required: 10, stock: 8, status: 'shortage' },
    { id: 4, materialCode: 'SCR-MAT-004', materialName: '미싱실', unit: 'M', required: 500, stock: 2000, status: 'ok' },
    { id: 5, materialCode: 'SCR-MAT-005', materialName: '포장박스', unit: 'EA', required: 10, stock: 50, status: 'ok' },
  ];

  const hasShortage = bomData.some(b => b.status === 'shortage');

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl w-full max-w-2xl max-h-[80vh] overflow-hidden">
        <div className="flex items-center justify-between p-4 border-b">
          <div className="flex items-center gap-3">
            <Box className="w-6 h-6 text-blue-500" />
            <div>
              <h3 className="font-bold text-gray-900">자재 재고 확인</h3>
              <p className="text-sm text-gray-500">{workOrder?.workOrderNo}</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg">
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {hasShortage && (
          <div className="mx-4 mt-4 p-3 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2">
            <AlertCircle className="w-5 h-5 text-red-500" />
            <span className="text-sm text-red-700">재고 부족 자재가 있습니다. 자재 발주가 필요합니다.</span>
          </div>
        )}

        <div className="p-4 overflow-y-auto max-h-[400px]">
          <table className="w-full">
            <thead className="bg-gray-50 sticky top-0">
              <tr>
                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">자재코드</th>
                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">자재명</th>
                <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">필요량</th>
                <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">재고</th>
                <th className="px-3 py-2 text-center text-xs font-medium text-gray-500">상태</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {bomData.map(item => (
                <tr key={item.id} className={item.status === 'shortage' ? 'bg-red-50' : ''}>
                  <td className="px-3 py-2 text-sm font-mono text-gray-600">{item.materialCode}</td>
                  <td className="px-3 py-2 text-sm text-gray-900">{item.materialName}</td>
                  <td className="px-3 py-2 text-sm text-right">{item.required} {item.unit}</td>
                  <td className="px-3 py-2 text-sm text-right font-medium">
                    <span className={item.status === 'shortage' ? 'text-red-600' : 'text-gray-900'}>
                      {item.stock} {item.unit}
                    </span>
                  </td>
                  <td className="px-3 py-2 text-center">
                    {item.status === 'ok' ? (
                      <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-green-100 text-green-700">
                        <CheckCircle className="w-3 h-3 mr-1" /> 충분
                      </span>
                    ) : (
                      <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-red-100 text-red-700">
                        <AlertCircle className="w-3 h-3 mr-1" /> 부족
                      </span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
          {hasShortage && (
            <Button variant="outline">
              <Send className="w-4 h-4" /> 자재 발주 요청
            </Button>
          )}
          <Button variant="primary" onClick={onClose}>확인</Button>
        </div>
      </div>
    </div>
  );
};

// ============ 자재 투입 모달 ============
const MaterialInputModal = ({
  workOrder,
  inventory = [],
  materialLots: allMaterialLots = [],
  onClose,
  onSubmit,
  // 기능정의서 관련 props
  showFeatureDescription,
  featureBadges = {},
  selectedBadge,
  setSelectedBadge,
  updateFeatureBadge,
  setEditingBadge
}) => {
  const [selectedMaterial, setSelectedMaterial] = useState(null);
  const [selectedLot, setSelectedLot] = useState(null);
  const [qty, setQty] = useState(0);
  const [inputBy, setInputBy] = useState(workOrder?.assignee || '');
  const [note, setNote] = useState('');

  // 공정별 필요 자재 매핑 (LOT 정보 포함)
  const getProcessMaterials = () => {
    const mapping = {
      // 스크린 공정: 원단, 앤드락, 하단바, 미싱실, 포장박스
      '스크린': ['SCR-MAT-001', 'SCR-MAT-002', 'SCR-MAT-003', 'SCR-MAT-004', 'SCR-MAT-005'],
      // 슬랫 공정: 슬랫코일, 미미자재, 포장박스
      '슬랫': ['SLT-MAT-001', 'SLT-MAT-002', 'SCR-MAT-005'],
      // 절곡 공정: EGI철판, SUS철판, 리벳, 볼트, 실리콘
      '절곡': ['EGI-1.55T', 'SUS-1.2T', 'SM-RIVET-01', 'SM-BOLT-01', 'SM-SILICON-01'],
    };
    const codes = mapping[workOrder?.processType] || [];
    return inventory.filter(m => codes.includes(m.materialCode));
  };

  const processMaterials = getProcessMaterials();

  // 선택된 자재의 LOT 목록 (실제 materialLots 데이터 사용 + FIFO 정렬)
  const getMaterialLots = (material) => {
    if (!material) return [];

    // 해당 자재의 LOT 필터링 (materialCode로 매칭)
    const matchingLots = allMaterialLots.filter(lot =>
      lot.materialCode === material.materialCode &&
      lot.remainingQty > 0 &&
      lot.status === 'AVAILABLE'
    );

    // FIFO 정렬: 입고일 기준 오름차순 (가장 오래된 것 먼저)
    const sortedLots = matchingLots.sort((a, b) =>
      new Date(a.inboundDate) - new Date(b.inboundDate)
    );

    // FIFO 순위 추가
    return sortedLots.map((lot, index) => ({
      lotNo: lot.lotNo,
      inboundDate: lot.inboundDate,
      remainQty: lot.remainingQty,
      expiryDate: lot.expiryDate,
      supplier: lot.supplier,
      location: lot.location,
      fifoRank: index + 1, // FIFO 순위 (1이 가장 먼저 사용 권장)
      isRecommended: index === 0, // 첫 번째가 FIFO 추천
    }));
  };

  const materialLots = selectedMaterial ? getMaterialLots(selectedMaterial) : [];

  const handleSubmit = () => {
    if (!selectedMaterial) {
      alert('자재를 선택해주세요.');
      return;
    }
    if (!selectedLot) {
      alert('LOT를 선택해주세요.');
      return;
    }
    if (qty <= 0) {
      alert('투입 수량을 입력해주세요.');
      return;
    }
    if (qty > selectedLot.remainQty) {
      alert(`LOT 잔량이 부족합니다.\n\nLOT 잔량: ${selectedLot.remainQty} ${selectedMaterial.unit}`);
      return;
    }
    onSubmit?.(selectedMaterial.materialCode, qty, selectedLot.lotNo, inputBy, note);
  };

  // 모달용 뱃지 가져오기
  const modalBadges = featureBadges['modal-material-input-modal'] || [];

  return (
    <div className="fixed inset-0 bg-black/50 flex items-end sm:items-center justify-center z-50">
      <div className="bg-white w-full sm:max-w-2xl sm:rounded-xl rounded-t-xl max-h-[90vh] overflow-hidden flex flex-col relative">
        {/* 기능정의서 모드일 때 뱃지 오버레이 */}
        {showFeatureDescription && (
          <ModalFeatureBadgeOverlay
            badges={modalBadges}
            selectedBadge={selectedBadge}
            onSelectBadge={setSelectedBadge}
            onUpdatePosition={(badgeId, pos) => updateFeatureBadge?.(badgeId, pos)}
            onEditBadge={(badge) => setEditingBadge?.(badge)}
            modalId="material-input-modal"
            screenId="DLG-P02-02"
          />
        )}

        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b sticky top-0 bg-white">
          <h3 className="font-bold text-lg text-gray-900">투입자재 등록</h3>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg text-gray-500 font-medium">
            닫기
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-4 space-y-4">
          {/* FIFO 안내 범례 */}
          <div className="flex items-center gap-4 p-3 bg-gray-100 rounded-lg border border-gray-300">
            <span className="text-sm font-bold text-black">FIFO 순위:</span>
            <div className="flex items-center gap-3">
              <span className="flex items-center gap-1">
                <span className="w-6 h-6 bg-black rounded-full flex items-center justify-center text-xs font-bold" style={{ color: '#ffffff' }}>1</span>
                <span className="text-xs text-black font-medium">최우선</span>
              </span>
              <span className="flex items-center gap-1">
                <span className="w-6 h-6 bg-black rounded-full flex items-center justify-center text-xs font-bold" style={{ color: '#ffffff' }}>2</span>
                <span className="text-xs text-black font-medium">차선</span>
              </span>
              <span className="flex items-center gap-1">
                <span className="w-6 h-6 bg-black rounded-full flex items-center justify-center text-xs font-bold" style={{ color: '#ffffff' }}>3+</span>
                <span className="text-xs text-black font-medium">대기</span>
              </span>
            </div>
          </div>

          {/* 자재 선택 */}
          <div>
            <label className="block text-sm font-bold text-black mb-2">① 자재 선택 (BOM 기준)</label>
            <div className="border border-gray-300 rounded-lg overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-gray-200">
                  <tr>
                    <th className="px-3 py-2 text-left font-bold text-black">자재코드</th>
                    <th className="px-3 py-2 text-left font-bold text-black">자재명</th>
                    <th className="px-3 py-2 text-center font-bold text-black">단위</th>
                    <th className="px-3 py-2 text-right font-bold text-black">현재고</th>
                    <th className="px-3 py-2 text-center font-bold text-black w-16">선택</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {processMaterials.map(material => (
                    <tr
                      key={material.id}
                      onClick={() => {
                        setSelectedMaterial(material);
                        setSelectedLot(null);
                        setQty(0);
                      }}
                      className={`cursor-pointer transition-colors ${selectedMaterial?.id === material.id
                          ? 'bg-gray-200'
                          : 'hover:bg-gray-50'
                        }`}
                    >
                      <td className="px-3 py-3 font-mono text-black">{material.materialCode}</td>
                      <td className="px-3 py-3 font-bold text-black">{material.materialName}</td>
                      <td className="px-3 py-3 text-center text-black">{material.unit}</td>
                      <td className="px-3 py-3 text-right font-bold text-black">{material.stock}</td>
                      <td className="px-3 py-3 text-center">
                        <input
                          type="radio"
                          name="material"
                          checked={selectedMaterial?.id === material.id}
                          onChange={() => {
                            setSelectedMaterial(material);
                            setSelectedLot(null);
                            setQty(0);
                          }}
                          className="w-4 h-4 cursor-pointer accent-black"
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {processMaterials.length === 0 && (
                <div className="p-8 text-center text-gray-600 font-medium">
                  이 공정에 배정된 자재가 없습니다.
                </div>
              )}
            </div>
          </div>

          {/* LOT 선택 */}
          {selectedMaterial && (
            <div>
              <label className="block text-sm font-bold text-black mb-2">
                ② LOT 선택 - {selectedMaterial.materialName}
                <span className="text-xs text-gray-600 font-normal ml-2">(FIFO 자동 정렬)</span>
              </label>
              <div className="border border-gray-300 rounded-lg overflow-hidden max-h-48 overflow-y-auto">
                <table className="w-full text-sm">
                  <thead className="bg-gray-200 sticky top-0">
                    <tr>
                      <th className="px-3 py-2 text-center font-bold text-black w-16">FIFO</th>
                      <th className="px-3 py-2 text-left font-bold text-black">LOT번호</th>
                      <th className="px-3 py-2 text-center font-bold text-black">입고일</th>
                      <th className="px-3 py-2 text-right font-bold text-black">잔량</th>
                      <th className="px-3 py-2 text-center font-bold text-black">위치</th>
                      <th className="px-3 py-2 text-center font-bold text-black w-16">선택</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {materialLots.map(lot => (
                      <tr
                        key={lot.lotNo}
                        onClick={() => {
                          setSelectedLot(lot);
                          setQty(Math.min(10, lot.remainQty));
                        }}
                        className={`cursor-pointer transition-colors ${selectedLot?.lotNo === lot.lotNo
                            ? 'bg-gray-200'
                            : lot.isRecommended
                              ? 'bg-gray-100'
                              : 'hover:bg-gray-50'
                          }`}
                      >
                        <td className="px-3 py-3 text-center">
                          <span className="w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold mx-auto bg-black" style={{ color: '#ffffff' }}>
                            {lot.fifoRank}
                          </span>
                        </td>
                        <td className="px-3 py-3 font-mono font-medium text-black">
                          {lot.lotNo}
                          {lot.isRecommended && (
                            <span className="ml-2 px-2 py-0.5 bg-black text-xs font-bold rounded" style={{ color: '#ffffff' }}>추천</span>
                          )}
                        </td>
                        <td className="px-3 py-3 text-center text-black">{lot.inboundDate}</td>
                        <td className="px-3 py-3 text-right font-bold text-black">
                          {lot.remainQty} {selectedMaterial.unit}
                        </td>
                        <td className="px-3 py-3 text-center text-black">{lot.location}</td>
                        <td className="px-3 py-3 text-center">
                          <input
                            type="radio"
                            name="lot"
                            checked={selectedLot?.lotNo === lot.lotNo}
                            onChange={() => {
                              setSelectedLot(lot);
                              setQty(Math.min(10, lot.remainQty));
                            }}
                            className="w-4 h-4 cursor-pointer accent-black"
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                {materialLots.length === 0 && (
                  <div className="p-8 text-center text-gray-600 font-medium">
                    선택한 자재의 LOT가 없습니다.
                  </div>
                )}
              </div>
            </div>
          )}

          {/* 투입 정보 입력 */}
          {selectedLot && (
            <div className="p-4 bg-gray-100 rounded-lg border border-gray-300">
              <label className="block text-sm font-bold text-black mb-3">③ 투입 정보 입력</label>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-medium text-black mb-1">선택 LOT</label>
                  <div className="px-3 py-2 bg-white border border-gray-300 rounded font-mono text-sm font-bold text-black">{selectedLot.lotNo}</div>
                </div>
                <div>
                  <label className="block text-xs font-medium text-black mb-1">LOT 잔량</label>
                  <div className="px-3 py-2 bg-white border border-gray-300 rounded text-sm font-bold text-black">{selectedLot.remainQty} {selectedMaterial.unit}</div>
                </div>
                <div>
                  <label className="block text-xs font-medium text-black mb-1">투입 수량 *</label>
                  <div className="flex items-center gap-2">
                    <input
                      type="number"
                      value={qty}
                      onChange={(e) => setQty(Number(e.target.value))}
                      min={1}
                      max={selectedLot.remainQty}
                      className="flex-1 px-3 py-2 border border-gray-300 rounded focus:ring-2 focus:ring-gray-400 focus:border-gray-400 text-base font-bold text-black"
                    />
                    <span className="text-sm font-medium text-black">{selectedMaterial.unit}</span>
                  </div>
                </div>
                <div>
                  <label className="block text-xs font-medium text-black mb-1">투입자</label>
                  <input
                    type="text"
                    value={inputBy}
                    onChange={(e) => setInputBy(e.target.value)}
                    placeholder="작업자명"
                    className="w-full px-3 py-2 border border-gray-300 rounded focus:ring-2 focus:ring-gray-400 focus:border-gray-400 text-base text-black"
                  />
                </div>
                <div className="col-span-2">
                  <label className="block text-xs font-medium text-black mb-1">비고</label>
                  <input
                    type="text"
                    value={note}
                    onChange={(e) => setNote(e.target.value)}
                    placeholder="특이사항 입력 (선택)"
                    className="w-full px-3 py-2 border border-gray-300 rounded focus:ring-2 focus:ring-gray-400 focus:border-gray-400 text-base text-black"
                  />
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 하단 버튼 */}
        <div className="p-4 border-t flex gap-3">
          <Button variant="outline" className="flex-1" onClick={onClose}>취소</Button>
          <Button
            variant="primary"
            className="flex-1"
            onClick={handleSubmit}
            disabled={!selectedMaterial || !selectedLot || qty <= 0}
          >
            투입 등록
          </Button>
        </div>
      </div>
    </div>
  );
};

// ============ 부적합품 처리 모달 ============
const DefectProcessModal = ({ inspection, onClose, onProcess }) => {
  const [processType, setProcessType] = useState('');
  const [reason, setReason] = useState('');
  const [note, setNote] = useState('');

  const processTypes = [
    { id: 'rework', label: '재작업', description: '수정 후 재검사', icon: '🔄' },
    { id: 'scrap', label: '폐기', description: '원자재 재투입 필요', icon: '🗑️' },
    { id: 'downgrade', label: '등급 하향', description: '품질 등급 조정', icon: '⬇️' },
    { id: 'special', label: '특채', description: '특별 허용 승인', icon: '✅' },
  ];

  const handleSubmit = () => {
    if (!processType) {
      alert('처리 방법을 선택해주세요.');
      return;
    }
    onProcess?.({
      type: processType,
      reason,
      note,
      processedAt: new Date().toISOString(),
    });
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl w-full max-w-lg max-h-[80vh] overflow-hidden">
        <div className="flex items-center justify-between p-4 border-b bg-red-50">
          <div className="flex items-center gap-3">
            <XCircle className="w-6 h-6 text-red-500" />
            <div>
              <h3 className="font-bold text-gray-900">부적합품 처리</h3>
              <p className="text-sm text-red-600">검사 불합격 - 처리 방법 선택</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-red-100 rounded-lg">
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        <div className="p-4 space-y-4">
          {/* 검사 정보 */}
          <div className="p-3 bg-gray-50 rounded-lg">
            <div className="grid grid-cols-2 gap-2 text-sm">
              <div>
                <span className="text-gray-500">검사번호:</span>
                <span className="ml-2 font-mono">{inspection?.inspectionNo || 'INS-001'}</span>
              </div>
              <div>
                <span className="text-gray-500">품목:</span>
                <span className="ml-2">{inspection?.productName || '스크린 셔터'}</span>
              </div>
            </div>
          </div>

          {/* 처리 방법 선택 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">처리 방법 *</label>
            <div className="grid grid-cols-2 gap-3">
              {processTypes.map(type => (
                <button
                  key={type.id}
                  onClick={() => setProcessType(type.id)}
                  className={`p-4 rounded-lg border text-left transition-all ${processType === type.id
                      ? 'border-blue-500 bg-blue-50 ring-2 ring-blue-200'
                      : 'border-gray-200 hover:border-gray-300'
                    }`}
                >
                  <span className="text-2xl">{type.icon}</span>
                  <p className="font-medium mt-2">{type.label}</p>
                  <p className="text-xs text-gray-500">{type.description}</p>
                </button>
              ))}
            </div>
          </div>

          {/* 사유 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">불량 사유</label>
            <select
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
            >
              <option value="">선택하세요</option>
              <option value="size">치수 불량</option>
              <option value="surface">외관 불량</option>
              <option value="material">자재 불량</option>
              <option value="process">공정 불량</option>
              <option value="other">기타</option>
            </select>
          </div>

          {/* 비고 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">처리 내용</label>
            <textarea
              value={note}
              onChange={(e) => setNote(e.target.value)}
              rows={3}
              className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
              placeholder="처리 상세 내용을 입력하세요..."
            />
          </div>

          {/* 안내 */}
          {processType === 'scrap' && (
            <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
              <p className="text-sm text-yellow-800">
                ⚠️ 폐기 처리 시 해당 LOT의 원자재를 재투입하여 다시 생산해야 합니다.
              </p>
            </div>
          )}
        </div>

        <div className="flex gap-2 p-4 border-t bg-gray-50">
          <Button variant="outline" className="flex-1" onClick={onClose}>취소</Button>
          <Button variant="primary" className="flex-1" onClick={handleSubmit}>
            처리 완료
          </Button>
        </div>
      </div>
    </div>
  );
};

// ============ 알림 컴포넌트 ============
const NotificationBell = ({ notifications = [], onViewAll }) => {
  const [isOpen, setIsOpen] = useState(false);

  const sampleNotifications = [
    { id: 1, type: 'urgent', message: '긴급 작업지시가 추가되었습니다.', time: '5분 전', read: false },
    { id: 2, type: 'change', message: '작업지시 WO-001 일정이 변경되었습니다.', time: '30분 전', read: false },
    { id: 3, type: 'issue', message: '김생산님이 이슈를 보고했습니다.', time: '1시간 전', read: true },
    { id: 4, type: 'complete', message: '작업지시 WO-002가 완료되었습니다.', time: '2시간 전', read: true },
  ];

  const allNotifications = notifications.length > 0 ? notifications : sampleNotifications;
  const unreadCount = allNotifications.filter(n => !n.read).length;

  const getIcon = (type) => {
    switch (type) {
      case 'urgent': return <AlertCircle className="w-4 h-4 text-red-500" />;
      case 'change': return <Edit className="w-4 h-4 text-yellow-500" />;
      case 'issue': return <AlertCircle className="w-4 h-4 text-orange-500" />;
      case 'complete': return <CheckCircle className="w-4 h-4 text-green-500" />;
      default: return <Bell className="w-4 h-4 text-gray-500" />;
    }
  };

  return (
    <div className="relative">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="relative p-2 hover:bg-gray-100 rounded-lg"
      >
        <Bell className="w-6 h-6 text-gray-600" />
        {unreadCount > 0 && (
          <span className="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white text-xs rounded-full flex items-center justify-center">
            {unreadCount}
          </span>
        )}
      </button>

      {isOpen && (
        <>
          <div className="fixed inset-0 z-40" onClick={() => setIsOpen(false)} />
          <div className="absolute right-0 mt-2 w-80 bg-white rounded-xl shadow-lg border z-50">
            <div className="flex items-center justify-between p-3 border-b">
              <h4 className="font-medium text-gray-900">알림</h4>
              {unreadCount > 0 && (
                <span className="text-xs text-blue-600">{unreadCount}개 새 알림</span>
              )}
            </div>
            <div className="max-h-80 overflow-y-auto">
              {allNotifications.map(notif => (
                <div
                  key={notif.id}
                  className={`p-3 border-b hover:bg-gray-50 cursor-pointer ${!notif.read ? 'bg-blue-50' : ''
                    }`}
                >
                  <div className="flex items-start gap-3">
                    {getIcon(notif.type)}
                    <div className="flex-1">
                      <p className={`text-sm ${!notif.read ? 'font-medium' : 'text-gray-600'}`}>
                        {notif.message}
                      </p>
                      <p className="text-xs text-gray-400 mt-1">{notif.time}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <button
              onClick={onViewAll}
              className="w-full p-3 text-sm text-blue-600 hover:bg-gray-50 text-center"
            >
              모든 알림 보기
            </button>
          </div>
        </>
      )}
    </div>
  );
};

// ==================== 생산지시 관리 컴포넌트 ====================
const ProductionOrderList = ({ productionOrders, workOrders, onNavigate, onCreateWorkOrders, onDeleteProductionOrders }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [selectedPO, setSelectedPO] = useState(null);
  const [selectedIds, setSelectedIds] = useState([]);
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  const tabs = [
    { id: 'all', label: '전체', count: productionOrders.length },
    { id: '생산대기', label: '생산대기', count: productionOrders.filter(po => po.status === '생산대기').length },
    { id: '생산중', label: '생산중', count: productionOrders.filter(po => po.status === '생산중').length },
    { id: '생산완료', label: '생산완료', count: productionOrders.filter(po => po.status === '생산완료').length },
  ];

  const filteredOrders = productionOrders.filter(po => {
    const matchSearch = !search ||
      po.productionOrderNo.toLowerCase().includes(search.toLowerCase()) ||
      po.orderNo.toLowerCase().includes(search.toLowerCase()) ||
      po.siteName.toLowerCase().includes(search.toLowerCase()) ||
      po.customerName.toLowerCase().includes(search.toLowerCase());
    const matchTab = activeTab === 'all' || po.status === activeTab;
    return matchSearch && matchTab;
  }).sort((a, b) => b.id - a.id); // ID 기준 내림차순 (최신 등록 최상단)

  // 전체 선택/해제
  const handleSelectAll = (e) => {
    if (e.target.checked) {
      setSelectedIds(filteredOrders.map(po => po.id));
    } else {
      setSelectedIds([]);
    }
  };

  // 개별 선택
  const handleSelectOne = (id, e) => {
    e.stopPropagation();
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  };

  // 삭제 확인
  const handleDeleteConfirm = () => {
    if (onDeleteProductionOrders && selectedIds.length > 0) {
      onDeleteProductionOrders(selectedIds);
    }
    setSelectedIds([]);
    setShowDeleteModal(false);
  };

  // 해당 생산지시의 작업지시서 개수 조회
  const getWorkOrderCount = (po) => {
    return workOrders.filter(wo => wo.orderNo === po.orderNo).length;
  };

  const handleCreateWorkOrders = (po) => {
    setSelectedPO(po);
    setShowCreateModal(true);
  };

  const confirmCreateWorkOrders = () => {
    if (selectedPO && onCreateWorkOrders) {
      onCreateWorkOrders(selectedPO);
    }
    setShowCreateModal(false);
    setSelectedPO(null);
  };

  return (
    <div className="p-4 md:p-6">
      {/* 헤더 */}
      <div className="mb-6 space-y-3">
        <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
          <ClipboardList className="w-6 h-6 text-blue-500" />
          생산지시 목록
        </h1>
      </div>

      {/* 프로세스 안내 */}
      <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl p-4 mb-6 border border-blue-100">
        <div className="flex items-center gap-6 text-sm overflow-x-auto pb-2">
          <div className="flex items-center gap-2 whitespace-nowrap">
            <div className="w-8 h-8 rounded-full bg-green-100 text-green-700 flex items-center justify-center text-xs font-bold">1</div>
            <span className="font-medium">수주확정</span>
          </div>
          <ChevronRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
          <div className="flex items-center gap-2 whitespace-nowrap">
            <div className="w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center text-xs font-bold">2</div>
            <span className="font-bold text-blue-700">생산지시</span>
          </div>
          <ChevronRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
          <div className="flex items-center gap-2 whitespace-nowrap">
            <div className="w-8 h-8 rounded-full bg-gray-200 text-gray-600 flex items-center justify-center text-xs font-bold">3</div>
            <span>작업지시</span>
          </div>
          <ChevronRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
          <div className="flex items-center gap-2 whitespace-nowrap">
            <div className="w-8 h-8 rounded-full bg-gray-200 text-gray-600 flex items-center justify-center text-xs font-bold">4</div>
            <span>생산</span>
          </div>
          <ChevronRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
          <div className="flex items-center gap-2 whitespace-nowrap">
            <div className="w-8 h-8 rounded-full bg-gray-200 text-gray-600 flex items-center justify-center text-xs font-bold">5</div>
            <span>검사/출하</span>
          </div>
        </div>
      </div>

      {/* 검색 및 탭 */}
      <div className="bg-white rounded-xl shadow-sm border p-4 mb-4">
        <div className="flex flex-col md:flex-row gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="생산지시번호, 수주번호, 현장명 검색..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border rounded-lg text-sm"
            />
          </div>
          <div className="flex flex-wrap gap-2 overflow-x-auto pb-2 md:pb-0">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-full border whitespace-nowrap transition-colors ${activeTab === tab.id
                    ? 'bg-gray-900 text-white border-gray-900'
                    : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                  }`}
              >
                {tab.label}
                <span className={`text-xs px-1.5 py-0.5 rounded-full ${activeTab === tab.id
                    ? 'bg-gray-700 text-white'
                    : 'bg-gray-100 text-gray-500'
                  }`}>
                  {tab.count}
                </span>
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* 목록 */}
      <div className="bg-white rounded-xl shadow-sm border overflow-hidden">
        {/* 선택 삭제 버튼 (2개 이상 선택 시) */}
        {selectedIds.length >= 2 && (
          <div className="px-4 py-3 bg-gray-50 border-b flex items-center justify-between">
            <span className="text-sm text-gray-600">
              {selectedIds.length}개 항목 선택됨
            </span>
            <button
              onClick={() => setShowDeleteModal(true)}
              className="px-4 py-2 bg-red-600 text-white text-sm rounded-lg hover:bg-red-700 flex items-center gap-2"
            >
              <Trash2 className="w-4 h-4" />
              선택 삭제({selectedIds.length})
            </button>
          </div>
        )}
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-3 py-3 text-center text-xs font-semibold text-gray-600 w-12">
                  <input
                    type="checkbox"
                    className="rounded"
                    checked={filteredOrders.length > 0 && selectedIds.length === filteredOrders.length}
                    onChange={handleSelectAll}
                  />
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600">생산지시번호</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600">수주번호</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600">현장명</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600">거래처</th>
                <th className="px-4 py-3 text-center text-xs font-semibold text-gray-600">수량</th>
                <th className="px-4 py-3 text-center text-xs font-semibold text-gray-600">납기</th>
                <th className="px-4 py-3 text-center text-xs font-semibold text-gray-600">상태</th>
                <th className="px-4 py-3 text-center text-xs font-semibold text-gray-600">작업지시</th>
                {/* 작업 컬럼 (1개 선택 시에만 헤더 표시) */}
                {selectedIds.length === 1 && (
                  <th className="px-3 py-3 text-center text-xs font-semibold text-gray-600 w-24">작업</th>
                )}
              </tr>
            </thead>
            <tbody className="divide-y">
              {filteredOrders.map(po => {
                const woCount = getWorkOrderCount(po);
                const isSelected = selectedIds.includes(po.id);
                const isOnlySelected = selectedIds.length === 1 && isSelected;

                return (
                  <tr
                    key={po.id}
                    className={`hover:bg-gray-50 cursor-pointer ${isSelected ? 'bg-blue-50' : ''}`}
                    onClick={() => onNavigate('production-order-detail', po)}
                  >
                    <td className="px-3 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                      <input
                        type="checkbox"
                        className="rounded"
                        checked={isSelected}
                        onChange={(e) => handleSelectOne(po.id, e)}
                      />
                    </td>
                    <td className="px-4 py-3">
                      <span className="text-blue-600 font-medium text-sm">
                        {po.productionOrderNo}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-600">{po.orderNo}</td>
                    <td className="px-4 py-3 text-sm font-medium">{po.siteName}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{po.customerName}</td>
                    <td className="px-4 py-3 text-sm text-center">{po.qty}개</td>
                    <td className="px-4 py-3 text-sm text-center">{po.dueDate}</td>
                    <td className="px-4 py-3 text-center">
                      <StatusBadge status={po.status} />
                    </td>
                    <td className="px-4 py-3 text-center">
                      {woCount > 0 ? (
                        <span className="inline-flex items-center gap-1 px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs">
                          <CheckCircle className="w-3 h-3" />
                          {woCount}건
                        </span>
                      ) : (
                        <span className="text-gray-400 text-xs">미생성</span>
                      )}
                    </td>
                    {/* 작업 컬럼 (1개만 선택된 경우에만 표시) */}
                    {selectedIds.length === 1 && (
                      <td className="px-3 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                        {isOnlySelected && (
                          <div className="flex items-center justify-center gap-1">
                            <button
                              onClick={() => onNavigate('production-order-edit', po)}
                              className="p-1.5 text-blue-600 hover:bg-blue-50 rounded transition-colors"
                              title="수정"
                            >
                              <Edit2 className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => setShowDeleteModal(true)}
                              className="p-1.5 text-red-600 hover:bg-red-50 rounded transition-colors"
                              title="삭제"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        )}
                      </td>
                    )}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {filteredOrders.length === 0 && (
          <div className="text-center py-12 text-gray-500">
            <ClipboardList className="w-12 h-12 mx-auto mb-3 text-gray-300" />
            <p>검색 결과가 없습니다</p>
          </div>
        )}
      </div>

      {/* 작업지시 생성 확인 모달 */}
      {showCreateModal && selectedPO && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-lg w-full">
            <div className="p-6 border-b">
              <h3 className="text-lg font-bold flex items-center gap-2">
                <Play className="w-5 h-5 text-green-600" />
                작업지시서 자동 생성
              </h3>
            </div>
            <div className="p-6">
              <div className="bg-blue-50 rounded-lg p-4 mb-4">
                <div className="text-sm space-y-1">
                  <p><strong>생산지시:</strong> {selectedPO.productionOrderNo}</p>
                  <p><strong>현장명:</strong> {selectedPO.siteName}</p>
                  <p><strong>수량:</strong> {selectedPO.qty}개</p>
                </div>
              </div>

              <div className="mb-4">
                <h4 className="font-medium mb-2">BOM 기반 공정별 작업지시서 생성</h4>
                <div className="space-y-2">
                  {selectedPO.processGroups?.map((pg, idx) => (
                    <div key={idx} className="flex items-center gap-3 p-2 bg-gray-50 rounded-lg">
                      <div className="w-6 h-6 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center text-xs font-bold">
                        {pg.processSeq}
                      </div>
                      <span className="font-medium">{pg.processName} 공정</span>
                      <span className="text-sm text-gray-500">({pg.items?.length || 0}개 품목)</span>
                    </div>
                  ))}
                </div>
              </div>

              <p className="text-sm text-gray-600">
                위 공정에 대한 작업지시서가 자동으로 생성되어 생산팀으로 전달됩니다.
              </p>
            </div>
            <div className="p-4 border-t bg-gray-50 flex justify-end gap-2">
              <button
                onClick={() => setShowCreateModal(false)}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg"
              >
                취소
              </button>
              <button
                onClick={confirmCreateWorkOrders}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2"
              >
                <Play className="w-4 h-4" />
                작업지시 생성
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4">
            <div className="p-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
                  <AlertTriangle className="w-6 h-6 text-red-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">삭제 확인</h3>
                  <p className="text-sm text-gray-500">선택한 항목을 삭제하시겠습니까?</p>
                </div>
              </div>
              <div className="bg-red-50 border border-red-200 rounded-lg p-3 mb-4">
                <p className="text-sm text-red-700">
                  <strong>{selectedIds.length}개</strong>의 생산지시가 삭제됩니다.
                  삭제된 데이터는 복구할 수 없습니다.
                </p>
              </div>
              <div className="flex justify-end gap-3">
                <button
                  onClick={() => setShowDeleteModal(false)}
                  className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  취소
                </button>
                <button
                  onClick={handleDeleteConfirm}
                  className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center gap-2"
                >
                  <Trash2 className="w-4 h-4" />
                  삭제
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 생산지시 상세 화면
const ProductionOrderDetail = ({ productionOrder, workOrders, orders, onNavigate, onBack, onCreateWorkOrders, onUpdateStatus }) => {
  const [showCreateModal, setShowCreateModal] = useState(false);

  if (!productionOrder) {
    return (
      <div className="p-6 text-center">
        <p className="text-gray-500">생산지시 정보를 찾을 수 없습니다.</p>
        <button onClick={onBack} className="mt-4 text-blue-600 hover:underline">목록으로</button>
      </div>
    );
  }

  const relatedWorkOrders = workOrders.filter(wo => wo.orderNo === productionOrder.orderNo);
  const relatedOrder = orders.find(o => o.orderNo === productionOrder.orderNo);

  const handleCreateWorkOrders = () => {
    if (onCreateWorkOrders) {
      onCreateWorkOrders(productionOrder);
      setShowCreateModal(false);
    }
  };

  const getProcessStatusColor = (processName) => {
    const wo = relatedWorkOrders.find(w => w.processName === processName);
    if (!wo) return 'bg-gray-200 text-gray-600';
    if (wo.status === '완료') return 'bg-green-100 text-green-700';
    if (wo.status === '진행중' || wo.status === '작업중') return 'bg-blue-100 text-blue-700';
    return 'bg-yellow-100 text-yellow-700';
  };

  return (
    <div className="space-y-6">
      {/* 상단 헤더 - 타이틀 위, 버튼 아래 */}
      <div className="space-y-3">
        {/* 타이틀 영역 */}
        <div className="flex items-center gap-4">
          <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
            <Factory className="w-6 h-6 text-blue-500" />
            생산지시 상세
          </h1>
          <div className="flex items-center gap-2 text-sm text-gray-500">
            <span className="font-mono">{productionOrder.productionOrderNo}</span>
            <StatusBadge status={productionOrder.status} />
          </div>
        </div>
        {/* 버튼 영역 */}
        <div className="flex items-center justify-end gap-2">
          <Button variant="outline" size="sm" onClick={onBack}>
            목록
          </Button>
          {!productionOrder.workOrdersGenerated && (
            <Button variant="primary" size="sm" onClick={() => setShowCreateModal(true)}>
              <ClipboardList className="w-4 h-4" /> 작업지시 생성
            </Button>
          )}
        </div>
      </div>

      {/* 공정 진행 현황 시각화 */}
      <div className="bg-white rounded-xl shadow-sm border p-6 mb-6">
        <h3 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
          <GitBranch className="w-5 h-5 text-blue-600" />
          공정 진행 현황
        </h3>

        <div className="flex items-center justify-between gap-2 overflow-x-auto pb-4">
          {productionOrder.processGroups?.map((pg, idx) => {
            const wo = relatedWorkOrders.find(w => w.processName === pg.processName);
            const isComplete = wo?.status === '완료';
            const isActive = wo?.status === '진행중' || wo?.status === '작업중';

            return (
              <React.Fragment key={idx}>
                <div className="flex flex-col items-center min-w-[100px]">
                  <div className={`w-12 h-12 rounded-full flex items-center justify-center mb-2 ${isComplete ? 'bg-green-500 text-white' :
                      isActive ? 'bg-blue-500 text-white animate-pulse' :
                        wo ? 'bg-yellow-100 text-yellow-700' : 'bg-gray-200 text-gray-500'
                    }`}>
                    {isComplete ? <CheckCircle className="w-6 h-6" /> :
                      isActive ? <Play className="w-6 h-6" /> :
                        <span className="font-bold">{pg.processSeq}</span>}
                  </div>
                  <span className="text-sm font-medium text-center">{pg.processName}</span>
                  <span className="text-xs text-gray-500">
                    {wo ? wo.status : '대기'}
                  </span>
                  {wo && (
                    <button
                      onClick={() => onNavigate('work-order-detail', wo)}
                      className="text-xs text-blue-600 hover:underline mt-1"
                    >
                      {wo.workOrderNo}
                    </button>
                  )}
                </div>
                {idx < productionOrder.processGroups.length - 1 && (
                  <div className={`flex-1 h-1 rounded ${isComplete ? 'bg-green-500' : 'bg-gray-200'
                    }`} style={{ minWidth: '30px' }} />
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* 정보 카드들 */}
      <div className="grid md:grid-cols-2 gap-6 mb-6">
        {/* 기본 정보 */}
        <div className="bg-white rounded-xl shadow-sm border p-6">
          <h3 className="font-bold text-gray-900 mb-4">기본 정보</h3>
          <div className="space-y-3">
            <div className="flex justify-between">
              <span className="text-gray-500">생산지시번호</span>
              <span className="font-medium">{productionOrder.productionOrderNo}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-500">수주번호</span>
              <button
                onClick={() => onNavigate('order-detail', relatedOrder)}
                className="text-blue-600 hover:underline font-medium"
              >
                {productionOrder.orderNo}
              </button>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-500">생산지시일</span>
              <span>{productionOrder.productionOrderDate}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-500">납기일</span>
              <span className="font-medium text-red-600">{productionOrder.dueDate}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-500">수량</span>
              <span className="font-medium">{productionOrder.qty}개</span>
            </div>
          </div>
        </div>

        {/* 거래처/현장 정보 */}
        <div className="bg-white rounded-xl shadow-sm border p-6">
          <h3 className="font-bold text-gray-900 mb-4">거래처/현장 정보</h3>
          <div className="space-y-3">
            <div className="flex justify-between">
              <span className="text-gray-500">거래처</span>
              <span className="font-medium">{productionOrder.customerName}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-500">현장명</span>
              <span className="font-medium">{productionOrder.siteName}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-500">제품유형</span>
              <span>{productionOrder.productType}</span>
            </div>
          </div>
        </div>
      </div>

      {/* BOM 품목별 공정 매핑 */}
      <div className="bg-white rounded-xl shadow-sm border p-6 mb-6">
        <h3 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
          <Package className="w-5 h-5 text-purple-600" />
          BOM 품목별 공정 분류
        </h3>
        <div className="space-y-4">
          {productionOrder.processGroups?.map((pg, idx) => (
            <div key={idx} className="border rounded-lg overflow-hidden">
              <div className={`px-4 py-2 font-medium flex items-center gap-2 ${getProcessStatusColor(pg.processName)}`}>
                <span className="w-6 h-6 rounded-full bg-white/50 flex items-center justify-center text-sm font-bold">
                  {pg.processSeq}
                </span>
                {pg.processName} 공정
                <span className="ml-auto text-sm">({pg.items?.length || 0}개 품목)</span>
              </div>
              <div className="p-4 bg-gray-50">
                <div className="grid gap-2">
                  {pg.items?.map((item, itemIdx) => (
                    <div key={itemIdx} className="flex items-center gap-3 text-sm">
                      <span className="text-gray-500">{item.itemCode}</span>
                      <span className="font-medium">{item.itemName}</span>
                      <span className="text-gray-600">{item.qty} {item.unit}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 작업지시서 목록 */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-bold text-gray-900 flex items-center gap-2">
            <ClipboardList className="w-5 h-5 text-blue-600" />
            작업지시서 목록
          </h3>
          {relatedWorkOrders.length === 0 && (
            <button
              onClick={() => setShowCreateModal(true)}
              className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2 text-sm"
            >
              <Play className="w-4 h-4" />
              작업지시 일괄생성
            </button>
          )}
        </div>

        {relatedWorkOrders.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-gray-600">작업지시번호</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-gray-600">공정</th>
                  <th className="px-4 py-2 text-center text-xs font-semibold text-gray-600">수량</th>
                  <th className="px-4 py-2 text-center text-xs font-semibold text-gray-600">상태</th>
                  <th className="px-4 py-2 text-center text-xs font-semibold text-gray-600">담당자</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {relatedWorkOrders.map(wo => (
                  <tr key={wo.id} className="hover:bg-gray-50">
                    <td className="px-4 py-2">
                      <button
                        onClick={() => onNavigate('work-order-detail', wo)}
                        className="text-blue-600 hover:underline text-sm font-medium"
                      >
                        {wo.workOrderNo}
                      </button>
                    </td>
                    <td className="px-4 py-2 text-sm">{wo.processName}</td>
                    <td className="px-4 py-2 text-sm text-center">{wo.qty}개</td>
                    <td className="px-4 py-2 text-center">
                      <StatusBadge status={wo.status} />
                    </td>
                    <td className="px-4 py-2 text-sm text-center text-gray-600">{wo.worker || '-'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="text-center py-8 text-gray-500">
            <ClipboardList className="w-12 h-12 mx-auto mb-3 text-gray-300" />
            <p className="mb-2">아직 작업지시서가 생성되지 않았습니다</p>
            <p className="text-sm">위 버튼을 클릭하여 BOM 기반 작업지시서를 자동 생성하세요</p>
          </div>
        )}
      </div>

      {/* 절곡 부품 전개도 정보 (FOLD/절곡 공정이 있는 경우에만 표시) */}
      {(productionOrder.processGroups?.some(pg => pg.processName === 'FOLD' || pg.processName === '절곡') || productionOrder.productType === '절곡') && (
        <div className="bg-white rounded-xl shadow-sm border p-6">
          <h3 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
            <Layers className="w-5 h-5 text-orange-600" />
            절곡 부품 전개도 정보
          </h3>

          {/* 전개도 섹션들 */}
          <div className="space-y-6">
            {/* 1. 벽면형 섹션 */}
            <div className="border rounded-lg overflow-hidden">
              <div className="bg-orange-50 px-4 py-2 font-medium text-orange-800">
                1.1 벽면형 [120·70]
              </div>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600 w-16">부품코드</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">세부품명</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">재질</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">LOT NO</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">길이/규격</th>
                      <th className="px-3 py-2 text-center text-xs font-semibold text-gray-600 w-20">수량</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">①</td>
                      <td className="px-3 py-2 text-sm">마감재</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.15T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-001</td>
                      <td className="px-3 py-2 text-sm">4300</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">8</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">②</td>
                      <td className="px-3 py-2 text-sm">가이드레일</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.6T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-002</td>
                      <td className="px-3 py-2 text-sm">3000</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">4</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">③</td>
                      <td className="px-3 py-2 text-sm">C형</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.55T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-003</td>
                      <td className="px-3 py-2 text-sm">4300</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">4</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">④</td>
                      <td className="px-3 py-2 text-sm">D형</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.6T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-004</td>
                      <td className="px-3 py-2 text-sm">4300</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">4</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">⑤</td>
                      <td className="px-3 py-2 text-sm">별도마감재</td>
                      <td className="px-3 py-2 text-sm text-gray-600">SUS1.2T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-005</td>
                      <td className="px-3 py-2 text-sm">4300</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">2</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-gray-400">-</td>
                      <td className="px-3 py-2 text-sm">하부BASE</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.55T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-006</td>
                      <td className="px-3 py-2 text-sm">하부BASE 130·80</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">4</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            {/* 2. 하단마감재 섹션 */}
            <div className="border rounded-lg overflow-hidden">
              <div className="bg-orange-50 px-4 py-2 font-medium text-orange-800">
                2. 하단마감재 [60·40]
              </div>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600 w-16">부품코드</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">세부품명</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">재질</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">LOT NO</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">길이/규격</th>
                      <th className="px-3 py-2 text-center text-xs font-semibold text-gray-600 w-20">수량</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">①</td>
                      <td className="px-3 py-2 text-sm">하단마감재</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.55T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-007</td>
                      <td className="px-3 py-2 text-sm">3000</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">4</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">②</td>
                      <td className="px-3 py-2 text-sm">하단보강엘바</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.55T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-009</td>
                      <td className="px-3 py-2 text-sm">3000</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">4</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">③</td>
                      <td className="px-3 py-2 text-sm">하단보강평철</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.15T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-010</td>
                      <td className="px-3 py-2 text-sm">3000</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">2</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">④</td>
                      <td className="px-3 py-2 text-sm">별도마감재</td>
                      <td className="px-3 py-2 text-sm text-gray-600">SUS1.2T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-008</td>
                      <td className="px-3 py-2 text-sm">3000</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">2</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            {/* 3. 케이스 섹션 */}
            <div className="border rounded-lg overflow-hidden">
              <div className="bg-orange-50 px-4 py-2 font-medium text-orange-800">
                3.1 케이스 [500*330]
              </div>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600 w-16">부품코드</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">세부품명</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">재질</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">LOT NO</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">길이/규격</th>
                      <th className="px-3 py-2 text-center text-xs font-semibold text-gray-600 w-20">수량</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">①</td>
                      <td className="px-3 py-2 text-sm">전면부</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.55T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-011</td>
                      <td className="px-3 py-2 text-sm">3000/2438</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">2</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">②</td>
                      <td className="px-3 py-2 text-sm">린텔부</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.55T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-012</td>
                      <td className="px-3 py-2 text-sm">3000/2438</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">2</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">③⑤</td>
                      <td className="px-3 py-2 text-sm">하부점검구</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.55T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-013</td>
                      <td className="px-3 py-2 text-sm">3000/2438</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">4</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">④</td>
                      <td className="px-3 py-2 text-sm">후면코너부</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.55T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-014</td>
                      <td className="px-3 py-2 text-sm">3000/2438</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">4</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">⑥</td>
                      <td className="px-3 py-2 text-sm">상부덮개</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.55T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-015</td>
                      <td className="px-3 py-2 text-sm">1220</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">5</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-orange-600">⑦</td>
                      <td className="px-3 py-2 text-sm">측면부(마구리)</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EGI1.55T</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-016</td>
                      <td className="px-3 py-2 text-sm">505*385</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">4</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            {/* 4. 연기차단재 섹션 */}
            <div className="border rounded-lg overflow-hidden">
              <div className="bg-orange-50 px-4 py-2 font-medium text-orange-800">
                4. 연기차단재
              </div>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600 w-16">부품코드</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">세부품명</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">재질</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">LOT NO</th>
                      <th className="px-3 py-2 text-left text-xs font-semibold text-gray-600">길이/규격</th>
                      <th className="px-3 py-2 text-center text-xs font-semibold text-gray-600 w-20">수량</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-gray-400">-</td>
                      <td className="px-3 py-2 text-sm">레일용 [W50]</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EG0.8T + 화이바 글라스</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-017</td>
                      <td className="px-3 py-2 text-sm">W50</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">8</td>
                    </tr>
                    <tr className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-medium text-gray-400">-</td>
                      <td className="px-3 py-2 text-sm">케이스용 [W80]</td>
                      <td className="px-3 py-2 text-sm text-gray-600">EG0.8T + 화이바 글라스</td>
                      <td className="px-3 py-2 text-sm font-mono text-gray-500">LOT-M-2024-018</td>
                      <td className="px-3 py-2 text-sm">W80</td>
                      <td className="px-3 py-2 text-sm text-center font-medium">4</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          {/* 전개도 요약 정보 */}
          <div className="mt-4 p-4 bg-gray-50 rounded-lg">
            <div className="grid grid-cols-3 gap-4 text-sm">
              <div>
                <span className="text-gray-500">총 부품 종류:</span>
                <span className="ml-2 font-medium">18개</span>
              </div>
              <div>
                <span className="text-gray-500">총 중량:</span>
                <span className="ml-2 font-medium">25.8 kg</span>
              </div>
              <div>
                <span className="text-gray-500">비고:</span>
                <span className="ml-2 text-gray-600">V컷팅 작업 완료 후 절곡 진행</span>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 작업지시 생성 모달 */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-lg w-full">
            <div className="p-6 border-b">
              <h3 className="text-lg font-bold flex items-center gap-2">
                <Play className="w-5 h-5 text-green-600" />
                작업지시서 자동 생성
              </h3>
            </div>
            <div className="p-6">
              <p className="mb-4">다음 공정에 대한 작업지시서가 생성됩니다:</p>
              <div className="space-y-2 mb-4">
                {productionOrder.processGroups?.map((pg, idx) => (
                  <div key={idx} className="flex items-center gap-3 p-2 bg-gray-50 rounded-lg">
                    <div className="w-6 h-6 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center text-xs font-bold">
                      {pg.processSeq}
                    </div>
                    <span className="font-medium">{pg.processName} 공정</span>
                    <span className="text-sm text-gray-500">({pg.items?.length || 0}개 품목)</span>
                  </div>
                ))}
              </div>
              <p className="text-sm text-gray-600">
                생성된 작업지시서는 생산팀에서 확인하고 작업을 진행할 수 있습니다.
              </p>
            </div>
            <div className="p-4 border-t bg-gray-50 flex justify-end gap-2">
              <button
                onClick={() => setShowCreateModal(false)}
                className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg"
              >
                취소
              </button>
              <button
                onClick={handleCreateWorkOrders}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2"
              >
                <Play className="w-4 h-4" />
                작업지시 생성
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const WorkOrderList = ({ workOrders, orders = [], onNavigate, onApprove, onAssign, onStartWork, onCompleteWork, onProgressWork, onDeleteWorkOrders }) => {
  // 수주 lotNo 조회 헬퍼 함수
  const getOrderLotNo = (orderId) => {
    const order = orders.find(o => o.id === orderId);
    return order?.lotNo || '-';
  };

  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [processFilter, setProcessFilter] = useState('all');
  const [viewMode, setViewMode] = useState('list'); // 'list' | 'manager'

  // 체크박스 선택 상태
  const [selectedIds, setSelectedIds] = useState([]);
  const [showDeleteModal, setShowDeleteModal] = useState(false);

  // ★ 공정 진행 모달 상태
  const [showProgressModal, setShowProgressModal] = useState(false);
  const [selectedWorkOrder, setSelectedWorkOrder] = useState(null);
  const [progressData, setProgressData] = useState({
    completedQty: 0,
    defectQty: 0,
    currentStep: '',
    note: ''
  });

  // ★ 공정 진행 모달 열기
  const handleOpenProgressModal = (wo) => {
    setSelectedWorkOrder(wo);
    setProgressData({
      completedQty: wo.completedQty || 0,
      defectQty: wo.defectQty || 0,
      currentStep: wo.currentStep || '',
      note: ''
    });
    setShowProgressModal(true);
  };

  // ★ 공정 진행 저장
  const handleSaveProgress = () => {
    if (selectedWorkOrder && onProgressWork) {
      onProgressWork(selectedWorkOrder.id, progressData);
    }
    setShowProgressModal(false);
    setSelectedWorkOrder(null);
  };

  // 공정별 단계 정의
  const getProcessSteps = (processType) => {
    const steps = {
      '스크린': ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'],
      '슬랫': ['코일절단', '중간검사', '미미작업', '포장'],
      '절곡': ['절단', '절곡', '중간검사', '포장'],
      '재고생산': ['절단', '절곡', '중간검사', '입고'],
    };
    return steps[processType] || ['작업준비', '작업진행', '검사', '완료'];
  };

  // ★ 담당자 배정 모달 상태
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [selectedForAssign, setSelectedForAssign] = useState(null);
  const [selectedAssignees, setSelectedAssignees] = useState([]);

  // 공정별 관리자 정보
  const processManagers = {
    '절곡': { name: '김절곡', unit: 'kg→장', desc: '자재LOT 선택 후 수량 지정' },
    '스크린': { name: '이스크린', unit: 'W×H', desc: '수주W × 자재LOT H 조합' },
    '슬랫': { name: '박슬랫', unit: '자동산출', desc: '높이 기반 절단매수 계산' },
  };

  // ★ 팀별 작업자 정의
  const teams = [
    { id: 'screen', name: '스크린팀', members: ['김스크린', '이스크린', '박스크린'] },
    { id: 'slat', name: '슬랫팀', members: ['김슬랫', '이슬랫', '박슬랫'] },
    { id: 'bending', name: '절곡팀', members: ['김절곡', '이절곡'] },
    { id: 'production', name: '생산팀', members: ['김생산', '이생산', '박생산'] },
  ];

  // ★ 담당자 표시 헬퍼 함수 (팀명/다중/개인 구분)
  const formatAssigneeDisplay = (wo) => {
    const assignees = wo.assignees || (wo.assignee ? wo.assignee.split(', ') : []);
    if (assignees.length === 0) return { text: '미배정', type: 'none', color: 'red' };
    if (assignees.length === 1) return { text: assignees[0], type: 'single', color: 'gray' };

    // 팀 전체 선택 여부 확인
    for (const team of teams) {
      const allInTeam = team.members.every(m => assignees.includes(m));
      const anyInTeam = team.members.some(m => assignees.includes(m));
      if (allInTeam && assignees.length === team.members.length) {
        return { text: team.name, type: 'team', color: 'blue', members: team.members };
      }
      if (allInTeam && assignees.length > team.members.length) {
        const othersCount = assignees.length - team.members.length;
        return { text: `${team.name} 외 ${othersCount}명`, type: 'team-plus', color: 'blue', members: assignees };
      }
    }

    // 여러 명이지만 팀 전체는 아닌 경우
    if (assignees.length > 2) {
      return { text: `${assignees[0]} 외 ${assignees.length - 1}명`, type: 'multi', color: 'green', members: assignees };
    }
    return { text: assignees.join(', '), type: 'multi', color: 'green', members: assignees };
  };

  const pendingApprovalCount = workOrders.filter(w => w.approvalStatus === '승인대기').length;
  const unassignedCount = workOrders.filter(w => !w.assignee && w.status === '작업대기').length;

  const tabs = [
    { id: 'all', label: '전체', count: workOrders.length },
    { id: 'unassigned', label: '미배정', count: unassignedCount, highlight: unassignedCount > 0 },
    { id: 'pending-approval', label: '승인대기', count: pendingApprovalCount, highlight: pendingApprovalCount > 0 },
    { id: 'waiting', label: '작업대기', count: workOrders.filter(w => w.status === '작업대기' && w.approvalStatus !== '승인대기').length },
    { id: 'working', label: '작업중', count: workOrders.filter(w => w.status === '작업중').length },
    { id: 'complete', label: '작업완료', count: workOrders.filter(w => w.status === '작업완료').length },
  ];

  const processTypes = ['전체', '스크린', '슬랫', '절곡', '재고생산'];

  const statusFilter = {
    all: () => true,
    unassigned: (w) => !w.assignee && w.status === '작업대기',
    'pending-approval': (w) => w.approvalStatus === '승인대기',
    waiting: (w) => w.status === '작업대기' && w.approvalStatus !== '승인대기',
    working: (w) => w.status === '작업중',
    complete: (w) => w.status === '작업완료',
  };

  // 승인 처리 함수
  const handleApprove = (wo, e) => {
    e.stopPropagation();
    if (onApprove) {
      onApprove(wo.id);
    }
  };

  // ★ 담당자 배정 모달 열기
  const handleOpenAssignModal = (wo, e) => {
    e?.stopPropagation();
    setSelectedForAssign(wo);
    setSelectedAssignees(wo.assignees || (wo.assignee ? wo.assignee.split(', ') : []));
    setShowAssignModal(true);
  };

  // ★ 담당자 토글
  const handleWorkerToggle = (worker) => {
    setSelectedAssignees(prev => {
      const exists = prev.includes(worker);
      return exists ? prev.filter(a => a !== worker) : [...prev, worker];
    });
  };

  // ★ 팀 전체 선택
  const handleTeamSelect = (team) => {
    const allSelected = team.members.every(m => selectedAssignees.includes(m));
    if (allSelected) {
      setSelectedAssignees(prev => prev.filter(a => !team.members.includes(a)));
    } else {
      setSelectedAssignees(prev => [...new Set([...prev, ...team.members])]);
    }
  };

  // ★ 담당자 배정 저장
  const handleSaveAssignment = () => {
    if (selectedForAssign && onAssign) {
      onAssign(selectedForAssign.id, selectedAssignees);
    }
    setShowAssignModal(false);
    setSelectedForAssign(null);
    setSelectedAssignees([]);
  };

  // ID 내림차순 정렬 - 최신 등록 최상단
  const filtered = workOrders
    .filter(statusFilter[activeTab])
    .filter(w => processFilter === 'all' || processFilter === '전체' || w.processType === processFilter)
    .filter(w =>
      w.workOrderNo.toLowerCase().includes(search.toLowerCase()) ||
      (w.customerName || '').includes(search) ||
      (w.siteName || '').includes(search)
    )
    .sort((a, b) => b.id - a.id);

  // 전체 선택/해제
  const handleSelectAll = (e) => {
    if (e.target.checked) {
      setSelectedIds(filtered.map(w => w.id));
    } else {
      setSelectedIds([]);
    }
  };

  // 개별 선택
  const handleSelectOne = (id, e) => {
    e.stopPropagation();
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  };

  // 삭제 확인
  const handleDeleteConfirm = () => {
    if (onDeleteWorkOrders && selectedIds.length > 0) {
      onDeleteWorkOrders(selectedIds);
    }
    setSelectedIds([]);
    setShowDeleteModal(false);
  };

  return (
    <div className="space-y-6">
      <PageHeader
        icon={ClipboardList}
        title="작업지시 목록"
        actions={
          <Button variant="primary" onClick={() => onNavigate('work-order-register')}>
            <Plus className="w-4 h-4" /> 등록
          </Button>
        }
      />

      {/* 대시보드 - 4개 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border p-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
              <ClipboardList className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <p className="text-sm" style={{ color: '#000000' }}>전체</p>
              <p className="text-xl font-bold" style={{ color: '#000000' }}>{workOrders.length}건</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center">
              <Clock className="w-5 h-5 text-yellow-600" />
            </div>
            <div>
              <p className="text-sm" style={{ color: '#000000' }}>작업대기</p>
              <p className="text-xl font-bold" style={{ color: '#000000' }}>{workOrders.filter(w => w.status === '작업대기').length}건</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
              <Factory className="w-5 h-5 text-purple-600" />
            </div>
            <div>
              <p className="text-sm" style={{ color: '#000000' }}>작업중</p>
              <p className="text-xl font-bold" style={{ color: '#000000' }}>{workOrders.filter(w => w.status === '작업중').length}건</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
              <CheckCircle className="w-5 h-5 text-green-600" />
            </div>
            <div>
              <p className="text-sm" style={{ color: '#000000' }}>작업완료</p>
              <p className="text-xl font-bold" style={{ color: '#000000' }}>{workOrders.filter(w => w.status === '작업완료').length}건</p>
            </div>
          </div>
        </div>
      </div>

      {/* 검색 */}
      <SearchInput
        placeholder="작업지시번호, 발주처, 현장명 검색..."
        value={search}
        onChange={setSearch}
      />

      {viewMode === 'list' && (
        <TabFilter tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />
      )}

      {/* 공정관리뷰 */}
      {viewMode === 'manager' ? (
        <div className="space-y-6">
          {/* 공정별 관리자 카드 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {Object.entries(processManagers).map(([process, manager]) => {
              const processOrders = workOrders.filter(w => w.processType === process);
              const pending = processOrders.filter(w => w.status === '작업대기').length;
              const working = processOrders.filter(w => w.status === '작업중').length;
              const noMaterial = processOrders.filter(w => !w.materialInputted).length;
              const noAssignee = processOrders.filter(w => !w.assignee).length;

              return (
                <div key={process} className={`bg-white rounded-xl border-2 p-4 ${process === '절곡' ? 'border-orange-200' :
                    process === '스크린' ? 'border-blue-200' : 'border-purple-200'
                  }`}>
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center gap-2">
                      <span className={`px-2 py-1 rounded text-sm font-bold ${process === '절곡' ? 'bg-orange-100 text-orange-700' :
                          process === '스크린' ? 'bg-blue-100 text-blue-700' : 'bg-purple-100 text-purple-700'
                        }`}>{process}</span>
                      <span className="text-sm text-gray-600">관리자: {manager.name}</span>
                    </div>
                    <span className="text-xs text-gray-400">{manager.unit}</span>
                  </div>
                  <p className="text-xs text-gray-500 mb-3">{manager.desc}</p>

                  <div className="grid grid-cols-2 gap-2 text-center">
                    <div className="bg-yellow-50 rounded p-2">
                      <p className="text-lg font-bold text-yellow-600">{pending}</p>
                      <p className="text-xs text-yellow-700">대기</p>
                    </div>
                    <div className="bg-blue-50 rounded p-2">
                      <p className="text-lg font-bold text-blue-600">{working}</p>
                      <p className="text-xs text-blue-700">진행중</p>
                    </div>
                    <div className="bg-red-50 rounded p-2">
                      <p className="text-lg font-bold text-red-600">{noMaterial}</p>
                      <p className="text-xs text-red-700">미투입</p>
                    </div>
                    <div className="bg-gray-50 rounded p-2">
                      <p className="text-lg font-bold text-gray-600">{noAssignee}</p>
                      <p className="text-xs text-gray-700">미배정</p>
                    </div>
                  </div>

                  <button
                    onClick={() => setProcessFilter(process)}
                    className={`w-full mt-3 py-2 text-sm rounded-lg transition-colors ${process === '절곡' ? 'bg-orange-500 hover:bg-orange-600 text-white' :
                        process === '스크린' ? 'bg-blue-500 hover:bg-blue-600 text-white' : 'bg-purple-500 hover:bg-purple-600 text-white'
                      }`}
                  >
                    상세보기
                  </button>
                </div>
              );
            })}
          </div>

          {/* 선택된 공정의 작업지시 목록 */}
          {processFilter !== 'all' && processFilter !== '전체' && (
            <div className="bg-white rounded-xl border overflow-hidden">
              <div className="px-4 py-3 bg-gray-50 border-b flex items-center justify-between">
                <h3 className="font-medium text-gray-900">{processFilter} 공정 작업지시 현황</h3>
                <button
                  onClick={() => setProcessFilter('전체')}
                  className="text-sm text-gray-500 hover:text-gray-700"
                >
                  전체보기
                </button>
              </div>
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">작업지시번호</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">현장/수주LOT</th>
                    <th className="px-3 py-2 text-center text-xs font-medium text-gray-500">자재투입</th>
                    <th className="px-3 py-2 text-center text-xs font-medium text-gray-500">작업시작</th>
                    <th className="px-3 py-2 text-center text-xs font-medium text-gray-500">작업자배정</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">작업일</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">우선순위</th>
                    <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">납기일</th>
                    <th className="px-3 py-2 text-center text-xs font-medium text-gray-500">액션</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {filtered.filter(w => w.processType === processFilter).map((wo) => (
                    <tr key={wo.id} className="hover:bg-gray-50">
                      <td className="px-3 py-2 text-sm font-mono text-blue-600">{wo.workOrderNo}</td>
                      <td className="px-3 py-2">
                        <p className="text-sm text-gray-900">{wo.siteName}</p>
                        <p className="text-xs text-gray-500">{wo.orderNo}</p>
                      </td>
                      <td className="px-3 py-2 text-center">
                        {wo.materialInputted ? (
                          <span className="inline-flex items-center justify-center w-6 h-6 bg-green-100 rounded-full">
                            <CheckCircle className="w-4 h-4 text-green-600" />
                          </span>
                        ) : (
                          <span className="inline-flex items-center justify-center w-6 h-6 bg-red-100 rounded-full">
                            <X className="w-4 h-4 text-red-600" />
                          </span>
                        )}
                      </td>
                      <td className="px-3 py-2 text-center">
                        {wo.status === '작업중' || wo.status === '작업완료' ? (
                          <span className="inline-flex items-center justify-center w-6 h-6 bg-green-100 rounded-full">
                            <CheckCircle className="w-4 h-4 text-green-600" />
                          </span>
                        ) : (
                          <span className="inline-flex items-center justify-center w-6 h-6 bg-gray-100 rounded-full">
                            <Clock className="w-4 h-4 text-gray-400" />
                          </span>
                        )}
                      </td>
                      <td className="px-3 py-2 text-center">
                        {(() => {
                          const assigneeInfo = formatAssigneeDisplay(wo);
                          return (
                            <div
                              className="group relative cursor-pointer"
                              onClick={(e) => { e.stopPropagation(); handleOpenAssignModal(wo, e); }}
                            >
                              <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium
                                ${assigneeInfo.color === 'red' ? 'bg-red-100 text-red-700' : ''}
                                ${assigneeInfo.color === 'gray' ? 'bg-gray-100 text-gray-700' : ''}
                                ${assigneeInfo.color === 'blue' ? 'bg-blue-100 text-blue-700' : ''}
                                ${assigneeInfo.color === 'green' ? 'bg-green-100 text-green-700' : ''}
                              `}>
                                {assigneeInfo.type === 'team' && <Users className="w-3 h-3" />}
                                {assigneeInfo.text}
                              </span>
                              {/* 툴팁: 여러 명일 때 전체 목록 표시 */}
                              {assigneeInfo.members && (
                                <div className="absolute z-10 hidden group-hover:block bottom-full left-1/2 -translate-x-1/2 mb-1 px-2 py-1 bg-gray-800 text-white text-xs rounded whitespace-nowrap">
                                  {assigneeInfo.members.join(', ')}
                                </div>
                              )}
                            </div>
                          );
                        })()}
                      </td>
                      <td className="px-3 py-2 text-sm text-gray-900">{wo.orderDate}</td>
                      <td className="px-3 py-2"><StatusBadge status={wo.priority} /></td>
                      <td className="px-3 py-2 text-sm text-gray-900">{wo.dueDate}</td>
                      <td className="px-3 py-2 text-center">
                        <button
                          onClick={() => onNavigate('work-order-detail', wo)}
                          className="px-2 py-1 text-xs bg-gray-100 hover:bg-gray-200 rounded transition-colors"
                        >
                          상세
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      ) : (
        /* 기존 목록뷰 */
        <div className="bg-white rounded-xl border overflow-hidden">
          {/* 선택 삭제 버튼 (2개 이상 선택 시) */}
          {selectedIds.length >= 2 && (
            <div className="px-4 py-3 bg-gray-50 border-b flex items-center justify-between">
              <span className="text-sm text-gray-600">
                {selectedIds.length}개 항목 선택됨
              </span>
              <button
                onClick={() => setShowDeleteModal(true)}
                className="px-4 py-2 bg-red-600 text-white text-sm rounded-lg hover:bg-red-700 flex items-center gap-2"
              >
                <Trash2 className="w-4 h-4" />
                선택 삭제({selectedIds.length})
              </button>
            </div>
          )}
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-2 py-3 text-center text-xs font-medium text-gray-500 w-10">
                  <input
                    type="checkbox"
                    checked={selectedIds.length === filtered.length && filtered.length > 0}
                    onChange={handleSelectAll}
                    onClick={(e) => e.stopPropagation()}
                    className="rounded"
                  />
                </th>
                <th className="px-2 py-3 text-center text-xs font-medium text-gray-500 w-12">번호</th>
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">작업지시번호</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">공정</th>
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">로트번호</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">지시일</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">배정</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">투입</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">시작</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">작업상태</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">우선순위</th>
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">현장명</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">출고예정일</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {filtered.map((wo, idx) => {
                const isSelected = selectedIds.includes(wo.id);
                const isOnlySelected = selectedIds.length === 1 && isSelected;
                // ★ 공정진행현황 계산 (stepStatus에서 현재 단계 추출)
                const getCurrentStep = () => {
                  if (!wo.stepStatus) return wo.currentStep || '대기';
                  const steps = Object.entries(wo.stepStatus);
                  const inProgressStep = steps.find(([, status]) => status === '진행중');
                  if (inProgressStep) return inProgressStep[0];
                  const lastCompleted = steps.filter(([, status]) => status === '완료').pop();
                  if (lastCompleted) return lastCompleted[0] + ' 완료';
                  return wo.currentStep || '대기';
                };
                const currentStepDisplay = getCurrentStep();

                return (
                  <tr
                    key={wo.id}
                    className={`hover:bg-gray-50 cursor-pointer ${isSelected ? 'bg-blue-50' : ''}`}
                    onClick={() => onNavigate('work-order-detail', wo)}
                  >
                    {/* 체크박스 */}
                    <td className="px-2 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                      <input
                        type="checkbox"
                        checked={isSelected}
                        onChange={() => handleSelect(wo.id)}
                        className="rounded"
                      />
                    </td>
                    {/* 번호 */}
                    <td className="px-2 py-3 text-center text-sm text-gray-500">{filtered.length - idx}</td>
                    {/* 작업지시번호 */}
                    <td className="px-3 py-3 text-sm text-blue-600 font-medium">{wo.workOrderNo || wo.id || '-'}</td>
                    {/* 공정 */}
                    <td className="px-3 py-3 text-center text-sm text-gray-900">{wo.processType || currentStepDisplay || '-'}</td>
                    {/* 로트번호 (작업지시 직접 또는 수주 로트번호) */}
                    <td className="px-3 py-3 text-sm text-gray-900 font-mono">{wo.lotNo || wo.productionLotNo || getOrderLotNo(wo.orderId)}</td>
                    {/* 지시일 */}
                    <td className="px-3 py-3 text-center text-sm text-gray-900">{wo.orderDate || wo.instructionDate || '-'}</td>
                    {/* 배정 (업무 흐름: 지시일 → 배정 → 투입 → 시작) */}
                    <td className="px-3 py-3 text-center">
                      <span className={`inline-flex items-center justify-center w-5 h-5 rounded text-xs
                        ${wo.assignStatus === 'Y' || wo.assignee ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-400'}
                      `}>
                        {wo.assignStatus === 'Y' || wo.assignee ? 'Y' : '-'}
                      </span>
                    </td>
                    {/* 투입 (materialInputs 배열에 데이터가 있으면 투입 완료) */}
                    <td className="px-3 py-3 text-center">
                      <span className={`inline-flex items-center justify-center w-5 h-5 rounded text-xs
                        ${wo.inputStatus === 'Y' || wo.isInputted || (wo.materialInputs && wo.materialInputs.length > 0) ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-400'}
                      `}>
                        {wo.inputStatus === 'Y' || wo.isInputted || (wo.materialInputs && wo.materialInputs.length > 0) ? 'Y' : '-'}
                      </span>
                    </td>
                    {/* 시작 (작업중/작업완료 상태이거나 startedAt/startTime이 있으면 시작됨) */}
                    <td className="px-3 py-3 text-center">
                      <span className={`inline-flex items-center justify-center w-5 h-5 rounded text-xs
                        ${wo.startStatus === 'Y' || wo.isStarted || wo.startedAt || wo.startTime || wo.status === '작업중' || wo.status === '작업완료' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-400'}
                      `}>
                        {wo.startStatus === 'Y' || wo.isStarted || wo.startedAt || wo.startTime || wo.status === '작업중' || wo.status === '작업완료' ? 'Y' : '-'}
                      </span>
                    </td>
                    {/* 작업상태 */}
                    <td className="px-3 py-3 text-center">
                      <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium
                        ${wo.status === '완료' || currentStepDisplay.includes('완료') ? 'bg-green-100 text-green-700' : ''}
                        ${wo.status === '진행중' || (currentStepDisplay !== '대기' && !currentStepDisplay.includes('완료')) ? 'bg-blue-100 text-blue-700' : ''}
                        ${wo.status === '대기' || currentStepDisplay === '대기' ? 'bg-gray-100 text-gray-600' : ''}
                      `}>
                        {wo.status || currentStepDisplay || '대기'}
                      </span>
                    </td>
                    {/* 우선순위 */}
                    <td className="px-3 py-3 text-center">
                      <span className={`inline-flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold
                        ${wo.workPriority === 1 || wo.priority === '긴급' ? 'bg-red-100 text-red-700' : ''}
                        ${wo.workPriority === 2 || wo.priority === '높음' ? 'bg-orange-100 text-orange-700' : ''}
                        ${wo.workPriority === 3 || wo.priority === '보통' ? 'bg-yellow-100 text-yellow-700' : ''}
                        ${(!wo.workPriority || wo.workPriority > 3) && !wo.priority ? 'bg-gray-100 text-gray-600' : ''}
                      `}>
                        {wo.workPriority || (wo.priority === '긴급' ? 1 : wo.priority === '높음' ? 2 : wo.priority === '보통' ? 3 : '-')}
                      </span>
                    </td>
                    {/* 현장명 */}
                    <td className="px-3 py-3 text-sm text-gray-900">{wo.siteName || '-'}</td>
                    {/* 출고예정일 */}
                    <td className="px-3 py-3 text-center text-sm text-gray-900">{wo.shipRequestDate || wo.dueDate || '-'}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {/* ★ 담당자 배정 모달 */}
      {showAssignModal && selectedForAssign && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg mx-4">
            {/* 모달 헤더 */}
            <div className="flex items-center justify-between p-4 border-b">
              <div>
                <h3 className="text-lg font-bold text-gray-900">담당자 배정</h3>
                <p className="text-sm text-gray-500 mt-1">
                  {selectedForAssign.workOrderNo} - {selectedForAssign.processType}
                </p>
              </div>
              <button
                onClick={() => {
                  setShowAssignModal(false);
                  setSelectedForAssign(null);
                  setSelectedAssignees([]);
                }}
                className="p-2 hover:bg-gray-100 rounded-full transition-colors"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            {/* 작업지시 정보 */}
            <div className="p-4 bg-gray-50 border-b">
              <div className="grid grid-cols-2 gap-3 text-sm">
                <div>
                  <span className="text-gray-500">현장명:</span>
                  <span className="ml-2 font-medium">{selectedForAssign.siteName}</span>
                </div>
                <div>
                  <span className="text-gray-500">납기일:</span>
                  <span className="ml-2 font-medium">{selectedForAssign.dueDate}</span>
                </div>
                <div>
                  <span className="text-gray-500">우선순위:</span>
                  <span className={`ml-2 px-2 py-0.5 rounded text-xs font-medium ${selectedForAssign.priority === '긴급' ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-700'
                    }`}>
                    {selectedForAssign.priority}
                  </span>
                </div>
                <div>
                  <span className="text-gray-500">상태:</span>
                  <span className="ml-2"><StatusBadge status={selectedForAssign.status} /></span>
                </div>
              </div>
            </div>

            {/* 팀별 작업자 선택 */}
            <div className="p-4 space-y-4 max-h-80 overflow-y-auto">
              {teams.map(team => {
                const isFullySelected = team.members.every(m => selectedAssignees.includes(m));
                const isPartiallySelected = team.members.some(m => selectedAssignees.includes(m)) && !isFullySelected;

                return (
                  <div key={team.id} className="border rounded-lg overflow-hidden">
                    {/* 팀 헤더 */}
                    <button
                      onClick={() => handleTeamSelect(team)}
                      className={`w-full flex items-center justify-between p-3 transition-colors ${isFullySelected ? 'bg-blue-50' : isPartiallySelected ? 'bg-blue-50/50' : 'bg-gray-50 hover:bg-gray-100'
                        }`}
                    >
                      <div className="flex items-center gap-2">
                        <div className={`w-5 h-5 rounded border-2 flex items-center justify-center ${isFullySelected ? 'bg-blue-500 border-blue-500' :
                            isPartiallySelected ? 'bg-blue-200 border-blue-400' : 'border-gray-300'
                          }`}>
                          {(isFullySelected || isPartiallySelected) && (
                            <Check className="w-3 h-3 text-white" />
                          )}
                        </div>
                        <span className="font-medium text-gray-900">{team.name}</span>
                        <span className="text-xs text-gray-500">({team.members.length}명)</span>
                      </div>
                      <span className="text-xs text-blue-600">전체선택</span>
                    </button>

                    {/* 개별 작업자 */}
                    <div className="p-2 grid grid-cols-3 gap-2">
                      {team.members.map(worker => (
                        <button
                          key={worker}
                          onClick={() => handleWorkerToggle(worker)}
                          className={`flex items-center gap-2 p-2 rounded-lg text-sm transition-colors ${selectedAssignees.includes(worker)
                              ? 'bg-blue-100 text-blue-700 border border-blue-300'
                              : 'bg-white border border-gray-200 hover:border-blue-300 text-gray-700'
                            }`}
                        >
                          <div className={`w-4 h-4 rounded border flex items-center justify-center ${selectedAssignees.includes(worker) ? 'bg-blue-500 border-blue-500' : 'border-gray-300'
                            }`}>
                            {selectedAssignees.includes(worker) && (
                              <Check className="w-2.5 h-2.5 text-white" />
                            )}
                          </div>
                          <span>{worker}</span>
                        </button>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>

            {/* 선택된 담당자 표시 */}
            {selectedAssignees.length > 0 && (
              <div className="px-4 py-3 bg-blue-50 border-t border-blue-100">
                <p className="text-sm text-blue-700">
                  <span className="font-medium">선택된 담당자:</span> {selectedAssignees.join(', ')}
                </p>
              </div>
            )}

            {/* 모달 푸터 */}
            <div className="flex items-center justify-end gap-3 p-4 border-t bg-gray-50">
              <button
                onClick={() => {
                  setShowAssignModal(false);
                  setSelectedForAssign(null);
                  setSelectedAssignees([]);
                }}
                className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
              >
                취소
              </button>
              <button
                onClick={handleSaveAssignment}
                disabled={selectedAssignees.length === 0}
                className={`px-4 py-2 rounded-lg transition-colors ${selectedAssignees.length > 0
                    ? 'bg-blue-500 text-white hover:bg-blue-600'
                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                  }`}
              >
                <div className="flex items-center gap-2">
                  <Users className="w-4 h-4" />
                  배정 저장
                </div>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ★ 공정 진행 모달 */}
      {showProgressModal && selectedWorkOrder && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg mx-4">
            {/* 모달 헤더 */}
            <div className="flex items-center justify-between p-4 border-b">
              <div>
                <h3 className="text-lg font-bold text-gray-900">공정 진행 입력</h3>
                <p className="text-sm text-gray-500 mt-1">
                  {selectedWorkOrder.workOrderNo} - {selectedWorkOrder.processType}
                </p>
              </div>
              <button
                onClick={() => {
                  setShowProgressModal(false);
                  setSelectedWorkOrder(null);
                }}
                className="p-2 hover:bg-gray-100 rounded-full transition-colors"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            {/* 작업지시 정보 */}
            <div className="p-4 bg-gray-50 border-b">
              <div className="grid grid-cols-2 gap-3 text-sm">
                <div>
                  <span className="text-gray-500">현장명:</span>
                  <span className="ml-2 font-medium">{selectedWorkOrder.siteName}</span>
                </div>
                <div>
                  <span className="text-gray-500">담당자:</span>
                  <span className="ml-2 font-medium">{selectedWorkOrder.assignee || '미배정'}</span>
                </div>
                <div>
                  <span className="text-gray-500">총수량:</span>
                  <span className="ml-2 font-medium">{selectedWorkOrder.totalQty}개</span>
                </div>
                <div>
                  <span className="text-gray-500">납기일:</span>
                  <span className="ml-2 font-medium">{selectedWorkOrder.dueDate}</span>
                </div>
              </div>
            </div>

            {/* 공정 단계 선택 */}
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">현재 공정 단계</label>
                <div className="flex flex-wrap gap-2">
                  {getProcessSteps(selectedWorkOrder.processType).map((step, idx) => (
                    <button
                      key={step}
                      onClick={() => setProgressData(prev => ({ ...prev, currentStep: step }))}
                      className={`px-3 py-2 text-sm rounded-lg border transition-colors ${progressData.currentStep === step
                          ? 'bg-purple-500 text-white border-purple-500'
                          : 'bg-white text-gray-700 border-gray-200 hover:border-purple-300'
                        }`}
                    >
                      <span className="mr-1">{idx + 1}.</span> {step}
                    </button>
                  ))}
                </div>
              </div>

              {/* 수량 입력 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">완료 수량</label>
                  <input
                    type="number"
                    min="0"
                    max={selectedWorkOrder.totalQty}
                    value={progressData.completedQty}
                    onChange={(e) => setProgressData(prev => ({ ...prev, completedQty: parseInt(e.target.value) || 0 }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                  />
                  <p className="text-xs text-gray-500 mt-1">최대: {selectedWorkOrder.totalQty}개</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">불량 수량</label>
                  <input
                    type="number"
                    min="0"
                    value={progressData.defectQty}
                    onChange={(e) => setProgressData(prev => ({ ...prev, defectQty: parseInt(e.target.value) || 0 }))}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
                  />
                </div>
              </div>

              {/* 진행률 표시 */}
              <div>
                <div className="flex items-center justify-between mb-1">
                  <span className="text-sm text-gray-600">진행률</span>
                  <span className="text-sm font-medium text-purple-600">
                    {Math.round((progressData.completedQty / selectedWorkOrder.totalQty) * 100)}%
                  </span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-3">
                  <div
                    className="bg-purple-500 h-3 rounded-full transition-all"
                    style={{ width: `${Math.min((progressData.completedQty / selectedWorkOrder.totalQty) * 100, 100)}%` }}
                  />
                </div>
              </div>

              {/* 메모 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">작업 메모</label>
                <textarea
                  value={progressData.note}
                  onChange={(e) => setProgressData(prev => ({ ...prev, note: e.target.value }))}
                  placeholder="특이사항이나 메모를 입력하세요..."
                  rows={2}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                />
              </div>
            </div>

            {/* 모달 푸터 */}
            <div className="flex items-center justify-between p-4 border-t bg-gray-50">
              <div className="text-sm text-gray-500">
                {progressData.defectQty > 0 && (
                  <span className="text-red-500">불량 {progressData.defectQty}개 발생</span>
                )}
              </div>
              <div className="flex gap-3">
                <button
                  onClick={() => {
                    setShowProgressModal(false);
                    setSelectedWorkOrder(null);
                  }}
                  className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  취소
                </button>
                <button
                  onClick={handleSaveProgress}
                  className="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors flex items-center gap-2"
                >
                  <Save className="w-4 h-4" />
                  진행상황 저장
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4">
            <div className="p-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
                  <AlertTriangle className="w-6 h-6 text-red-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">삭제 확인</h3>
                  <p className="text-sm text-gray-500">선택한 항목을 삭제하시겠습니까?</p>
                </div>
              </div>
              <div className="bg-red-50 border border-red-200 rounded-lg p-3 mb-4">
                <p className="text-sm text-red-700">
                  <strong>{selectedIds.length}개</strong>의 작업지시가 삭제됩니다.
                  삭제된 데이터는 복구할 수 없습니다.
                </p>
              </div>
              <div className="flex justify-end gap-3">
                <button
                  onClick={() => setShowDeleteModal(false)}
                  className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  취소
                </button>
                <button
                  onClick={handleDeleteConfirm}
                  className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center gap-2"
                >
                  <Trash2 className="w-4 h-4" />
                  삭제
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 작업지시 등록
const WorkOrderCreate = ({ orders, customers, sites, onNavigate, onBack, onSave }) => {
  // 매출 거래처만 필터링 (발주처 선택용)
  const salesCustomers = customers?.filter(c => c.customerType === '매출') || [];
  // 공정관리에서 사용중인 공정 목록 동적으로 가져오기
  const activeProcesses = sampleProcesses.filter(p => p.isActive);
  const processTypes = activeProcesses.map(p => p.processName);

  // 등록 모드: 'order' (수주 연동) / 'manual' (수동 등록)
  const [registrationMode, setRegistrationMode] = useState('order');

  const [selectedOrder, setSelectedOrder] = useState(null);
  const [selectedSplit, setSelectedSplit] = useState(null);
  const [showOrderPanel, setShowOrderPanel] = useState(false);
  const [orderSearch, setOrderSearch] = useState('');
  const [formData, setFormData] = useState({
    processType: processTypes[0] || '스크린',
    processId: activeProcesses[0]?.id || null, // 공정 ID 연결
    processCode: activeProcesses[0]?.processCode || null, // 공정 코드 연결
    workSheetType: activeProcesses[0]?.workSheetType || null, // 작업일지 양식 연결
    dueDate: '',
    priority: 5, // 기본값: 5 (1=긴급, 5=일반, 9=낮음)
    assignees: [], // 다중 담당자 배열
    note: '',
    // 수동 등록용 필드
    customerId: '', // 거래처 ID
    customerName: '',
    siteId: '', // 현장 ID
    siteName: '',
    manualItems: [{ id: 1, itemName: '', specification: '', qty: 1, unit: 'EA' }],
  });
  const [showAssigneePanel, setShowAssigneePanel] = useState(false);

  // 선택한 거래처에 해당하는 현장 목록 필터링
  const filteredSites = formData.customerId
    ? (sites || []).filter(s => s.customerId === parseInt(formData.customerId))
    : [];

  // 유효성 검사 규칙 (수동 등록 모드에서만 적용)
  const validationRules = {
    customerId: { required: registrationMode === 'manual', label: '발주처', message: '발주처를 선택해주세요.' },
    siteId: { required: registrationMode === 'manual', label: '현장명', message: '현장명을 선택해주세요.' },
    dueDate: { required: registrationMode === 'manual', label: '출고예정일', message: '출고예정일을 선택해주세요.' },
  };
  const { errors, touched, hasError, getFieldError, validateForm, handleBlur, clearFieldError } = useFormValidation(formData, validationRules);

  // 수동 등록 시 품목 추가
  const addManualItem = () => {
    setFormData(prev => ({
      ...prev,
      manualItems: [...prev.manualItems, {
        id: Date.now(),
        itemName: '',
        specification: '',
        qty: 1,
        unit: 'EA'
      }]
    }));
  };

  // 수동 등록 시 품목 삭제
  const removeManualItem = (itemId) => {
    if (formData.manualItems.length <= 1) return;
    setFormData(prev => ({
      ...prev,
      manualItems: prev.manualItems.filter(item => item.id !== itemId)
    }));
  };

  // 수동 등록 시 품목 수정
  const updateManualItem = (itemId, field, value) => {
    setFormData(prev => ({
      ...prev,
      manualItems: prev.manualItems.map(item =>
        item.id === itemId ? { ...item, [field]: value } : item
      )
    }));
  };

  // 등록 모드 변경 시 데이터 초기화
  const handleModeChange = (mode) => {
    setRegistrationMode(mode);
    if (mode === 'manual') {
      setSelectedOrder(null);
      setSelectedSplit(null);
    }
  };

  // 생산지시 가능한 수주 (회계확인완료 상태)
  const availableOrders = orders.filter(o =>
    o.accountingStatus === '회계확인완료' || o.accountingStatus === '입금확인'
  );

  // 검색 필터링
  const filteredOrders = availableOrders.filter(order => {
    if (!orderSearch) return true;
    const search = orderSearch.toLowerCase();
    return (
      order.orderNo?.toLowerCase().includes(search) ||
      order.customerName?.toLowerCase().includes(search) ||
      order.siteName?.toLowerCase().includes(search)
    );
  });

  // 공정 선택 시 관련 정보도 함께 업데이트
  const handleProcessTypeChange = (processName) => {
    const selectedProcess = activeProcesses.find(p => p.processName === processName);
    setFormData(prev => ({
      ...prev,
      processType: processName,
      processId: selectedProcess?.id || null,
      processCode: selectedProcess?.processCode || null,
      workSheetType: selectedProcess?.workSheetType || null,
    }));
  };

  // 우선순위 1~9 (1=가장 긴급, 9=가장 낮음)
  const priorities = [1, 2, 3, 4, 5, 6, 7, 8, 9];

  // 팀별 작업자 정의 - 공정관리에서 동적으로 생성
  const teams = activeProcesses.map(p => ({
    id: p.processCode.toLowerCase(),
    name: `${p.processName}팀`,
    members: p.assignedWorkers || [`${p.processName}작업자1`, `${p.processName}작업자2`] // 공정에 배정된 작업자 또는 기본값
  }));
  const allWorkers = teams.flatMap(t => t.members);

  // 팀 전체 선택
  const handleTeamSelect = (team) => {
    const currentAssignees = formData.assignees;
    const allSelected = team.members.every(m => currentAssignees.includes(m));

    if (allSelected) {
      // 팀 전체 해제
      setFormData(prev => ({
        ...prev,
        assignees: prev.assignees.filter(a => !team.members.includes(a))
      }));
    } else {
      // 팀 전체 선택
      const newAssignees = [...new Set([...currentAssignees, ...team.members])];
      setFormData(prev => ({ ...prev, assignees: newAssignees }));
    }
  };

  // 개별 작업자 토글
  const handleWorkerToggle = (worker) => {
    setFormData(prev => {
      const exists = prev.assignees.includes(worker);
      return {
        ...prev,
        assignees: exists
          ? prev.assignees.filter(a => a !== worker)
          : [...prev.assignees, worker]
      };
    });
  };

  // 팀 선택 여부 확인
  const isTeamFullySelected = (team) => team.members.every(m => formData.assignees.includes(m));
  const isTeamPartiallySelected = (team) =>
    team.members.some(m => formData.assignees.includes(m)) && !isTeamFullySelected(team);

  const handleOrderSelect = (order) => {
    setSelectedOrder(order);
    setSelectedSplit(null);
    setShowOrderPanel(false);
    setFormData(prev => ({
      ...prev,
      dueDate: order.dueDate,
    }));
  };

  const handleClearOrder = () => {
    setSelectedOrder(null);
    setSelectedSplit(null);
    setFormData(prev => ({
      ...prev,
      dueDate: '',
    }));
  };

  const handleSplitSelect = (split) => {
    setSelectedSplit(split);
    if (split) {
      setFormData(prev => ({
        ...prev,
        dueDate: split.dueDate,
      }));
    }
  };

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 날짜를 YYMMDD 형식으로 변환
  const formatDateCode = (date) => {
    const d = new Date(date);
    const yy = String(d.getFullYear()).slice(-2);
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const dd = String(d.getDate()).padStart(2, '0');
    return `${yy}${mm}${dd}`;
  };

  const handleSubmit = () => {
    // 모드별 유효성 검사
    if (registrationMode === 'order') {
      if (!selectedOrder) {
        alert('수주를 선택해주세요.');
        return;
      }
    } else {
      // 수동 등록 모드 - 유효성 검사 훅 사용
      if (!validateForm()) {
        return;
      }
      const validItems = formData.manualItems.filter(item => item.itemName.trim());
      if (validItems.length === 0) {
        alert('최소 1개 이상의 품목을 입력해주세요.');
        return;
      }
    }

    // 생산LOT 생성: KD-PL-YYMMDD-순번
    const dateCode = formatDateCode(new Date());
    const seq = String(Math.floor(Math.random() * 99) + 1).padStart(2, '0');
    const workOrderNo = `KD-PL-${dateCode}-${seq}`;

    // 품목 데이터 구성
    let items = [];
    if (registrationMode === 'order') {
      if (selectedSplit && selectedOrder) {
        items = selectedOrder.items
          .filter(item => selectedSplit.itemIds.includes(item.id))
          .map(item => ({
            ...item,
            lotNo: null,
            materialLotNo: null,
          }));
      } else if (selectedOrder) {
        items = selectedOrder.items.map(item => ({
          ...item,
          lotNo: null,
          materialLotNo: null,
        }));
      }
    } else {
      // 수동 등록 모드: 입력된 품목 데이터 변환
      items = formData.manualItems
        .filter(item => item.itemName.trim())
        .map((item, idx) => ({
          id: Date.now() + idx,
          itemName: item.itemName,
          specification: item.specification,
          qty: parseInt(item.qty) || 1,
          unit: item.unit,
          lotNo: null,
          materialLotNo: null,
        }));
    }

    // 공정별 작업단계 설정
    const getStepStatus = (processType) => {
      const steps = {
        '스크린': ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'],
        '슬랫': ['코일절단', '중간검사', '미미작업', '포장'],
        '절곡': ['절단', '절곡', '중간검사', '포장'],
      };

      const stepStatus = {};
      (steps[processType] || steps['스크린']).forEach(step => {
        stepStatus[step] = { status: '대기' };
      });
      return stepStatus;
    };

    const newWorkOrder = {
      id: Date.now(),
      workOrderNo,
      orderNo: registrationMode === 'order' ? selectedOrder.orderNo : null,
      orderId: registrationMode === 'order' ? selectedOrder.id : null, // ★ 수주 ID 연결
      splitNo: selectedSplit?.splitNo || null,
      orderDate: new Date().toISOString().split('T')[0],
      processType: formData.processType,
      customerName: registrationMode === 'order' ? selectedOrder.customerName : formData.customerName,
      siteName: registrationMode === 'order' ? selectedOrder.siteName : formData.siteName,
      dueDate: formData.dueDate,
      shipRequestDate: registrationMode === 'order' ? (selectedOrder.shipRequestDate || selectedOrder.dueDate || formData.dueDate) : formData.dueDate, // ★ 출고예정일 추가
      status: '작업대기',
      workPriority: formData.priority, // ★ 숫자 우선순위 직접 저장 (1~9)
      priority: formData.priority <= 2 ? '긴급' : formData.priority <= 5 ? '일반' : '낮음', // ★ 호환성 위한 문자열 버전
      assignees: formData.assignees, // 다중 담당자 배열
      assignee: formData.assignees.join(', '), // 호환성을 위한 문자열 버전
      totalQty: items.reduce((sum, item) => sum + (item.qty || 0), 0),
      completedQty: 0,
      currentStep: null,
      stepStatus: getStepStatus(formData.processType),
      movedToShippingArea: false,
      movedToShippingAreaAt: null,
      items,
      issues: [],
      createdAt: new Date().toISOString().split('T')[0],
      createdBy: '현재 사용자',
      note: formData.note,
      registrationType: registrationMode, // 등록 유형 저장 (order/manual)
    };

    onSave?.(newWorkOrder);
    onBack();
  };

  // 등록 버튼 활성화 조건
  const isSubmitDisabled = registrationMode === 'order' ? !selectedOrder : false;

  return (
    <div className="space-y-6">
      {/* 헤더 - 타이틀/버튼 분리 */}
      <div className="space-y-3">
        <div className="flex items-center gap-3">
          <button onClick={onBack} className="p-2 hover:bg-gray-100 rounded-lg">
            <ArrowLeft className="w-5 h-5 text-gray-500" />
          </button>
          <Factory className="w-6 h-6 text-blue-500" />
          <h1 className="text-xl font-bold text-gray-900">작업지시 등록</h1>
        </div>
        <div className="flex items-center justify-end gap-2">
          <Button variant="outline" onClick={onBack}>취소</Button>
          <Button variant="primary" onClick={handleSubmit} disabled={isSubmitDisabled}>
            <Check className="w-4 h-4" /> 등록
          </Button>
        </div>
      </div>

      {/* 등록 방식 선택 섹션 */}
      <Card title="등록 방식">
        <div className="flex gap-6">
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="radio"
              name="registrationMode"
              checked={registrationMode === 'order'}
              onChange={() => handleModeChange('order')}
              className="w-4 h-4 text-purple-600 border-gray-300 focus:ring-purple-500"
            />
            <span className={`text-sm font-medium ${registrationMode === 'order' ? 'text-purple-700' : 'text-gray-700'}`}>
              수주 연동 등록
            </span>
            <span className="text-xs text-gray-500">(회계확인 완료된 수주에서 불러오기)</span>
          </label>
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="radio"
              name="registrationMode"
              checked={registrationMode === 'manual'}
              onChange={() => handleModeChange('manual')}
              className="w-4 h-4 text-purple-600 border-gray-300 focus:ring-purple-500"
            />
            <span className={`text-sm font-medium ${registrationMode === 'manual' ? 'text-purple-700' : 'text-gray-700'}`}>
              수동 등록
            </span>
            <span className="text-xs text-gray-500">(수주 없이 직접 입력)</span>
          </label>
        </div>
      </Card>

      {/* 수주 연동 모드: 수주 불러오기 영역 */}
      {registrationMode === 'order' && (
        <Card title="수주 정보">
          <div className={`p-4 rounded-lg border-2 ${selectedOrder ? 'bg-purple-50 border-purple-300' : 'bg-gray-50 border-dashed border-gray-300'}`}>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <ClipboardList className={`w-5 h-5 ${selectedOrder ? 'text-purple-600' : 'text-gray-400'}`} />
                {selectedOrder ? (
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="font-mono text-purple-600 font-bold">{selectedOrder.orderNo}</span>
                      <StatusBadge status={selectedOrder.status} />
                      <span className="text-sm text-gray-500">에서 불러옴</span>
                    </div>
                    <p className="text-sm text-gray-600 mt-0.5">
                      {selectedOrder.customerName} / {selectedOrder.siteName} / {selectedOrder.items?.length || 0}개 품목
                      {selectedSplit && <span className="ml-2 text-purple-600">분할: {selectedSplit.splitNo}</span>}
                    </p>
                  </div>
                ) : (
                  <div>
                    <p className="text-gray-700 font-medium">수주에서 불러오기</p>
                    <p className="text-sm text-gray-500">회계확인 완료된 수주를 선택하면 정보가 자동으로 채워집니다</p>
                  </div>
                )}
              </div>
              <div className="flex items-center gap-2">
                {selectedOrder && (
                  <Button variant="ghost" size="sm" onClick={handleClearOrder}>
                    <X className="w-4 h-4" /> 해제
                  </Button>
                )}
                <Button variant={selectedOrder ? "outline" : "primary"} size="sm" onClick={() => setShowOrderPanel(true)}>
                  <ClipboardList className="w-4 h-4" /> {selectedOrder ? '변경' : '수주 선택'}
                </Button>
              </div>
            </div>
          </div>
          {/* 분할 선택 (수주에 분할이 있을 경우) */}
          {selectedOrder && selectedOrder.splits?.length > 0 && (
            <div className="mt-4 pt-4 border-t border-gray-200">
              <p className="text-sm font-medium text-gray-700 mb-3">분할 선택</p>
              <div className="flex flex-wrap gap-4">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="radio"
                    name="splitSelection"
                    checked={!selectedSplit}
                    onChange={() => handleSplitSelect(null)}
                    className="w-4 h-4 text-purple-600 border-gray-300 focus:ring-purple-500"
                  />
                  <span className={`text-sm ${!selectedSplit ? 'font-medium text-purple-700' : 'text-gray-600'}`}>
                    전체 품목
                  </span>
                </label>
                {selectedOrder.splits.map(split => (
                  <label key={split.id} className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="splitSelection"
                      checked={selectedSplit?.id === split.id}
                      onChange={() => handleSplitSelect(split)}
                      className="w-4 h-4 text-purple-600 border-gray-300 focus:ring-purple-500"
                    />
                    <span className={`text-sm ${selectedSplit?.id === split.id ? 'font-medium text-purple-700' : 'text-gray-600'}`}>
                      {split.splitNo}
                    </span>
                  </label>
                ))}
              </div>
            </div>
          )}
        </Card>
      )}

      {/* 수동 등록 모드: 안내 메시지 */}
      {registrationMode === 'manual' && (
        <Card title="수동 등록 안내">
          <div className="flex items-center gap-3 p-3 bg-orange-50 rounded-lg">
            <AlertCircle className="w-5 h-5 text-orange-600" />
            <div>
              <p className="text-orange-800 font-medium">수동 등록 모드</p>
              <p className="text-sm text-orange-600">수주 없이 직접 작업지시를 생성합니다. 긴급 작업, 재작업, 샘플/시제품, 내부 작업 등에 사용됩니다.</p>
            </div>
          </div>
        </Card>
      )}

      {/* 기본 정보 */}
      <Card title="기본 정보">
        <div className="grid grid-cols-1 gap-4">
          <FormField label="발주처" required error={registrationMode === 'manual' && hasError('customerId')} errorMessage={getFieldError('customerId')}>
            {registrationMode === 'order' ? (
              selectedOrder ? (
                <input
                  type="text"
                  value={selectedOrder.customerName}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-700"
                  readOnly
                />
              ) : (
                <input
                  type="text"
                  value=""
                  placeholder="수주를 선택하면 자동 입력됩니다"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-400"
                  readOnly
                />
              )
            ) : (
              <select
                value={formData.customerId}
                onChange={(e) => {
                  const selectedCustomer = salesCustomers.find(c => c.id === parseInt(e.target.value));
                  handleChange('customerId', e.target.value);
                  handleChange('customerName', selectedCustomer?.customerName || '');
                  // 거래처 변경 시 현장 초기화
                  handleChange('siteId', '');
                  handleChange('siteName', '');
                  clearFieldError('customerId');
                }}
                onBlur={() => handleBlur('customerId')}
                className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 ${hasError('customerId') ? 'border-red-500 bg-red-50' : 'border-gray-200'}`}
              >
                <option value="">발주처를 선택하세요</option>
                {salesCustomers.map(customer => (
                  <option key={customer.id} value={customer.id}>
                    {customer.customerName} ({customer.customerCode})
                  </option>
                ))}
              </select>
            )}
          </FormField>
          <FormField label="현장명" required error={registrationMode === 'manual' && hasError('siteId')} errorMessage={getFieldError('siteId')}>
            {registrationMode === 'order' ? (
              selectedOrder ? (
                <input
                  type="text"
                  value={selectedOrder.siteName}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-700"
                  readOnly
                />
              ) : (
                <input
                  type="text"
                  value=""
                  placeholder="수주를 선택하면 자동 입력됩니다"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-400"
                  readOnly
                />
              )
            ) : (
              <select
                value={formData.siteId}
                onChange={(e) => {
                  const selectedSite = filteredSites.find(s => s.id === parseInt(e.target.value));
                  handleChange('siteId', e.target.value);
                  handleChange('siteName', selectedSite?.name || '');
                  clearFieldError('siteId');
                }}
                onBlur={() => handleBlur('siteId')}
                disabled={!formData.customerId}
                className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 ${!formData.customerId ? 'bg-gray-100 text-gray-400' : ''} ${hasError('siteId') ? 'border-red-500 bg-red-50' : 'border-gray-200'}`}
              >
                <option value="">{formData.customerId ? '현장을 선택하세요' : '발주처를 먼저 선택하세요'}</option>
                {filteredSites.map(site => (
                  <option key={site.id} value={site.id}>
                    {site.name} ({site.code})
                  </option>
                ))}
              </select>
            )}
          </FormField>
          {registrationMode === 'order' && (
            <>
              <FormField label="수주번호">
                {selectedOrder ? (
                  <input
                    type="text"
                    value={selectedOrder.orderNo}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-700 font-mono"
                    readOnly
                  />
                ) : (
                  <input
                    type="text"
                    value=""
                    placeholder="수주를 선택하면 자동 입력됩니다"
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-400"
                    readOnly
                  />
                )}
              </FormField>
              <FormField label="품목수">
                <input
                  type="text"
                  value={selectedOrder ? `${selectedOrder.items?.length || 0}개` : ''}
                  placeholder="수주를 선택하면 자동 입력됩니다"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-700"
                  readOnly
                />
              </FormField>
            </>
          )}
        </div>
      </Card>

      {/* 수동 등록 모드: 품목 입력 */}
      {registrationMode === 'manual' && (
        <Card title="품목 정보">
          <div className="space-y-3">
            {formData.manualItems.map((item, index) => (
              <div key={item.id} className="p-3 border border-gray-200 rounded-lg bg-gray-50">
                <div className="flex items-center justify-between mb-2">
                  <span className="text-sm font-medium text-gray-700">품목 {index + 1}</span>
                  {formData.manualItems.length > 1 && (
                    <button
                      onClick={() => removeManualItem(item.id)}
                      className="p-1 text-red-500 hover:bg-red-50 rounded"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  )}
                </div>
                <div className="grid grid-cols-1 gap-2">
                  <input
                    type="text"
                    value={item.itemName}
                    onChange={(e) => updateManualItem(item.id, 'itemName', e.target.value)}
                    placeholder="품목명"
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 text-sm"
                  />
                  <input
                    type="text"
                    value={item.specification}
                    onChange={(e) => updateManualItem(item.id, 'specification', e.target.value)}
                    placeholder="규격 (예: W1000 x H2000)"
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 text-sm"
                  />
                  <div className="flex gap-2">
                    <input
                      type="number"
                      value={item.qty}
                      onChange={(e) => updateManualItem(item.id, 'qty', e.target.value)}
                      placeholder="수량"
                      min="1"
                      className="flex-1 px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 text-sm"
                    />
                    <select
                      value={item.unit}
                      onChange={(e) => updateManualItem(item.id, 'unit', e.target.value)}
                      className="w-24 px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 text-sm"
                    >
                      <option value="EA">EA</option>
                      <option value="SET">SET</option>
                      <option value="M">M</option>
                      <option value="M2">M2</option>
                    </select>
                  </div>
                </div>
              </div>
            ))}
            <button
              onClick={addManualItem}
              className="w-full py-2 border-2 border-dashed border-gray-300 rounded-lg text-gray-500 hover:border-purple-300 hover:text-purple-600 transition-colors flex items-center justify-center gap-2"
            >
              <Plus className="w-4 h-4" /> 품목 추가
            </button>
          </div>
        </Card>
      )}

      {/* 작업지시 정보 */}
      <Card title="작업지시 정보">
        <div className="grid grid-cols-1 gap-4">
          <FormField label="공정구분" required>
            <select
              value={formData.processType}
              onChange={(e) => handleProcessTypeChange(e.target.value)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
            >
              {processTypes.map(type => (
                <option key={type} value={type}>{type}</option>
              ))}
            </select>
            {formData.processCode && (
              <p className="text-xs text-gray-500 mt-1">
                공정코드: {formData.processCode} | 작업일지: {formData.workSheetType || '-'}
              </p>
            )}
          </FormField>

          <FormField label="출고예정일" required error={registrationMode === 'manual' && hasError('dueDate')} errorMessage={getFieldError('dueDate')}>
            <input
              type="date"
              value={formData.dueDate}
              onChange={(e) => {
                handleChange('dueDate', e.target.value);
                clearFieldError('dueDate');
              }}
              onBlur={() => handleBlur('dueDate')}
              className={registrationMode === 'manual' ? getInputClassName(hasError('dueDate')) : "w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"}
            />
          </FormField>

          <FormField label="우선순위 (1=긴급, 9=낮음)">
            <select
              value={formData.priority}
              onChange={(e) => handleChange('priority', parseInt(e.target.value))}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
            >
              {priorities.map(p => (
                <option key={p} value={p}>{p} {p === 1 ? '(긴급)' : p === 5 ? '(일반)' : p === 9 ? '(낮음)' : ''}</option>
              ))}
            </select>
          </FormField>

          <FormField label="담당자 (다중선택 가능)">
            <div
              onClick={() => setShowAssigneePanel(true)}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg cursor-pointer hover:border-purple-300 transition-colors min-h-[42px] flex items-center gap-2 flex-wrap"
            >
              {formData.assignees.length === 0 ? (
                <span className="text-gray-400">담당자를 선택하세요 (팀/개인)</span>
              ) : (
                <>
                  {formData.assignees.map(a => (
                    <span key={a} className="inline-flex items-center gap-1 px-2 py-0.5 bg-purple-100 text-purple-700 text-sm rounded-full">
                      {a}
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleWorkerToggle(a);
                        }}
                        className="hover:text-purple-900"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </span>
                  ))}
                </>
              )}
            </div>
          </FormField>
        </div>
      </Card>

      {/* 비고 - 수주 선택 여부와 관계없이 항상 표시 */}
      <Card title="비고">
        <textarea
          value={formData.note}
          onChange={(e) => handleChange('note', e.target.value)}
          rows={3}
          className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
          placeholder="특이사항이나 메모를 입력하세요"
        />
      </Card>

      {/* 수주 선택 모달 */}
      {showOrderPanel && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between p-4 border-b">
              <h3 className="text-lg font-bold">수주 선택</h3>
              <button onClick={() => setShowOrderPanel(false)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="p-4 space-y-4 overflow-y-auto flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input type="text" value={orderSearch} onChange={(e) => setOrderSearch(e.target.value)} placeholder="수주번호, 거래처, 현장명 검색..." className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500" />
              </div>
              <p className="text-sm text-gray-500">생산지시 가능한 수주 {availableOrders.length}건 (회계확인 완료 상태)</p>
              <div className="divide-y max-h-96 overflow-y-auto border rounded-lg">
                {filteredOrders.length === 0 ? (
                  <div className="p-8 text-center text-gray-500"><p>생산지시 가능한 수주가 없습니다</p><p className="text-sm mt-1">회계확인이 완료된 수주만 표시됩니다</p></div>
                ) : (
                  filteredOrders.map((order) => (
                    <div key={order.id} onClick={() => handleOrderSelect(order)} className={`p-4 hover:bg-purple-50 cursor-pointer transition-colors ${selectedOrder?.id === order.id ? 'bg-purple-50 border-l-4 border-l-purple-500' : ''}`}>
                      <div className="flex items-center justify-between">
                        <div>
                          <div className="flex items-center gap-2 mb-1"><span className="font-mono text-purple-600 font-bold">{order.orderNo}</span><StatusBadge status={order.status} /></div>
                          <p className="text-sm text-gray-900">{order.customerName}</p>
                          <p className="text-sm text-gray-500">{order.siteName}</p>
                        </div>
                        <div className="text-right">
                          <p className="text-sm font-medium text-gray-700">납기: {order.dueDate}</p>
                          <p className="text-xs text-gray-500">{order.items?.length || 0}개 품목</p>
                          {order.splits?.length > 0 && <p className="text-xs text-purple-600 mt-1">분할 {order.splits.length}건</p>}
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 담당자 선택 모달 */}
      {showAssigneePanel && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl w-full max-w-md mx-4 max-h-[90vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between p-4 border-b">
              <h3 className="text-lg font-bold">담당자 선택</h3>
              <button onClick={() => setShowAssigneePanel(false)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="p-4 space-y-4 overflow-y-auto flex-1">
              <p className="text-sm text-gray-500">팀 전체 또는 개별 작업자를 선택할 수 있습니다</p>
              {formData.assignees.length > 0 && (
                <div className="p-3 bg-purple-50 rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-medium text-purple-700">선택된 담당자 ({formData.assignees.length}명)</span>
                    <button onClick={() => setFormData(prev => ({ ...prev, assignees: [] }))} className="text-xs text-purple-600 hover:text-purple-800">전체 해제</button>
                  </div>
                  <div className="flex flex-wrap gap-1">{formData.assignees.map(a => (<span key={a} className="px-2 py-0.5 bg-purple-100 text-purple-700 text-xs rounded-full">{a}</span>))}</div>
                </div>
              )}
              <div className="space-y-3">
                {teams.map(team => (
                  <div key={team.id} className="border rounded-lg overflow-hidden">
                    <div onClick={() => handleTeamSelect(team)} className={`p-3 cursor-pointer transition-colors flex items-center justify-between ${isTeamFullySelected(team) ? 'bg-purple-100 border-purple-300' : isTeamPartiallySelected(team) ? 'bg-purple-50' : 'bg-gray-50 hover:bg-gray-100'}`}>
                      <div className="flex items-center gap-2">
                        <div className={`w-5 h-5 rounded border-2 flex items-center justify-center ${isTeamFullySelected(team) ? 'bg-purple-500 border-purple-500' : isTeamPartiallySelected(team) ? 'bg-purple-200 border-purple-400' : 'border-gray-300'}`}>
                          {isTeamFullySelected(team) && <Check className="w-3 h-3 text-white" />}
                          {isTeamPartiallySelected(team) && <div className="w-2 h-2 bg-purple-500 rounded-sm" />}
                        </div>
                        <Users className="w-4 h-4 text-gray-500" />
                        <span className="font-medium text-gray-900">{team.name}</span>
                        <span className="text-xs text-gray-500">({team.members.length}명)</span>
                      </div>
                      <span className="text-xs text-purple-600">{isTeamFullySelected(team) ? '팀 전체 선택됨' : '팀 전체 선택'}</span>
                    </div>
                    <div className="divide-y border-t">
                      {team.members.map(member => (
                        <div key={member} onClick={() => handleWorkerToggle(member)} className={`p-2.5 pl-10 cursor-pointer transition-colors flex items-center gap-2 ${formData.assignees.includes(member) ? 'bg-purple-50' : 'hover:bg-gray-50'}`}>
                          <div className={`w-4 h-4 rounded border-2 flex items-center justify-center ${formData.assignees.includes(member) ? 'bg-purple-500 border-purple-500' : 'border-gray-300'}`}>
                            {formData.assignees.includes(member) && <Check className="w-2.5 h-2.5 text-white" />}
                          </div>
                          <User className="w-3.5 h-3.5 text-gray-400" />
                          <span className="text-sm text-gray-700">{member}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
              <div className="pt-4 border-t">
                <Button variant="primary" className="w-full" onClick={() => setShowAssigneePanel(false)}><Check className="w-4 h-4" /> 선택 완료 ({formData.assignees.length}명)</Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 작업지시 수정
const WorkOrderEdit = ({ workOrder, onNavigate, onBack, onSave }) => {
  // 기존 데이터가 배열이면 그대로, 문자열이면 파싱
  const parseAssignees = () => {
    if (Array.isArray(workOrder?.assignees)) return workOrder.assignees;
    if (workOrder?.assignee) return workOrder.assignee.split(', ').filter(Boolean);
    return [];
  };

  const [formData, setFormData] = useState({
    dueDate: workOrder?.dueDate || '',
    priority: workOrder?.priority || '일반',
    assignees: parseAssignees(),
    note: workOrder?.note || '',
  });
  const [showAssigneePanel, setShowAssigneePanel] = useState(false);

  // 유효성 검사 규칙
  const validationRules = {
    dueDate: { required: true, label: '납기일', message: '납기일을 선택해주세요.' },
  };
  const { errors, touched, hasError, getFieldError, validateForm, handleBlur, clearFieldError } = useFormValidation(formData, validationRules);

  const priorities = ['긴급', '일반', '낮음'];

  // 팀별 작업자 정의
  const teams = [
    { id: 'screen', name: '스크린팀', members: ['김스크린', '이스크린', '박스크린'] },
    { id: 'slat', name: '슬랫팀', members: ['김슬랫', '이슬랫', '박슬랫'] },
    { id: 'bending', name: '절곡팀', members: ['김절곡', '이절곡'] },
  ];

  // 팀 전체 선택
  const handleTeamSelect = (team) => {
    const currentAssignees = formData.assignees;
    const allSelected = team.members.every(m => currentAssignees.includes(m));

    if (allSelected) {
      setFormData(prev => ({
        ...prev,
        assignees: prev.assignees.filter(a => !team.members.includes(a))
      }));
    } else {
      const newAssignees = [...new Set([...currentAssignees, ...team.members])];
      setFormData(prev => ({ ...prev, assignees: newAssignees }));
    }
  };

  // 개별 작업자 토글
  const handleWorkerToggle = (worker) => {
    setFormData(prev => {
      const exists = prev.assignees.includes(worker);
      return {
        ...prev,
        assignees: exists
          ? prev.assignees.filter(a => a !== worker)
          : [...prev.assignees, worker]
      };
    });
  };

  const isTeamFullySelected = (team) => team.members.every(m => formData.assignees.includes(m));
  const isTeamPartiallySelected = (team) =>
    team.members.some(m => formData.assignees.includes(m)) && !isTeamFullySelected(team);

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleSubmit = () => {
    // 유효성 검사
    if (!validateForm()) {
      return;
    }
    onSave?.({
      ...workOrder,
      ...formData,
      assignee: formData.assignees.join(', '), // 호환성을 위한 문자열 버전
    });
    onBack();
  };

  if (!workOrder) return null;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button onClick={onBack} className="p-2 hover:bg-gray-100 rounded-lg">
            <ArrowLeft className="w-5 h-5 text-gray-500" />
          </button>
          <Factory className="w-6 h-6 text-purple-500" />
          <div>
            <h1 className="text-xl font-bold text-gray-900">작업지시 수정</h1>
            <p className="text-sm text-gray-500 font-mono">{workOrder.workOrderNo}</p>
          </div>
          <StatusBadge status={workOrder.status} />
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={onBack}>취소</Button>
          <Button variant="primary" onClick={handleSubmit}>
            <Check className="w-4 h-4" /> 저장
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6">
        {/* 기본 정보 (읽기 전용) */}
        <Card title="기본 정보">
          <div className="grid grid-cols-2 gap-4">
            <InfoRow label="작업지시번호" value={workOrder.workOrderNo} />
            <InfoRow label="로트번호" value={workOrder.orderNo} />
            <InfoRow label="분할번호" value={workOrder.splitNo || '전체'} />
            <InfoRow label="공정구분" value={workOrder.processType} />
            <InfoRow label="발주처" value={workOrder.customerName} />
            <InfoRow label="현장명" value={workOrder.siteName} />
            <InfoRow label="총수량" value={`${workOrder.totalQty}개`} />
            <InfoRow label="완료수량" value={`${workOrder.completedQty}개`} />
            <InfoRow label="현재공정" value={workOrder.currentStep || '-'} />
            <InfoRow label="등록일" value={workOrder.createdAt} />
          </div>
        </Card>

        {/* 수정 가능 정보 */}
        <Card title="작업지시 정보 수정">
          <div className="space-y-4">
            <FormField label="납기일" required error={hasError('dueDate')} errorMessage={getFieldError('dueDate')}>
              <input
                type="date"
                value={formData.dueDate}
                onChange={(e) => {
                  handleChange('dueDate', e.target.value);
                  clearFieldError('dueDate');
                }}
                onBlur={() => handleBlur('dueDate')}
                className={getInputClassName(hasError('dueDate'))}
              />
            </FormField>

            <FormField label="우선순위">
              <select
                value={formData.priority}
                onChange={(e) => handleChange('priority', e.target.value)}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
              >
                {priorities.map(p => (
                  <option key={p} value={p}>{p}</option>
                ))}
              </select>
            </FormField>

            <FormField label="담당자 (다중선택 가능)">
              <div
                onClick={() => setShowAssigneePanel(true)}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg cursor-pointer hover:border-purple-300 transition-colors min-h-[42px] flex items-center gap-2 flex-wrap"
              >
                {formData.assignees.length === 0 ? (
                  <span className="text-gray-400">담당자를 선택하세요 (팀/개인)</span>
                ) : (
                  <>
                    {formData.assignees.map(a => (
                      <span key={a} className="inline-flex items-center gap-1 px-2 py-0.5 bg-purple-100 text-purple-700 text-sm rounded-full">
                        {a}
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleWorkerToggle(a);
                          }}
                          className="hover:text-purple-900"
                        >
                          <X className="w-3 h-3" />
                        </button>
                      </span>
                    ))}
                  </>
                )}
              </div>
            </FormField>

            <FormField label="비고">
              <textarea
                value={formData.note}
                onChange={(e) => handleChange('note', e.target.value)}
                rows={3}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
              />
            </FormField>
          </div>
        </Card>

        {/* 작업 품목 */}
        <Card title="작업 품목">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목코드</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">층</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">부호</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">규격</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">수량</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">완제품LOT</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {workOrder.items?.map((item, idx) => (
                  <tr key={idx}>
                    <td className="px-4 py-3 text-sm font-mono text-gray-600">{item.productCode}</td>
                    <td className="px-4 py-3 text-sm text-gray-900">{item.productName}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{item.floor}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{item.location}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{item.spec}</td>
                    <td className="px-4 py-3 text-sm text-gray-900">{item.qty}</td>
                    <td className="px-4 py-3 text-sm font-mono text-blue-600">{item.lotNo || '-'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      </div>

      {/* 담당자 선택 모달 */}
      {showAssigneePanel && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl w-full max-w-md mx-4 max-h-[90vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between p-4 border-b">
              <h3 className="text-lg font-bold">담당자 선택</h3>
              <button onClick={() => setShowAssigneePanel(false)} className="p-1 hover:bg-gray-100 rounded"><X className="w-5 h-5" /></button>
            </div>
            <div className="p-4 space-y-4 overflow-y-auto flex-1">
              <p className="text-sm text-gray-500">팀 전체 또는 개별 작업자를 선택할 수 있습니다</p>
              {formData.assignees.length > 0 && (
                <div className="p-3 bg-purple-50 rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-medium text-purple-700">선택된 담당자 ({formData.assignees.length}명)</span>
                    <button onClick={() => setFormData(prev => ({ ...prev, assignees: [] }))} className="text-xs text-purple-600 hover:text-purple-800">전체 해제</button>
                  </div>
                  <div className="flex flex-wrap gap-1">{formData.assignees.map(a => (<span key={a} className="px-2 py-0.5 bg-purple-100 text-purple-700 text-xs rounded-full">{a}</span>))}</div>
                </div>
              )}
              <div className="space-y-3">
                {teams.map(team => (
                  <div key={team.id} className="border rounded-lg overflow-hidden">
                    <div onClick={() => handleTeamSelect(team)} className={`p-3 cursor-pointer transition-colors flex items-center justify-between ${isTeamFullySelected(team) ? 'bg-purple-100 border-purple-300' : isTeamPartiallySelected(team) ? 'bg-purple-50' : 'bg-gray-50 hover:bg-gray-100'}`}>
                      <div className="flex items-center gap-2">
                        <div className={`w-5 h-5 rounded border-2 flex items-center justify-center ${isTeamFullySelected(team) ? 'bg-purple-500 border-purple-500' : isTeamPartiallySelected(team) ? 'bg-purple-200 border-purple-400' : 'border-gray-300'}`}>
                          {isTeamFullySelected(team) && <Check className="w-3 h-3 text-white" />}
                          {isTeamPartiallySelected(team) && <div className="w-2 h-2 bg-purple-500 rounded-sm" />}
                        </div>
                        <Users className="w-4 h-4 text-gray-500" />
                        <span className="font-medium text-gray-900">{team.name}</span>
                        <span className="text-xs text-gray-500">({team.members.length}명)</span>
                      </div>
                      <span className="text-xs text-purple-600">{isTeamFullySelected(team) ? '팀 전체 선택됨' : '팀 전체 선택'}</span>
                    </div>
                    <div className="divide-y border-t">
                      {team.members.map(member => (
                        <div key={member} onClick={() => handleWorkerToggle(member)} className={`p-2.5 pl-10 cursor-pointer transition-colors flex items-center gap-2 ${formData.assignees.includes(member) ? 'bg-purple-50' : 'hover:bg-gray-50'}`}>
                          <div className={`w-4 h-4 rounded border-2 flex items-center justify-center ${formData.assignees.includes(member) ? 'bg-purple-500 border-purple-500' : 'border-gray-300'}`}>
                            {formData.assignees.includes(member) && <Check className="w-2.5 h-2.5 text-white" />}
                          </div>
                          <User className="w-3.5 h-3.5 text-gray-400" />
                          <span className="text-sm text-gray-700">{member}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
              <div className="pt-4 border-t">
                <Button variant="primary" className="w-full" onClick={() => setShowAssigneePanel(false)}><Check className="w-4 h-4" /> 선택 완료 ({formData.assignees.length}명)</Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 작업지시 상세
const WorkOrderDetail = ({
  workOrder,
  workResults,
  orders,
  inventory = [],
  materialLots = [],
  onNavigate,
  onBack,
  onUpdate,
  onUpdateOrder,
  onUseMaterial,
  // 기능정의서 관련 props
  setActiveModal,
  showFeatureDescription,
  featureBadges = {},
  selectedBadge,
  setSelectedBadge,
  updateFeatureBadge,
  setEditingBadge
}) => {
  // ★ workOrder가 없으면 에러 화면 표시
  if (!workOrder) {
    return (
      <div className="space-y-6">
        <PageHeader
          icon={ClipboardList}
          title="작업지시 상세"
          actions={<Button variant="secondary" onClick={onBack}><ArrowLeft className="w-4 h-4" /> 목록으로</Button>}
        />
        <div className="bg-white rounded-xl p-8 shadow-sm border text-center">
          <AlertCircle className="w-16 h-16 text-red-400 mx-auto mb-4" />
          <h3 className="text-lg font-bold text-gray-900 mb-2">작업지시를 찾을 수 없습니다</h3>
          <p className="text-gray-500 mb-4">선택된 작업지시 정보가 없습니다. 목록에서 다시 선택해 주세요.</p>
          <Button variant="primary" onClick={onBack}>
            <ArrowLeft className="w-4 h-4" /> 목록으로 돌아가기
          </Button>
        </div>
      </div>
    );
  }

  const [showMaterialCheck, setShowMaterialCheck] = useState(false);
  const [showProductionSheet, setShowProductionSheet] = useState(false);
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [showStepModal, setShowStepModal] = useState(false);
  const [showMaterialInputModal, setShowMaterialInputModal] = useState(false);
  const [showWorkLogEditor, setShowWorkLogEditor] = useState(false);
  const [showWorkLogSheet, setShowWorkLogSheet] = useState(false);
  const [showCombinedSheet, setShowCombinedSheet] = useState(false);  // 작업지시서+작업일지 함께 출력
  const [showWorkLogDataPreview, setShowWorkLogDataPreview] = useState(false);  // 작업일지 양식보기 (데이터 연동)
  const [showApprovalModal, setShowApprovalModal] = useState(false);  // 결재 상신/승인 모달
  const [workLogData, setWorkLogData] = useState(null);
  const [workLogApproval, setWorkLogApproval] = useState({
    status: 'draft',  // draft, step1_pending, step1_approved, step2_pending, step2_approved, approved, rejected
    // 1단계: 생산지시자 (작성)
    step1: {
      status: 'draft',
      submittedAt: null,
      submittedBy: null,
    },
    // 2단계: 생산담당자 (확인)
    step2: {
      status: 'pending',
      approvedAt: null,
      approvedBy: null,
    },
    // 3단계: 품질팀장 (최종결재)
    step3: {
      status: 'pending',
      approvedAt: null,
      approvedBy: null,
    },
    rejectedAt: null,
    rejectedBy: null,
    rejectReason: null,
    rejectedStep: null,
  });

  // 투입자재 선택 모달
  const [showMaterialSelectModal, setShowMaterialSelectModal] = useState(false);
  const [selectedMaterials, setSelectedMaterials] = useState([]);

  // 중간검사성적서 모달
  const [showInspectionCertModal, setShowInspectionCertModal] = useState(false);
  const [inspectionCertData, setInspectionCertData] = useState({
    lotNo: '',
    inspectionDate: new Date().toISOString().slice(0, 10),
    inspector: '',
    items: [],
    result: 'pending',
    inputMaterials: [],
  });
  const [currentStep, setCurrentStep] = useState(null);
  // ★ 다중 작업자 배정을 위한 상태
  const parseInitialAssignees = () => {
    if (Array.isArray(workOrder?.assignees)) return workOrder.assignees;
    if (workOrder?.assignee) return workOrder.assignee.split(', ').filter(Boolean);
    return [];
  };
  const [selectedAssignees, setSelectedAssignees] = useState(parseInitialAssignees);

  // 해당 작업지시의 수주 정보 찾기
  const relatedOrder = orders?.find(o => o.orderNo === workOrder.orderNo);

  // ★ 작업팀 정의 - 공정관리(sampleProcesses)의 assignedWorkers와 연동
  const workerTeams = sampleProcesses
    .filter(p => p.isActive && p.assignedWorkers?.length > 0)
    .map(p => ({
      name: `${p.processName}팀`,
      processCode: p.processCode,
      department: p.department,
      members: p.assignedWorkers,
    }));

  // 현재 공정에 배정된 작업자 목록 (해당 공정 우선 표시)
  const currentProcessWorkers = (() => {
    const matchedProcess = sampleProcesses.find(p =>
      p.processName === workOrder.processType ||
      p.processCode === workOrder.processCode
    );
    return matchedProcess?.assignedWorkers || [];
  })();

  // 전체 작업자 목록 (모든 공정에서 수집)
  const allWorkers = [...new Set(sampleProcesses.flatMap(p => p.assignedWorkers || []))];
  const workers = allWorkers.length > 0 ? allWorkers : ['김생산', '이생산', '박생산', '최생산', '정생산'];
  const inspectors = ['이검사', '최품질', '김검사'];

  // ★ 팀 선택/해제 토글
  const handleTeamToggle = (team) => {
    const allSelected = team.members.every(m => selectedAssignees.includes(m));
    if (allSelected) {
      setSelectedAssignees(prev => prev.filter(a => !team.members.includes(a)));
    } else {
      const newAssignees = [...new Set([...selectedAssignees, ...team.members])];
      setSelectedAssignees(newAssignees);
    }
  };

  // ★ 개별 작업자 선택/해제 토글
  const handleWorkerToggle = (worker) => {
    setSelectedAssignees(prev => {
      const exists = prev.includes(worker);
      return exists ? prev.filter(a => a !== worker) : [...prev, worker];
    });
  };

  // ★ 팀 전체 선택 여부 확인
  const isTeamFullySelected = (team) => team.members.every(m => selectedAssignees.includes(m));
  const isTeamPartiallySelected = (team) =>
    team.members.some(m => selectedAssignees.includes(m)) && !isTeamFullySelected(team);

  // 해당 작업지시의 실적 필터링
  const relatedResults = workResults.filter(r => r.workOrderNo === workOrder.workOrderNo);

  // 공정 단계 정보 - sampleProcesses(공정관리)에서 동적으로 가져옴
  const getProcessSteps = () => {
    // 공정관리에서 해당 공정 찾기 (processType 또는 processName으로 매칭)
    const matchedProcess = sampleProcesses.find(p =>
      p.processName === workOrder.processType ||
      p.processCode === workOrder.processCode
    );

    // 공정관리에 workSteps가 있으면 사용, 없으면 기본값
    if (matchedProcess?.workSteps?.length > 0) {
      return matchedProcess.workSteps;
    }

    // 기본값 (공정관리에 데이터 없을 경우)
    const defaultSteps = {
      '스크린': ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'],
      '슬랫': ['코일절단', '중간검사', '미미작업', '포장'],
      '절곡': ['절단', '절곡', '중간검사', '포장'],
      '재고(포밍)': ['포밍', '검사', '포장'],
    };
    return defaultSteps[workOrder.processType] || ['준비', '작업', '검사', '완료'];
  };

  // 공정관리에서 현재 공정 정보 가져오기
  const getCurrentProcessInfo = () => {
    return sampleProcesses.find(p =>
      p.processName === workOrder.processType ||
      p.processCode === workOrder.processCode
    );
  };

  const processInfo = getCurrentProcessInfo();

  // 단계 상태 아이콘
  const getStepIcon = (status) => {
    if (status === '완료') return <CheckCircle className="w-5 h-5 text-green-500" />;
    if (status === '진행중') return <Clock className="w-5 h-5 text-blue-500 animate-pulse" />;
    return <div className="w-5 h-5 rounded-full border-2 border-gray-300" />;
  };

  // ★ 다중 작업자 배정 핸들러
  const handleAssign = () => {
    if (selectedAssignees.length === 0) {
      alert('작업자를 1명 이상 선택해주세요.');
      return;
    }
    onUpdate?.({
      ...workOrder,
      assignees: selectedAssignees, // 배열로 저장
      assignee: selectedAssignees.join(', '), // 호환성을 위한 문자열 버전
    });
    setShowAssignModal(false);
    alert(`✅ 작업자 ${selectedAssignees.length}명이 배정되었습니다.\n\n${selectedAssignees.join(', ')}`);
  };

  // 작업 시작 핸들러
  const handleStartWork = () => {
    if (!workOrder.assignee && (!workOrder.assignees || workOrder.assignees.length === 0)) {
      alert('먼저 작업자를 배정해주세요.');
      setShowAssignModal(true);
      return;
    }

    const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
    const firstStep = getProcessSteps()[0];

    onUpdate?.({
      ...workOrder,
      status: '작업중',
      startedAt: now,
      currentStep: firstStep,
      stepStatus: {
        ...workOrder.stepStatus,
        [firstStep]: {
          status: '진행중',
          worker: workOrder.assignee,
          startedAt: now,
        },
      },
    });

    // 수주 상태는 생산지시완료 유지 (작업지시 실행 상태와 별도 관리)
    // onUpdateOrder?.(workOrder.orderNo, { status: '생산중' });

    alert(`✅ 작업이 시작되었습니다!\n\n작업자: ${workOrder.assignee}\n현재 공정: ${firstStep}`);
  };

  // 공정 시작 핸들러
  const handleStepStart = (step) => {
    const now = new Date().toISOString().replace('T', ' ').slice(0, 16);

    onUpdate?.({
      ...workOrder,
      currentStep: step,
      stepStatus: {
        ...workOrder.stepStatus,
        [step]: {
          status: '진행중',
          worker: workOrder.assignee,
          startedAt: now,
        },
      },
    });
  };

  // 공정 완료 핸들러
  const handleStepComplete = (step, additionalData = {}) => {
    const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
    const steps = getProcessSteps();
    const currentIndex = steps.indexOf(step);
    const isLastStep = currentIndex === steps.length - 1;
    const nextStep = isLastStep ? null : steps[currentIndex + 1];

    const updatedStepStatus = {
      ...workOrder.stepStatus,
      [step]: {
        ...workOrder.stepStatus[step],
        status: '완료',
        completedAt: now,
        ...additionalData,
      },
    };

    // 다음 공정이 있으면 진행중으로 설정
    if (nextStep) {
      updatedStepStatus[nextStep] = {
        status: '진행중',
        worker: workOrder.assignee,
        startedAt: now,
      };
    }

    // 완료 수량 계산 (마지막 공정 완료 시)
    const newCompletedQty = isLastStep ? workOrder.totalQty : workOrder.completedQty;
    const newStatus = isLastStep ? '작업완료' : workOrder.status;

    onUpdate?.({
      ...workOrder,
      status: newStatus,
      currentStep: nextStep,
      stepStatus: updatedStepStatus,
      completedQty: newCompletedQty,
      completedAt: isLastStep ? now : workOrder.completedAt,
    });

    // 마지막 공정 완료 시 (수주 상태는 생산지시완료 유지, 출하완료는 출하 처리 시 변경)
    if (isLastStep) {
      // onUpdateOrder?.(workOrder.orderNo, { status: '생산완료' });
      alert(`🎉 모든 공정이 완료되었습니다!\n\n작업지시: ${workOrder.workOrderNo}\n완료수량: ${workOrder.totalQty}건`);
    } else {
      alert(`✅ ${step} 공정이 완료되었습니다.\n\n다음 공정: ${nextStep}`);
    }

    setShowStepModal(false);
  };

  // 중간검사 완료 핸들러
  const handleInspectionComplete = (result, inspector, rejectReason = '') => {
    const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
    const inspectionLot = `KD-SC-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-01`;

    if (result === '합격') {
      // 합격 시 다음 공정으로 진행
      handleStepComplete('중간검사', {
        result: '합격',
        inspector: inspector,
        approvedBy: '품질팀장 최품질',
        inspectionLot: inspectionLot,
      });
    } else {
      // 불합격 시 재작업 처리
      const steps = getProcessSteps();
      const inspectionIndex = steps.indexOf('중간검사');
      const previousStep = inspectionIndex > 0 ? steps[inspectionIndex - 1] : steps[0];

      // 중간검사를 불합격으로 기록하고 이전 공정으로 되돌림
      const updatedStepStatus = {
        ...workOrder.stepStatus,
        '중간검사': {
          status: '불합격',
          result: '불합격',
          inspector: inspector,
          inspectionLot: inspectionLot,
          rejectReason: rejectReason,
          rejectedAt: now,
        },
        [previousStep]: {
          status: '진행중',  // 이전 공정을 다시 진행중으로
          worker: workOrder.assignee,
          startedAt: now,
          reworkCount: (workOrder.stepStatus?.[previousStep]?.reworkCount || 0) + 1,
          reworkReason: `중간검사 불합격: ${rejectReason}`,
        },
      };

      // 불량 이슈 추가
      const newIssue = {
        id: Date.now(),
        type: '품질불량',
        step: '중간검사',
        description: `중간검사 불합격 - ${rejectReason}`,
        reportedBy: inspector,
        reportedAt: now,
        status: '처리중',
      };

      onUpdate?.({
        ...workOrder,
        currentStep: previousStep,
        stepStatus: updatedStepStatus,
        issues: [...(workOrder.issues || []), newIssue],
        hasQualityIssue: true,
        qualityIssueNote: `중간검사 불합격 - ${rejectReason}`,
      });

      setShowStepModal(false);
      alert(`⚠️ 중간검사 불합격\n\n사유: ${rejectReason}\n\n${previousStep} 공정으로 돌아가서 재작업을 진행합니다.`);
    }
  };

  // 포장 완료 핸들러
  const handlePackingComplete = (labelInfo) => {
    handleStepComplete('포장', {
      labelInfo: labelInfo,
    });
  };

  // 출고구역 이동 핸들러
  const handleMoveToShipping = () => {
    const now = new Date().toISOString().replace('T', ' ').slice(0, 16);

    onUpdate?.({
      ...workOrder,
      movedToShippingArea: true,
      movedToShippingAreaAt: now,
    });

    // 수주 상태는 생산지시완료 유지 (출하완료는 출하 처리 시 변경)
    // onUpdateOrder?.(workOrder.orderNo, { status: '생산완료' });

    alert(`✅ 출고구역으로 이동 완료!\n\n이동시각: ${now}\n\n[출하관리]에서 출하 진행이 가능합니다.`);
  };

  // ============ 개별 품목 작업 처리 핸들러 ============

  // 히스토리 추가 헬퍼 함수
  const addItemHistory = (item, action, note = '') => {
    const timestamp = new Date().toISOString().replace('T', ' ').slice(0, 19);
    return {
      timestamp,
      action,
      itemId: item.id,
      itemName: item.productName,
      floor: item.floor,
      location: item.location,
      worker: workOrder.assignee || '작업자',
      note,
    };
  };

  // 품목 작업 시작
  const handleItemStart = (itemId) => {
    const now = new Date().toISOString().replace('T', ' ').slice(0, 19);
    const item = workOrder.items.find(i => i.id === itemId);
    if (!item) return;

    const updatedItems = workOrder.items.map(i =>
      i.id === itemId
        ? { ...i, itemStatus: '진행중', worker: workOrder.assignee, startedAt: now }
        : i
    );

    const historyEntry = addItemHistory(item, '시작');

    onUpdate?.({
      ...workOrder,
      items: updatedItems,
      itemHistory: [...(workOrder.itemHistory || []), historyEntry],
    });
  };

  // 품목 작업 완료
  const handleItemComplete = (itemId) => {
    const now = new Date().toISOString().replace('T', ' ').slice(0, 19);
    const item = workOrder.items.find(i => i.id === itemId);
    if (!item) return;

    // 제품 LOT 번호 생성
    const dateCode = new Date().toISOString().slice(2, 10).replace(/-/g, '');
    const seq = String(Math.floor(Math.random() * 99) + 1).padStart(2, '0');
    const lotNo = `KD-FG-${dateCode}-${seq}`;

    const updatedItems = workOrder.items.map(i =>
      i.id === itemId
        ? { ...i, itemStatus: '완료', completedAt: now, lotNo }
        : i
    );

    const historyEntry = addItemHistory(item, '완료');

    // 모든 품목이 완료되었는지 확인
    const allCompleted = updatedItems.every(i => i.itemStatus === '완료');
    const completedCount = updatedItems.filter(i => i.itemStatus === '완료').length;

    onUpdate?.({
      ...workOrder,
      items: updatedItems,
      itemHistory: [...(workOrder.itemHistory || []), historyEntry],
      completedQty: completedCount,
    });

    if (allCompleted) {
      alert(`🎉 모든 품목 작업이 완료되었습니다!\n\n완료: ${completedCount}건`);
    } else {
      alert(`✅ "${item.productName}" 작업 완료!\n\n완료: ${completedCount}/${workOrder.items.length}건`);
    }
  };

  // 품목 작업 중단 (다음날 이어서)
  const handleItemPause = (itemId) => {
    const now = new Date().toISOString().replace('T', ' ').slice(0, 19);
    const item = workOrder.items.find(i => i.id === itemId);
    if (!item) return;

    const reason = prompt('작업 중단 사유를 입력하세요 (퇴근, 자재부족 등):', '퇴근');
    if (reason === null) return; // 취소

    const updatedItems = workOrder.items.map(i =>
      i.id === itemId
        ? { ...i, itemStatus: '중단', pausedAt: now, pauseReason: reason }
        : i
    );

    const historyEntry = addItemHistory(item, '중단', reason);

    onUpdate?.({
      ...workOrder,
      items: updatedItems,
      itemHistory: [...(workOrder.itemHistory || []), historyEntry],
    });

    alert(`⏸️ "${item.productName}" 작업이 중단되었습니다.\n\n사유: ${reason}\n\n다음 작업일에 이어서 진행할 수 있습니다.`);
  };

  // 품목 작업 재개
  const handleItemResume = (itemId) => {
    const now = new Date().toISOString().replace('T', ' ').slice(0, 19);
    const item = workOrder.items.find(i => i.id === itemId);
    if (!item) return;

    const updatedItems = workOrder.items.map(i =>
      i.id === itemId
        ? { ...i, itemStatus: '진행중', resumedAt: now, worker: workOrder.assignee }
        : i
    );

    const historyEntry = addItemHistory(item, '재개', `이전 중단 사유: ${item.pauseReason || '-'}`);

    onUpdate?.({
      ...workOrder,
      items: updatedItems,
      itemHistory: [...(workOrder.itemHistory || []), historyEntry],
    });

    alert(`▶️ "${item.productName}" 작업을 재개합니다!`);
  };

  // 샘플 BOM 데이터
  const bomData = [
    { id: 1, materialCode: 'SCR-MAT-001', materialName: '스크린 원단', unit: '㎡', required: 26, stock: 150, status: 'ok' },
    { id: 2, materialCode: 'SCR-MAT-002', materialName: '앤드락', unit: 'EA', required: 40, stock: 200, status: 'ok' },
    { id: 3, materialCode: 'SCR-MAT-003', materialName: '하단바', unit: 'EA', required: 10, stock: 15, status: 'ok' },
    { id: 4, materialCode: 'SCR-MAT-004', materialName: '미싱실', unit: 'M', required: 500, stock: 2000, status: 'ok' },
    { id: 5, materialCode: 'SCR-MAT-005', materialName: '포장박스', unit: 'EA', required: 10, stock: 50, status: 'ok' },
  ];

  // 다음 처리할 공정 찾기
  const getNextActionStep = () => {
    const steps = getProcessSteps();
    for (const step of steps) {
      const status = workOrder.stepStatus?.[step]?.status;
      if (status === '진행중') return { step, action: 'complete' };
      if (status === '대기' || !status) return { step, action: 'start' };
    }
    return null;
  };

  return (
    <div className="space-y-6">
      {/* 상단 헤더 - 타이틀 위, 버튼 아래 */}
      <div className="space-y-3">
        {/* 타이틀 영역 */}
        <h1 className="text-xl font-bold text-gray-900">
          작업지시 상세
        </h1>
        {/* 버튼 영역 - 우측 정렬 */}
        <div className="flex items-center justify-end">
          <div className="flex items-center gap-2">
            <button
              onClick={() => setShowWorkLogDataPreview(true)}
              className="px-3 py-1.5 text-sm border border-gray-300 rounded hover:bg-gray-50 transition-colors"
            >
              작업일지
            </button>
            <Button variant="outline" size="sm" onClick={onBack}>
              목록
            </Button>
          </div>
        </div>
      </div>

      {/* 기본정보 섹션 - 컴팩트 레이아웃 */}
      <Card title="기본 정보">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-x-6 gap-y-3 text-sm">
          <InfoRow label="작업지시번호" value={<span className="font-mono">{workOrder.workOrderNo}</span>} />
          <InfoRow label="로트번호" value={<span className="font-mono text-blue-600">{workOrder.orderNo}</span>} />
          <InfoRow label="공정구분" value={workOrder.processType} />
          <InfoRow label="작업상태" value={<StatusBadge status={workOrder.status} />} />
          <InfoRow label="발주처" value={workOrder.customerName} />
          <InfoRow label="현장명" value={workOrder.siteName} />
          <InfoRow label="납기일" value={workOrder.dueDate} />
          <InfoRow label="작업자" value={
            workOrder.assignee ? (
              <span className="text-blue-600">{workOrder.assignee}</span>
            ) : (
              <button onClick={() => setShowAssignModal(true)} className="text-orange-600 hover:underline">+ 배정</button>
            )
          } />
        </div>
      </Card>

      {/* 공정 진행 - 컴팩트 인라인 */}
      <Card title={`공정 진행 (${getProcessSteps().length}단계)`}>
        <div className="flex flex-wrap gap-2">
          {getProcessSteps().map((step, idx) => {
            const stepStatus = workOrder.stepStatus?.[step] || { status: '대기' };
            const canStart = idx === 0
              ? workOrder.status === '작업중' && stepStatus.status === '대기'
              : workOrder.stepStatus?.[getProcessSteps()[idx - 1]]?.status === '완료' && stepStatus.status === '대기';
            const canComplete = stepStatus.status === '진행중';

            return (
              <div key={step} className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm ${stepStatus.status === '완료' ? 'bg-green-100 text-green-700' :
                  stepStatus.status === '진행중' ? 'bg-blue-100 text-blue-700' :
                    'bg-gray-100 text-gray-500'
                }`}>
                <span className="w-5 h-5 rounded-full bg-white/50 flex items-center justify-center text-xs font-bold">{idx + 1}</span>
                <span>{step}</span>
                {canStart && (
                  <button onClick={() => handleStepStart(step)} className="ml-1 px-2 py-0.5 bg-white rounded text-xs hover:bg-gray-50">시작</button>
                )}
                {canComplete && (
                  <button onClick={() => { setCurrentStep(step); setShowStepModal(true); }} className="ml-1 px-2 py-0.5 bg-blue-500 text-white rounded text-xs hover:bg-blue-600">완료</button>
                )}
              </div>
            );
          })}
        </div>
      </Card>

      {/* 작업품목 섹션 - 컴팩트 테이블 */}
      <Card title={`작업 품목 (${workOrder.items.length}건)`}>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-2 py-2 text-left text-xs font-medium text-gray-500">No</th>
                <th className="px-2 py-2 text-left text-xs font-medium text-gray-500">상태</th>
                <th className="px-2 py-2 text-left text-xs font-medium text-gray-500">품목명</th>
                <th className="px-2 py-2 text-left text-xs font-medium text-gray-500">층/부호</th>
                <th className="px-2 py-2 text-left text-xs font-medium text-gray-500">규격</th>
                <th className="px-2 py-2 text-right text-xs font-medium text-gray-500">수량</th>
                <th className="px-2 py-2 text-center text-xs font-medium text-gray-500">작업</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {workOrder.items.map((item, idx) => {
                const status = item.itemStatus || '대기';
                const statusColors = {
                  '대기': 'bg-gray-100 text-gray-600',
                  '진행중': 'bg-blue-100 text-blue-700',
                  '완료': 'bg-green-100 text-green-700',
                  '중단': 'bg-red-100 text-red-700',
                };
                return (
                  <tr key={item.id} className={status === '진행중' ? 'bg-blue-50' : ''}>
                    <td className="px-2 py-2 text-gray-500">{idx + 1}</td>
                    <td className="px-2 py-2">
                      <span className={`px-1.5 py-0.5 text-xs rounded ${statusColors[status]}`}>{status}</span>
                    </td>
                    <td className="px-2 py-2">{item.productName}</td>
                    <td className="px-2 py-2 text-gray-600">{item.floor}/{item.location}</td>
                    <td className="px-2 py-2 text-gray-600">{item.spec}</td>
                    <td className="px-2 py-2 text-right font-medium">{item.qty}</td>
                    <td className="px-2 py-2 text-center">
                      {workOrder.status === '작업중' && status === '대기' && (
                        <button onClick={() => handleItemStart(item.id)} className="px-2 py-1 text-xs bg-gray-100 rounded hover:bg-gray-200">시작</button>
                      )}
                      {workOrder.status === '작업중' && status === '진행중' && (
                        <button onClick={() => handleItemComplete(item.id)} className="px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600">완료</button>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>

      {/* 절곡 공정일 때 전개도 섹션 표시 - 품목별 통합 */}
      {workOrder.processType === '절곡' && (
        <Card title="전개도 상세정보">
          <div className="space-y-3">
            {[
              { itemCode: 'SD30', itemName: '엘바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 4, weight: 0.9, dimensions: '75', note: '', svgType: 'rect' },
              { itemCode: 'SD31', itemName: '하장바', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 2, weight: 1.158, dimensions: '67→126→165→178→193', note: '', svgType: 'hajang' },
              { itemCode: 'SD32', itemName: '짜부가스켓', material: 'E.G.I 0.8T', totalWidth: 500, length: 3000, qty: 4, weight: 0.576, dimensions: '48', note: '80*4,50*8', svgType: 'thin' },
              { itemCode: 'SD33', itemName: '50평철', material: 'E.G.I 1.2T', totalWidth: 500, length: 3000, qty: 2, weight: 0.3, dimensions: '50', note: '', svgType: 'flat' },
              { itemCode: 'SD34', itemName: '전면판', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 1.764, dimensions: '120→499→553→588', note: '500*380', svgType: 'front' },
              { itemCode: 'SD35', itemName: '린텔박스', material: 'E.G.I 1.6T', totalWidth: 500, length: 3000, qty: 1, weight: 0.504, dimensions: '84→138→168', note: 'S/BOX', svgType: 'lintel' },
              { itemCode: 'SD36', itemName: '밑면 점검구', material: 'E.G.I 1.6T', totalWidth: 500, length: 2438, qty: 2, weight: 0.98, dimensions: '90→240→310', note: '500*380', svgType: 'bottom' },
              { itemCode: 'SD37', itemName: '후면코너부', material: 'E.G.I 1.2T', totalWidth: 500, length: 1219, qty: 4, weight: 0.45, dimensions: '35→85→120', note: '', svgType: 'corner' },
            ].map((part, idx) => (
              <div key={idx} className="border rounded-lg overflow-hidden">
                {/* 품목 헤더 */}
                <div className="bg-gray-100 px-4 py-2 flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <span className="font-mono text-sm font-bold text-blue-600">{part.itemCode}</span>
                    <span className="font-medium">{part.itemName}</span>
                    <span className="text-sm text-gray-500">{part.material}</span>
                  </div>
                  <span className="px-2 py-0.5 bg-blue-100 text-blue-700 rounded text-xs font-medium">
                    수량: {part.qty}
                  </span>
                </div>
                {/* 품목 내용 - 정보 + 도면 */}
                <div className="p-4 flex gap-6">
                  {/* 좌측: 상세 정보 */}
                  <div className="flex-1 grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
                    <div>
                      <p className="text-xs text-gray-500">전개폭</p>
                      <p className="font-medium">{part.totalWidth}mm</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500">길이</p>
                      <p className="font-medium">{part.length}mm</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500">중량</p>
                      <p className="font-medium">{part.weight}kg</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500">비고</p>
                      <p className="font-medium text-gray-600">{part.note || '-'}</p>
                    </div>
                    <div className="col-span-2 md:col-span-4">
                      <p className="text-xs text-gray-500">전개치수</p>
                      <p className="font-mono text-blue-600 font-medium">{part.dimensions}</p>
                    </div>
                  </div>
                  {/* 우측: 전개도 도면 */}
                  <div className="w-40 flex-shrink-0">
                    <div className="bg-gray-50 border rounded p-2 h-24 flex items-center justify-center">
                      <svg viewBox="0 0 100 60" className="w-full h-full">
                        {part.svgType === 'rect' && (
                          <>
                            <rect x="10" y="20" width="80" height="20" fill="none" stroke="#333" strokeWidth="1" />
                            <line x1="10" y1="25" x2="90" y2="25" stroke="#666" strokeWidth="0.5" strokeDasharray="2,2" />
                          </>
                        )}
                        {part.svgType === 'hajang' && (
                          <path d="M10,40 L20,40 L20,20 L40,20 L40,30 L60,30 L60,20 L80,20 L80,40 L90,40" fill="none" stroke="#333" strokeWidth="1" />
                        )}
                        {part.svgType === 'thin' && (
                          <rect x="10" y="25" width="80" height="10" fill="none" stroke="#333" strokeWidth="1" />
                        )}
                        {part.svgType === 'flat' && (
                          <rect x="10" y="22" width="80" height="16" fill="none" stroke="#333" strokeWidth="1" />
                        )}
                        {part.svgType === 'front' && (
                          <path d="M10,45 L10,15 L25,15 L25,25 L75,25 L75,15 L90,15 L90,45 Z" fill="none" stroke="#333" strokeWidth="1" />
                        )}
                        {part.svgType === 'lintel' && (
                          <path d="M15,40 L15,20 L35,20 L35,30 L65,30 L65,20 L85,20 L85,40" fill="none" stroke="#333" strokeWidth="1" />
                        )}
                        {part.svgType === 'bottom' && (
                          <path d="M10,40 L10,20 L30,20 L30,15 L70,15 L70,20 L90,20 L90,40 Z" fill="none" stroke="#333" strokeWidth="1" />
                        )}
                        {part.svgType === 'corner' && (
                          <path d="M20,40 L20,25 L50,25 L50,20 L80,20 L80,40" fill="none" stroke="#333" strokeWidth="1" />
                        )}
                        <text x="50" y="55" textAnchor="middle" fontSize="5" fill="#666">{part.dimensions}</text>
                      </svg>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* 이슈 - 컴팩트 (이슈 있을때만 표시) */}
      {workOrder.issues?.length > 0 && (
        <Card title={`이슈 (${workOrder.issues.length}건)`}>
          <div className="space-y-2">
            {workOrder.issues.map(issue => (
              <div key={issue.id} className="flex items-center gap-3 p-2 bg-gray-50 rounded text-sm">
                <span className={`px-2 py-0.5 rounded text-xs ${issue.status === '처리완료' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                  }`}>{issue.status}</span>
                <span className="text-gray-600">{issue.issueType}</span>
                <span className="flex-1 truncate">{issue.description}</span>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* 이하 작업일지/BOM 섹션은 컴팩트 버튼으로 대체됨 - 약 500줄 제거됨 */}
      {false && (<div>
        {relatedResults.length > 0 ? (
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">작업일</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">작업자</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">자재LOT</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">수주LOT</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">생산수량</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">양품</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">불량</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">이슈</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {relatedResults.map(result => (
                <tr key={result.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3 text-sm">{result.workDate}</td>
                  <td className="px-4 py-3 text-sm">{result.worker}</td>
                  <td className="px-4 py-3 text-sm font-mono text-purple-600">{result.materialLotNo || '-'}</td>
                  <td className="px-4 py-3 text-sm font-mono text-blue-600">{result.lotNo}</td>
                  <td className="px-4 py-3 text-sm text-right">{result.productionQty || result.completedQty}</td>
                  <td className="px-4 py-3 text-sm text-right font-medium text-green-600">{result.goodQty || result.completedQty}</td>
                  <td className="px-4 py-3 text-sm text-right text-red-500">{result.defectQty || 0}</td>
                  <td className="px-4 py-3 text-center">
                    {result.hasIssue ? <span className="text-red-500">⚠️</span> : <span className="text-green-500">✓</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="text-center py-8 text-gray-500">
            <BarChart3 className="w-12 h-12 mx-auto mb-3 text-gray-300" />
            <p>작업 시작 시 자동으로 기록됩니다.</p>
          </div>
        )}

        {/* 작업일지 상태 - 공정별 요약 */}
        {workLogData ? (
          <div className="space-y-6">
            {/* 기본정보 요약 (공통) */}
            <Card title="기본정보">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                <div>
                  <p className="text-gray-500">작업일자</p>
                  <p className="font-medium">{workLogData.workDate || '-'}</p>
                </div>
                <div>
                  <p className="text-gray-500">생산담당자</p>
                  <p className="font-medium">{workLogData.productionManager || '-'}</p>
                </div>
                <div>
                  <p className="text-gray-500">제품 LOT NO</p>
                  <p className="font-mono font-medium text-blue-600">{workLogData.productLotNo || '-'}</p>
                </div>
                <div>
                  <p className="text-gray-500">
                    {workOrder.processType === '스크린' ? '원단유형' :
                      workOrder.processType === '슬랫' ? '코일유형' : '마감유형'}
                  </p>
                  <p className="font-medium">
                    {workOrder.processType === '스크린' ? workLogData.fabric?.type :
                      workOrder.processType === '슬랫' ? workLogData.coil?.type :
                        workLogData.finishType || '-'}
                  </p>
                </div>
              </div>
            </Card>

            {/* 스크린 공정 요약 */}
            {workOrder.processType === '스크린' && (
              <div className="grid grid-cols-1 gap-4">
                <Card title="작업 내역">
                  <div className="space-y-2 text-sm">
                    {workLogData.workItems?.filter(item => item.qty).map(item => (
                      <div key={item.id} className="flex justify-between py-1 border-b">
                        <span className="text-gray-600">{item.step}</span>
                        <span className="font-medium">{item.qty} {item.unit}</span>
                      </div>
                    ))}
                  </div>
                </Card>
                <Card title="생산 실적">
                  <div className="grid grid-cols-3 gap-4 text-center">
                    <div className="p-3 bg-blue-50 rounded-lg">
                      <p className="text-xs text-blue-600">생산</p>
                      <p className="text-xl font-bold text-blue-700">{workLogData.productionResult?.totalProduced || 0}</p>
                    </div>
                    <div className="p-3 bg-green-50 rounded-lg">
                      <p className="text-xs text-green-600">양품</p>
                      <p className="text-xl font-bold text-green-700">{workLogData.productionResult?.goodQty || 0}</p>
                    </div>
                    <div className="p-3 bg-red-50 rounded-lg">
                      <p className="text-xs text-red-600">불량</p>
                      <p className="text-xl font-bold text-red-700">{workLogData.productionResult?.defectQty || 0}</p>
                    </div>
                  </div>
                </Card>
              </div>
            )}

            {/* 슬랫 공정 요약 */}
            {workOrder.processType === '슬랫' && (
              <div className="grid grid-cols-1 gap-4">
                <Card title="절단 내역">
                  <div className="space-y-2 text-sm">
                    {workLogData.cuttingDetails?.filter(item => item.qty).map(item => (
                      <div key={item.id} className="flex justify-between py-1 border-b">
                        <span className="text-gray-600">{item.length}</span>
                        <span className="font-medium">{item.qty} EA</span>
                      </div>
                    ))}
                  </div>
                </Card>
                <Card title="생산 실적">
                  <div className="grid grid-cols-2 gap-4 text-center">
                    <div className="p-3 bg-purple-50 rounded-lg">
                      <p className="text-xs text-purple-600">양품</p>
                      <p className="text-xl font-bold text-purple-700">{workLogData.productionResult?.goodQty || 0}</p>
                    </div>
                    <div className="p-3 bg-yellow-50 rounded-lg">
                      <p className="text-xs text-yellow-600">총 중량</p>
                      <p className="text-xl font-bold text-yellow-700">{workLogData.productionResult?.totalWeight || 0} kg</p>
                    </div>
                  </div>
                </Card>
              </div>
            )}

            {/* 절곡 공정 요약 */}
            {workOrder.processType === '절곡' && (
              <>
                <div className="grid grid-cols-1 gap-4">
                  <Card title="1. 벽면형 (120·70)">
                    <div className="space-y-2 text-sm">
                      {workLogData.guideRail?.filter(item => item.qty).map(item => (
                        <div key={item.id} className="flex justify-between py-1 border-b">
                          <span className="text-gray-600">{item.name} ({item.spec})</span>
                          <span className="font-medium">{item.qty}개</span>
                        </div>
                      ))}
                      {!workLogData.guideRail?.some(item => item.qty) && (
                        <p className="text-gray-400">입력된 수량 없음</p>
                      )}
                    </div>
                  </Card>
                  <Card title="2. 하단마감재">
                    <div className="space-y-2 text-sm">
                      {workLogData.bottomFinish?.map(item => (
                        <div key={item.id} className="py-1 border-b">
                          <span className="text-gray-600">{item.name}</span>
                          <div className="flex gap-4 mt-1">
                            {item.rows?.map((row, idx) => (
                              row.qty && <span key={idx} className="text-xs">{row.spec}: <strong>{row.qty}</strong></span>
                            ))}
                          </div>
                        </div>
                      ))}
                    </div>
                  </Card>
                </div>
                <Card title="생산량 합계">
                  <div className="grid grid-cols-2 gap-6">
                    <div className="p-4 bg-gray-50 rounded-lg text-center">
                      <p className="text-sm text-gray-500">SUS</p>
                      <p className="text-3xl font-bold">{workLogData.totalProduction?.sus || 0} <span className="text-lg font-normal text-gray-500">kg</span></p>
                    </div>
                    <div className="p-4 bg-green-50 rounded-lg text-center">
                      <p className="text-sm text-gray-500">EGI</p>
                      <p className="text-3xl font-bold text-green-700">{workLogData.totalProduction?.egi || 0} <span className="text-lg font-normal text-gray-500">kg</span></p>
                    </div>
                  </div>
                </Card>
              </>
            )}

            {/* 비고 (공통) */}
            {workLogData.remarks && (
              <Card title="비고">
                <p className="text-sm whitespace-pre-wrap">{workLogData.remarks}</p>
              </Card>
            )}
          </div>
        ) : (
          <Card>
            <div className="text-center py-12 text-gray-500">
              <Clipboard className="w-16 h-16 mx-auto mb-4 text-gray-300" />
              <p className="text-lg font-medium mb-2">작업일지가 아직 작성되지 않았습니다</p>
              <p className="text-sm mb-6">
                {workOrder.processType} 공정에 필요한 작업 내역을 기록하세요.
              </p>
              <Button variant="primary" onClick={() => setShowWorkLogEditor(true)}>
                <Plus className="w-4 h-4" /> 작업일지 작성
              </Button>
            </div>
          </Card>
        )}

        {/* 안내 (공정별) */}
        <div className={`p-4 rounded-lg text-sm ${workOrder.processType === '스크린' ? 'bg-blue-50' :
            workOrder.processType === '슬랫' ? 'bg-purple-50' :
              'bg-orange-50'
          }`}>
          <h4 className={`font-medium mb-2 ${workOrder.processType === '스크린' ? 'text-blue-800' :
              workOrder.processType === '슬랫' ? 'text-purple-800' :
                'text-orange-800'
            }`}>📋 작업일지 작성 안내</h4>
          <ul className={`space-y-1 ${workOrder.processType === '스크린' ? 'text-blue-700' :
              workOrder.processType === '슬랫' ? 'text-purple-700' :
                'text-orange-700'
            }`}>
            {workOrder.processType === '스크린' && (
              <>
                <li>• 원단 유형, 색상, 폭 정보를 입력합니다.</li>
                <li>• 원단절단, 미싱, 앤드락작업 등 각 공정별 작업 수량을 입력합니다.</li>
                <li>• 품목별 원단 LOT와 제품 LOT를 기록하여 추적성을 확보합니다.</li>
              </>
            )}
            {workOrder.processType === '슬랫' && (
              <>
                <li>• 코일 유형, 색상, 두께 정보를 입력합니다.</li>
                <li>• 길이별 절단 수량과 미미작업 수량을 입력합니다.</li>
                <li>• 생산 완료 후 총 중량(kg)을 입력합니다.</li>
              </>
            )}
            {workOrder.processType === '절곡' && (
              <>
                <li>• 벽면형, 하단마감재, 케이스, 연기차단재 각 섹션의 작업량을 입력합니다.</li>
                <li>• 각 부품별 입고 및 생산 LOT NO를 기록하여 추적성을 확보합니다.</li>
                <li>• 작업 완료 후 생산량 합계(SUS, EGI)를 입력합니다.</li>
              </>
            )}
            <li>• 작성된 작업일지는 인쇄하여 현장 기록으로 활용할 수 있습니다.</li>
          </ul>
        </div>

        {/* BOM/자재 섹션 */}
        <div className="space-y-6">
          {/* 공정별 자재 투입 안내 */}
          <div className={`rounded-lg p-4 border-2 ${workOrder.processType === '절곡' ? 'bg-orange-50 border-orange-200' :
              workOrder.processType === '스크린' ? 'bg-blue-50 border-blue-200' : 'bg-purple-50 border-purple-200'
            }`}>
            <div className="flex items-start gap-3">
              <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${workOrder.processType === '절곡' ? 'bg-orange-100' :
                  workOrder.processType === '스크린' ? 'bg-blue-100' : 'bg-purple-100'
                }`}>
                <Calculator className={`w-5 h-5 ${workOrder.processType === '절곡' ? 'text-orange-600' :
                    workOrder.processType === '스크린' ? 'text-blue-600' : 'text-purple-600'
                  }`} />
              </div>
              <div className="flex-1">
                <h4 className={`font-medium ${workOrder.processType === '절곡' ? 'text-orange-800' :
                    workOrder.processType === '스크린' ? 'text-blue-800' : 'text-purple-800'
                  }`}>
                  {workOrder.processType} 공정 자재 투입 기준
                </h4>
                {workOrder.processType === '절곡' && (
                  <div className="mt-2 space-y-1 text-sm text-orange-700">
                    <p><strong>단위:</strong> kg → 장 환산</p>
                    <p><strong>방식:</strong> 자재 LOT 선택 후 투입 수량(장) 지정</p>
                    <p><strong>계산:</strong> 총 중량(kg) ÷ 장당 중량 = 투입 장수</p>
                    <div className="mt-2 p-2 bg-white rounded text-xs">
                      예) 100kg 코일, 장당 0.5kg → 200장 투입 가능
                    </div>
                  </div>
                )}
                {workOrder.processType === '스크린' && (
                  <div className="mt-2 space-y-1 text-sm text-blue-700">
                    <p><strong>단위:</strong> W(폭) × H(높이)</p>
                    <p><strong>방식:</strong> 수주 W값 × 자재LOT H값 조합</p>
                    <p><strong>계산:</strong> 수주 폭(W) 그대로, 높이(H)는 자재LOT에서 선택</p>
                    <div className="mt-2 p-2 bg-white rounded text-xs">
                      예) 수주 W=2400 × 자재LOT H=1500 → 2400×1500 원단 투입
                    </div>
                  </div>
                )}
                {workOrder.processType === '슬랫' && (
                  <div className="mt-2 space-y-1 text-sm text-purple-700">
                    <p><strong>단위:</strong> 자동산출 (높이 기반)</p>
                    <p><strong>방식:</strong> 수주 높이에 따른 절단 매수 자동 계산</p>
                    <p><strong>계산:</strong> 코일 길이 ÷ 제품 높이 = 절단 매수</p>
                    <div className="mt-2 p-2 bg-white rounded text-xs">
                      예) 코일 10M, 제품높이 500mm → 20매 절단
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* 자재 재고 현황 요약 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-blue-50 rounded-lg p-4">
              <div className="flex items-center gap-3">
                <Box className="w-8 h-8 text-blue-500" />
                <div>
                  <p className="text-sm text-blue-600">필요 자재</p>
                  <p className="text-xl font-bold text-blue-700">{bomData.length}종</p>
                </div>
              </div>
            </div>
            <div className="bg-green-50 rounded-lg p-4">
              <div className="flex items-center gap-3">
                <CheckCircle className="w-8 h-8 text-green-500" />
                <div>
                  <p className="text-sm text-green-600">재고 충분</p>
                  <p className="text-xl font-bold text-green-700">{bomData.filter(b => b.stock >= b.required).length}종</p>
                </div>
              </div>
            </div>
            <div className="bg-red-50 rounded-lg p-4">
              <div className="flex items-center gap-3">
                <AlertCircle className="w-8 h-8 text-red-500" />
                <div>
                  <p className="text-sm text-red-600">재고 부족</p>
                  <p className="text-xl font-bold text-red-700">{bomData.filter(b => b.stock < b.required).length}종</p>
                </div>
              </div>
            </div>
          </div>

          <Card title="필요 자재 목록 (BOM) - LOT 연결">
            <div className="flex justify-between items-center mb-4">
              <p className="text-sm text-gray-500">작업에 필요한 자재 목록입니다. 입고 LOT와 생산 LOT를 연결할 수 있습니다.</p>
              <div className="flex gap-2">
                {workOrder.status === '작업중' && (
                  <>
                    <Button variant="outline" onClick={() => {
                      const productionLot = `PROD-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-${String(Math.floor(Math.random() * 100)).padStart(2, '0')}`;
                      alert(`✅ 로트번호 일괄적용 완료\n\n생산 LOT: ${productionLot}\n모든 자재에 동일한 생산 LOT가 적용됩니다.`);
                    }}>
                      로트번호 일괄적용
                    </Button>
                    <Button variant="primary" onClick={() => {
                      setShowMaterialInputModal(true);
                      setActiveModal?.('material-input-modal');
                    }}>
                      <Plus className="w-4 h-4" /> 자재 투입
                    </Button>
                  </>
                )}
              </div>
            </div>
            <table className="w-full">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">자재코드</th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">자재명</th>
                  <th className="px-3 py-3 text-right text-xs font-medium text-gray-500">필요량</th>
                  <th className="px-3 py-3 text-right text-xs font-medium text-gray-500">현재고</th>
                  <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">상태</th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">입고LOT</th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">생산LOT</th>
                  <th className="px-3 py-3 text-center text-xs font-medium text-gray-500">투입</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {bomData.map((item, idx) => {
                  // 샘플 입고LOT와 생산LOT 생성
                  const sampleInLot = item.inputLot || `IN-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-${String(idx + 1).padStart(2, '0')}`;
                  const sampleProdLot = item.productionLot || `PROD-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-${String(Math.floor(Math.random() * 10) + 1).padStart(2, '0')}`;

                  return (
                    <tr key={item.id} className={item.stock < item.required ? 'bg-red-50' : ''}>
                      <td className="px-3 py-3 text-sm font-mono text-gray-600">{item.materialCode}</td>
                      <td className="px-3 py-3 text-sm text-gray-900">{item.materialName}</td>
                      <td className="px-3 py-3 text-sm text-right">{item.required} {item.unit}</td>
                      <td className="px-3 py-3 text-sm text-right font-medium">
                        <span className={item.stock < item.required ? 'text-red-600' : 'text-gray-900'}>
                          {item.stock} {item.unit}
                        </span>
                      </td>
                      <td className="px-3 py-3 text-center">
                        {item.stock >= item.required ? (
                          <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-green-100 text-green-700">
                            <CheckCircle className="w-3 h-3 mr-1" /> 충분
                          </span>
                        ) : (
                          <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-red-100 text-red-700">
                            <AlertCircle className="w-3 h-3 mr-1" /> 부족
                          </span>
                        )}
                      </td>
                      {/* ★ 입고 LOT 선택 */}
                      <td className="px-3 py-3">
                        {item.stock >= item.required ? (
                          <select className="w-full px-2 py-1 text-xs border rounded bg-white text-blue-600 font-mono">
                            <option value="">{sampleInLot}</option>
                            <option value="IN-241215-01">IN-241215-01</option>
                            <option value="IN-241214-02">IN-241214-02</option>
                          </select>
                        ) : (
                          <span className="text-xs text-gray-400">-</span>
                        )}
                      </td>
                      {/* ★ 생산 LOT 표시/입력 */}
                      <td className="px-3 py-3">
                        {item.stock >= item.required ? (
                          <input
                            type="text"
                            className="w-full px-2 py-1 text-xs border rounded font-mono text-purple-600"
                            placeholder="생산LOT"
                            defaultValue={item.productionLot || ''}
                          />
                        ) : (
                          <span className="text-xs text-gray-400">-</span>
                        )}
                      </td>
                      <td className="px-3 py-3 text-center">
                        {workOrder.status === '작업중' && item.stock >= item.required && !item.inputLot && (
                          <Button size="sm" variant="outline" onClick={() => {
                            alert(`✅ 자재 투입 완료\n\n자재: ${item.materialName}\n입고LOT: ${sampleInLot}\n생산LOT: ${sampleProdLot}`);
                          }}>
                            투입
                          </Button>
                        )}
                        {item.inputLot && (
                          <CheckCircle className="w-5 h-5 text-green-500 mx-auto" />
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            {/* LOT 연결 안내 */}
            <div className="mt-4 p-3 bg-blue-50 rounded-lg border border-blue-200">
              <p className="text-sm text-blue-800">
                <strong>LOT 추적 안내:</strong> 입고LOT는 입고 시 부여된 LOT번호이며, 생산LOT는 이 작업지시에서 생산되는 제품의 LOT번호입니다.
                투입 시 두 LOT가 연결되어 제품 추적이 가능합니다.
              </p>
            </div>
          </Card>

          <Card title="자재 투입 이력 (LOT 추적)">
            {workOrder.materialInputs?.length > 0 ? (
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">투입일시</th>
                    <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">자재명</th>
                    <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">입고LOT</th>
                    <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">생산LOT</th>
                    <th className="px-3 py-3 text-right text-xs font-medium text-gray-500">투입량</th>
                    <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">작업자</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  <tr>
                    <td className="px-3 py-3 text-sm">2024-12-04 09:00</td>
                    <td className="px-3 py-3 text-sm">스크린 원단 (W2400)</td>
                    <td className="px-3 py-3 text-sm font-mono text-blue-600">IN-241204-01</td>
                    <td className="px-3 py-3 text-sm font-mono text-purple-600">PROD-241204-01</td>
                    <td className="px-3 py-3 text-sm text-right">50 M</td>
                    <td className="px-3 py-3 text-sm">김생산</td>
                  </tr>
                </tbody>
              </table>
            ) : (
              <div className="text-center py-8 text-gray-500">
                <Box className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                <p>투입된 자재가 없습니다.</p>
                <p className="text-sm mt-1">작업 시작 후 자재 투입 시 입고LOT-생산LOT가 연결되어 기록됩니다.</p>
              </div>
            )}
          </Card>
        </div>
      </div>
      )}
      {/* 작업일지/BOM 섹션 끝 - false && 로 비활성화됨 */}

      {/* 재고 확인 모달 */}
      {showMaterialCheck && (
        <MaterialCheckModal
          workOrder={workOrder}
          onClose={() => setShowMaterialCheck(false)}
        />
      )}

      {/* 투입자재 추가 모달 */}
      {showMaterialInputModal && (
        <MaterialInputModal
          workOrder={workOrder}
          inventory={inventory}
          materialLots={materialLots}
          showFeatureDescription={showFeatureDescription}
          featureBadges={featureBadges}
          selectedBadge={selectedBadge}
          setSelectedBadge={setSelectedBadge}
          updateFeatureBadge={updateFeatureBadge}
          setEditingBadge={setEditingBadge}
          onClose={() => {
            setShowMaterialInputModal(false);
            setActiveModal?.(null);
          }}
          onSubmit={(materialCode, qty, lotNo, inputBy, note) => {
            // 재고 감소 처리
            onUseMaterial?.(materialCode, qty, {
              workOrderNo: workOrder.workOrderNo,
              lotNo,
              inputBy,
              note,
            });

            // 작업지시에 투입 이력 추가
            const material = inventory.find(m => m.materialCode === materialCode);
            const newInput = {
              id: Date.now(),
              materialCode,
              materialName: material?.materialName || '',
              lotNo,
              qty,
              unit: material?.unit || '',
              inputBy,
              inputAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
              note,
            };

            onUpdate?.({
              ...workOrder,
              materialInputs: [...(workOrder.materialInputs || []), newInput],
            });

            setShowMaterialInputModal(false);
            setActiveModal?.(null);
            alert(`✅ 자재 투입이 등록되었습니다.\n\n자재: ${material?.materialName}\n투입량: ${qty} ${material?.unit}\nLOT: ${lotNo}`);
          }}
        />
      )}

      {/* ★ 다중 작업자 배정 모달 */}
      {showAssignModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl w-full max-w-lg overflow-hidden max-h-[90vh] flex flex-col">
            <div className="flex items-center justify-between p-4 border-b">
              <div className="flex items-center gap-2">
                <Users className="w-5 h-5 text-blue-600" />
                <h2 className="text-lg font-bold">작업자 배정 (다중 선택)</h2>
              </div>
              <button onClick={() => setShowAssignModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>

            <div className="flex-1 overflow-y-auto p-4 space-y-4">
              {/* 작업지시 정보 */}
              <div className="p-3 bg-gray-50 rounded-lg">
                <div className="flex justify-between items-center">
                  <div>
                    <p className="text-xs text-gray-500">작업지시번호</p>
                    <p className="font-mono font-medium">{workOrder.workOrderNo}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-xs text-gray-500">공정유형</p>
                    <p className="font-medium">{workOrder.processType}</p>
                  </div>
                </div>
              </div>

              {/* 선택된 작업자 표시 */}
              {selectedAssignees.length > 0 && (
                <div className="p-3 bg-purple-50 rounded-lg border border-purple-200">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-medium text-purple-700">선택된 작업자 ({selectedAssignees.length}명)</span>
                    <button onClick={() => setSelectedAssignees([])} className="text-xs text-purple-600 hover:text-purple-800">전체 해제</button>
                  </div>
                  <div className="flex flex-wrap gap-1">
                    {selectedAssignees.map(a => (
                      <span key={a} className="inline-flex items-center gap-1 px-2 py-0.5 bg-purple-100 text-purple-700 text-xs rounded-full">
                        {a}
                        <button onClick={() => handleWorkerToggle(a)} className="hover:text-purple-900">✕</button>
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* 팀별 작업자 선택 */}
              <div className="space-y-2">
                <p className="text-sm font-medium text-gray-700">팀별 작업자 선택</p>
                {workerTeams.map(team => (
                  <div key={team.name} className="border rounded-lg overflow-hidden">
                    {/* 팀 헤더 */}
                    <div
                      onClick={() => handleTeamToggle(team)}
                      className={`p-3 flex items-center justify-between cursor-pointer transition-colors
                        ${isTeamFullySelected(team) ? 'bg-purple-100' : isTeamPartiallySelected(team) ? 'bg-purple-50' : 'bg-gray-50 hover:bg-gray-100'}`}
                    >
                      <div className="flex items-center gap-2">
                        <div className={`w-4 h-4 rounded border-2 flex items-center justify-center
                          ${isTeamFullySelected(team) ? 'bg-purple-500 border-purple-500' : isTeamPartiallySelected(team) ? 'bg-purple-200 border-purple-400' : 'border-gray-300'}`}>
                          {isTeamFullySelected(team) && <Check className="w-2.5 h-2.5 text-white" />}
                          {isTeamPartiallySelected(team) && <div className="w-1.5 h-1.5 bg-purple-500 rounded-sm" />}
                        </div>
                        <span className="font-medium">{team.name}</span>
                        <span className="text-xs text-gray-500">({team.members.length}명)</span>
                      </div>
                      <span className="text-xs text-gray-500">전체 선택</span>
                    </div>
                    {/* 팀원 목록 */}
                    <div className="divide-y">
                      {team.members.map(member => (
                        <div
                          key={member}
                          onClick={() => handleWorkerToggle(member)}
                          className={`p-2.5 pl-10 cursor-pointer transition-colors flex items-center gap-2
                            ${selectedAssignees.includes(member) ? 'bg-purple-50' : 'hover:bg-gray-50'}`}
                        >
                          <div className={`w-4 h-4 rounded border-2 flex items-center justify-center
                            ${selectedAssignees.includes(member) ? 'bg-purple-500 border-purple-500' : 'border-gray-300'}`}>
                            {selectedAssignees.includes(member) && <Check className="w-2.5 h-2.5 text-white" />}
                          </div>
                          <span className="text-sm">{member}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>

              <div className="text-sm text-gray-500 p-2 bg-gray-50 rounded">
                * 다중 작업자를 배정할 수 있습니다. 팀 전체 선택도 가능합니다.
              </div>
            </div>

            <div className="flex gap-2 p-4 border-t bg-gray-50">
              <Button variant="outline" className="flex-1" onClick={() => setShowAssignModal(false)}>
                취소
              </Button>
              <Button variant="primary" className="flex-1" onClick={handleAssign} disabled={selectedAssignees.length === 0}>
                <Users className="w-4 h-4" /> 배정하기 ({selectedAssignees.length}명)
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 공정 완료 모달 */}
      {showStepModal && currentStep && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl w-full max-w-lg overflow-hidden">
            <div className="flex items-center justify-between p-4 border-b">
              <div className="flex items-center gap-2">
                <CheckCircle className="w-5 h-5 text-green-600" />
                <h2 className="text-lg font-bold">{currentStep} 공정 완료</h2>
              </div>
              <button onClick={() => setShowStepModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>

            <div className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-lg text-sm">
                <div>
                  <p className="text-gray-500">작업지시번호</p>
                  <p className="font-mono font-medium">{workOrder.workOrderNo}</p>
                </div>
                <div>
                  <p className="text-gray-500">현재 공정</p>
                  <p className="font-medium text-blue-600">{currentStep}</p>
                </div>
                <div>
                  <p className="text-gray-500">작업자</p>
                  <p className="font-medium">{workOrder.assignee}</p>
                </div>
                <div>
                  <p className="text-gray-500">시작시간</p>
                  <p className="font-medium">{workOrder.stepStatus?.[currentStep]?.startedAt || '-'}</p>
                </div>
              </div>

              {/* 중간검사 공정일 때 */}
              {currentStep === '중간검사' && (
                <div className="space-y-4">
                  <FormField label="검사자" required>
                    <Select
                      options={inspectors.map(i => ({ value: i, label: i }))}
                      value=""
                      onChange={() => { }}
                      placeholder="검사자 선택"
                    />
                  </FormField>
                  <div className="flex gap-2">
                    <Button
                      variant="success"
                      className="flex-1"
                      onClick={() => handleInspectionComplete('합격', '이검사')}
                    >
                      <CheckCircle className="w-4 h-4" /> 합격
                    </Button>
                    <Button
                      variant="danger"
                      className="flex-1"
                      onClick={() => handleInspectionComplete('불합격', '이검사')}
                    >
                      <X className="w-4 h-4" /> 불합격
                    </Button>
                  </div>
                </div>
              )}

              {/* 포장 공정일 때 */}
              {currentStep === '포장' && (
                <div className="space-y-4">
                  <FormField label="라벨 정보" required>
                    <TextInput
                      placeholder="예: 1층 A-01,A-02 / 1차분"
                      value=""
                      onChange={() => { }}
                    />
                  </FormField>
                  <Button
                    variant="primary"
                    className="w-full"
                    onClick={() => handlePackingComplete('1층 A-01,A-02 / 1차분')}
                  >
                    <Package className="w-4 h-4" /> 포장 완료
                  </Button>
                </div>
              )}

              {/* 일반 공정일 때 */}
              {currentStep !== '중간검사' && currentStep !== '포장' && (
                <Button
                  variant="primary"
                  className="w-full"
                  onClick={() => handleStepComplete(currentStep)}
                >
                  <CheckCircle className="w-4 h-4" /> {currentStep} 공정 완료
                </Button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 작업지시서 출력 모달 */}
      {showProductionSheet && (
        <ProductionOrderSheet
          workOrder={workOrder}
          order={relatedOrder}
          title="작업지시서"
          onClose={() => setShowProductionSheet(false)}
        />
      )}

      {/* 작업일지 에디터 모달 (공정별) */}
      {showWorkLogEditor && workOrder.processType === '스크린' && (
        <ScreenWorkLogEditor
          workOrder={workOrder}
          order={relatedOrder}
          workLog={workLogData}
          onClose={() => setShowWorkLogEditor(false)}
          onSave={(data) => {
            setWorkLogData(data);
            setShowWorkLogEditor(false);
          }}
        />
      )}
      {showWorkLogEditor && workOrder.processType === '슬랫' && (
        <SlatWorkLogEditor
          workOrder={workOrder}
          order={relatedOrder}
          workLog={workLogData}
          onClose={() => setShowWorkLogEditor(false)}
          onSave={(data) => {
            setWorkLogData(data);
            setShowWorkLogEditor(false);
          }}
        />
      )}
      {showWorkLogEditor && workOrder.processType === '절곡' && (
        <BendingWorkLogEditor
          workOrder={workOrder}
          order={relatedOrder}
          workLog={workLogData}
          onClose={() => setShowWorkLogEditor(false)}
          onSave={(data) => {
            setWorkLogData(data);
            setShowWorkLogEditor(false);
          }}
        />
      )}

      {/* 작업일지 출력 모달 - 공정별 전용 템플릿 포함 */}
      {showWorkLogSheet && (
        <WorkLogTemplateModal
          workOrder={workOrder}
          order={relatedOrder}
          workLog={workLogData}
          workResults={relatedResults}
          onClose={() => setShowWorkLogSheet(false)}
        />
      )}

      {/* 작업지시서 + 작업일지 함께 출력 모달 */}
      {showCombinedSheet && workLogData && (
        <CombinedWorkOrderSheet
          workOrder={workOrder}
          order={relatedOrder}
          workLog={workLogData}
          approvalStatus={workLogApproval}
          onClose={() => setShowCombinedSheet(false)}
        />
      )}

      {/* 3단계 결재 프로세스 모달 */}
      {showApprovalModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b">
              <h3 className="text-lg font-bold">작업일지 결재 (3단계)</h3>
              <p className="text-sm text-gray-500 mt-1">작업지시: {workOrder?.workOrderNo}</p>
            </div>
            <div className="p-6 space-y-6">
              {/* 결재 상태 요약 */}
              <div className="p-4 bg-gray-50 rounded-lg">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-gray-600">결재 상태</span>
                  <span className={`px-3 py-1 rounded-full text-sm font-medium ${workLogApproval.status === 'draft' ? 'bg-gray-100 text-gray-700' :
                      workLogApproval.status === 'step2_pending' ? 'bg-yellow-100 text-yellow-700' :
                        workLogApproval.status === 'step3_pending' ? 'bg-purple-100 text-purple-700' :
                          workLogApproval.status === 'approved' ? 'bg-green-100 text-green-700' :
                            'bg-red-100 text-red-700'
                    }`}>
                    {workLogApproval.status === 'draft' ? '작성중' :
                      workLogApproval.status === 'step2_pending' ? '2단계 결재중' :
                        workLogApproval.status === 'step3_pending' ? '최종 결재중' :
                          workLogApproval.status === 'approved' ? '최종승인완료' : '반려'}
                  </span>
                </div>
              </div>

              {/* 3단계 결재라인 */}
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-3">결재라인 (3단계)</h4>
                <div className="border rounded-lg overflow-hidden">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-3 py-2 text-center border-r w-1/3">
                          <div className="text-xs text-gray-500">1단계</div>
                          <div>생산지시자</div>
                        </th>
                        <th className="px-3 py-2 text-center border-r w-1/3">
                          <div className="text-xs text-gray-500">2단계</div>
                          <div>생산담당자</div>
                        </th>
                        <th className="px-3 py-2 text-center w-1/3">
                          <div className="text-xs text-gray-500">3단계</div>
                          <div>품질팀장</div>
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr className="border-t">
                        <td className="px-3 py-4 text-center border-r">
                          {workLogApproval.step1?.status === 'approved' ? (
                            <div className="flex flex-col items-center">
                              <CheckCircle className="w-8 h-8 text-green-500 mb-1" />
                              <span className="text-xs font-medium">{workLogApproval.step1?.submittedBy}</span>
                              <span className="text-xs text-gray-400">{workLogApproval.step1?.submittedAt?.slice(0, 10)}</span>
                            </div>
                          ) : (
                            <div className="flex flex-col items-center">
                              <div className="w-8 h-8 rounded-full border-2 border-dashed border-gray-300 mb-1" />
                              <span className="text-xs text-gray-400">미결재</span>
                            </div>
                          )}
                        </td>
                        <td className="px-3 py-4 text-center border-r">
                          {workLogApproval.step2?.status === 'approved' ? (
                            <div className="flex flex-col items-center">
                              <CheckCircle className="w-8 h-8 text-green-500 mb-1" />
                              <span className="text-xs font-medium">{workLogApproval.step2?.approvedBy}</span>
                              <span className="text-xs text-gray-400">{workLogApproval.step2?.approvedAt?.slice(0, 10)}</span>
                            </div>
                          ) : workLogApproval.status === 'step2_pending' ? (
                            <div className="flex flex-col items-center">
                              <Clock className="w-8 h-8 text-yellow-500 animate-pulse mb-1" />
                              <span className="text-xs text-yellow-600">결재 대기중</span>
                            </div>
                          ) : workLogApproval.rejectedStep === 2 ? (
                            <div className="flex flex-col items-center">
                              <XCircle className="w-8 h-8 text-red-500 mb-1" />
                              <span className="text-xs text-red-600">{workLogApproval.rejectedBy}</span>
                            </div>
                          ) : (
                            <div className="flex flex-col items-center">
                              <div className="w-8 h-8 rounded-full border-2 border-dashed border-gray-300 mb-1" />
                              <span className="text-xs text-gray-400">미결재</span>
                            </div>
                          )}
                        </td>
                        <td className="px-3 py-4 text-center">
                          {workLogApproval.step3?.status === 'approved' ? (
                            <div className="flex flex-col items-center">
                              <CheckCircle className="w-8 h-8 text-green-500 mb-1" />
                              <span className="text-xs font-medium">{workLogApproval.step3?.approvedBy}</span>
                              <span className="text-xs text-gray-400">{workLogApproval.step3?.approvedAt?.slice(0, 10)}</span>
                            </div>
                          ) : workLogApproval.status === 'step3_pending' ? (
                            <div className="flex flex-col items-center">
                              <Clock className="w-8 h-8 text-purple-500 animate-pulse mb-1" />
                              <span className="text-xs text-purple-600">결재 대기중</span>
                            </div>
                          ) : workLogApproval.rejectedStep === 3 ? (
                            <div className="flex flex-col items-center">
                              <XCircle className="w-8 h-8 text-red-500 mb-1" />
                              <span className="text-xs text-red-600">{workLogApproval.rejectedBy}</span>
                            </div>
                          ) : (
                            <div className="flex flex-col items-center">
                              <div className="w-8 h-8 rounded-full border-2 border-dashed border-gray-300 mb-1" />
                              <span className="text-xs text-gray-400">미결재</span>
                            </div>
                          )}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

              {/* 결재 진행 기록 */}
              <div className="border rounded-lg p-4">
                <h4 className="text-sm font-medium text-gray-700 mb-3">결재 진행 기록</h4>
                <div className="space-y-2 text-sm">
                  {workLogApproval.step1?.submittedAt && (
                    <div className="flex items-center gap-2 text-gray-600">
                      <CheckCircle className="w-4 h-4 text-green-500" />
                      <span>{workLogApproval.step1.submittedAt}</span>
                      <span className="font-medium">{workLogApproval.step1.submittedBy}</span>
                      <span>작성 완료 (1단계)</span>
                    </div>
                  )}
                  {workLogApproval.step2?.approvedAt && (
                    <div className="flex items-center gap-2 text-gray-600">
                      <CheckCircle className="w-4 h-4 text-green-500" />
                      <span>{workLogApproval.step2.approvedAt}</span>
                      <span className="font-medium">{workLogApproval.step2.approvedBy}</span>
                      <span>확인 완료 (2단계)</span>
                    </div>
                  )}
                  {workLogApproval.step3?.approvedAt && (
                    <div className="flex items-center gap-2 text-gray-600">
                      <CheckCircle className="w-4 h-4 text-green-500" />
                      <span>{workLogApproval.step3.approvedAt}</span>
                      <span className="font-medium">{workLogApproval.step3.approvedBy}</span>
                      <span>최종 승인 (3단계)</span>
                    </div>
                  )}
                  {workLogApproval.status === 'rejected' && (
                    <div className="flex items-center gap-2 text-red-600">
                      <XCircle className="w-4 h-4 text-red-500" />
                      <span>{workLogApproval.rejectedAt}</span>
                      <span className="font-medium">{workLogApproval.rejectedBy}</span>
                      <span>반려 ({workLogApproval.rejectedStep}단계)</span>
                    </div>
                  )}
                  {workLogApproval.status === 'draft' && (
                    <div className="text-gray-400 text-xs">아직 결재 기록이 없습니다.</div>
                  )}
                </div>
              </div>

              {/* 반려 사유 */}
              {workLogApproval.status === 'rejected' && workLogApproval.rejectReason && (
                <div className="p-4 bg-red-50 rounded-lg border border-red-200">
                  <h4 className="text-sm font-medium text-red-700 mb-1">반려 사유 ({workLogApproval.rejectedStep}단계)</h4>
                  <p className="text-sm text-red-600">{workLogApproval.rejectReason}</p>
                </div>
              )}

              {/* 투입 자재 정보 */}
              {selectedMaterials.length > 0 && (
                <div className="border rounded-lg p-4">
                  <h4 className="text-sm font-medium text-gray-700 mb-3">투입 원자재 (IQC 연계)</h4>
                  <table className="w-full text-xs">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-2 py-1 text-left">자재명</th>
                        <th className="px-2 py-1 text-left">입고로트</th>
                        <th className="px-2 py-1 text-center">수량</th>
                        <th className="px-2 py-1 text-center">IQC</th>
                      </tr>
                    </thead>
                    <tbody>
                      {selectedMaterials.map((mat, idx) => (
                        <tr key={idx} className="border-t">
                          <td className="px-2 py-1">{mat.name}</td>
                          <td className="px-2 py-1 font-mono">{mat.lotNo}</td>
                          <td className="px-2 py-1 text-center">{mat.qty} {mat.unit}</td>
                          <td className="px-2 py-1 text-center">
                            <span className="px-1.5 py-0.5 bg-green-100 text-green-700 rounded text-xs">합격</span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>

            <div className="p-6 border-t flex justify-between">
              <Button variant="outline" onClick={() => setShowApprovalModal(false)}>
                닫기
              </Button>
              <div className="flex gap-2">
                {/* 1단계: 작성 완료 */}
                {workLogApproval.status === 'draft' && (
                  <Button
                    variant="primary"
                    onClick={() => {
                      const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
                      setWorkLogApproval({
                        ...workLogApproval,
                        status: 'step2_pending',
                        step1: { status: 'approved', submittedAt: now, submittedBy: workOrder.assignee || '작업자' },
                      });
                      alert('1단계 작성 완료\n\n생산담당자에게 결재 요청이 전달됩니다.');
                    }}
                  >
                    <Send className="w-4 h-4" /> 1단계 상신
                  </Button>
                )}
                {/* 2단계: 생산담당자 확인 */}
                {workLogApproval.status === 'step2_pending' && (
                  <>
                    <Button variant="danger" onClick={() => {
                      const reason = prompt('반려 사유를 입력하세요:');
                      if (reason) {
                        const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
                        setWorkLogApproval({ ...workLogApproval, status: 'rejected', rejectedAt: now, rejectedBy: '생산담당 이생산', rejectReason: reason, rejectedStep: 2 });
                        alert('작업일지가 2단계에서 반려되었습니다.');
                      }
                    }}>
                      <XCircle className="w-4 h-4" /> 2단계 반려
                    </Button>
                    <Button variant="success" onClick={() => {
                      const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
                      setWorkLogApproval({ ...workLogApproval, status: 'step3_pending', step2: { status: 'approved', approvedAt: now, approvedBy: '생산담당 이생산' } });
                      alert('2단계 확인 완료\n\n품질팀장에게 최종 결재 요청이 전달됩니다.');
                    }}>
                      <CheckCircle className="w-4 h-4" /> 2단계 승인
                    </Button>
                  </>
                )}
                {/* 3단계: 품질팀장 최종 결재 */}
                {workLogApproval.status === 'step3_pending' && (
                  <>
                    <Button variant="danger" onClick={() => {
                      const reason = prompt('반려 사유를 입력하세요:');
                      if (reason) {
                        const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
                        setWorkLogApproval({ ...workLogApproval, status: 'rejected', rejectedAt: now, rejectedBy: '품질팀장 최품질', rejectReason: reason, rejectedStep: 3 });
                        alert('작업일지가 최종 단계에서 반려되었습니다.');
                      }
                    }}>
                      <XCircle className="w-4 h-4" /> 3단계 반려
                    </Button>
                    <Button variant="success" onClick={() => {
                      const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
                      setWorkLogApproval({ ...workLogApproval, status: 'approved', step3: { status: 'approved', approvedAt: now, approvedBy: '품질팀장 최품질' } });
                      alert('최종 승인 완료!\n\n중간검사성적서를 생성할 수 있습니다.');
                    }}>
                      <CheckCircle className="w-4 h-4" /> 최종 승인
                    </Button>
                  </>
                )}
                {/* 재상신 (반려 시) */}
                {workLogApproval.status === 'rejected' && (
                  <Button variant="primary" onClick={() => {
                    setWorkLogApproval({
                      ...workLogApproval, status: 'draft',
                      step1: { status: 'draft', submittedAt: null, submittedBy: null },
                      step2: { status: 'pending', approvedAt: null, approvedBy: null },
                      step3: { status: 'pending', approvedAt: null, approvedBy: null },
                      rejectedAt: null, rejectedBy: null, rejectReason: null, rejectedStep: null,
                    });
                    alert('작업일지를 수정 후 다시 상신해주세요.');
                  }}>
                    <Edit className="w-4 h-4" /> 수정 후 재상신
                  </Button>
                )}
                {/* 최종 승인 후 중간검사성적서 생성 */}
                {workLogApproval.status === 'approved' && (
                  <Button variant="primary" onClick={() => { setShowApprovalModal(false); setShowInspectionCertModal(true); }}>
                    <FileText className="w-4 h-4" /> 중간검사성적서 생성
                  </Button>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 투입 자재 선택 모달 (IQC 연계) */}
      {showMaterialSelectModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-3xl mx-4 max-h-[80vh] overflow-hidden flex flex-col">
            <div className="p-6 border-b">
              <h3 className="text-lg font-bold">투입 자재 선택 (IQC 합격 자재)</h3>
              <p className="text-sm text-gray-500 mt-1">IQC 검사 합격된 자재만 선택 가능합니다.</p>
            </div>
            <div className="flex-1 overflow-y-auto p-6">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 sticky top-0">
                  <tr>
                    <th className="px-3 py-2 text-center w-12">선택</th>
                    <th className="px-3 py-2 text-left">자재코드</th>
                    <th className="px-3 py-2 text-left">자재명</th>
                    <th className="px-3 py-2 text-left">입고로트</th>
                    <th className="px-3 py-2 text-center">가용수량</th>
                    <th className="px-3 py-2 text-center">IQC</th>
                  </tr>
                </thead>
                <tbody>
                  {[
                    { code: 'MAT-001', name: '원단 A (폴리에스터)', lotNo: '241210-001', qty: 500, unit: 'm', iqcStatus: '합격' },
                    { code: 'MAT-002', name: '원단 B (면)', lotNo: '241210-002', qty: 300, unit: 'm', iqcStatus: '합격' },
                    { code: 'MAT-003', name: '코일 (알루미늄)', lotNo: '241209-001', qty: 1000, unit: 'kg', iqcStatus: '합격' },
                    { code: 'MAT-004', name: '철판 (아연도금)', lotNo: '241208-003', qty: 200, unit: '장', iqcStatus: '합격' },
                    { code: 'MAT-005', name: '실 (흰색)', lotNo: '241207-001', qty: 50, unit: '롤', iqcStatus: '합격' },
                  ].map((mat, idx) => (
                    <tr key={idx} className="border-t hover:bg-gray-50">
                      <td className="px-3 py-2 text-center">
                        <input type="checkbox" checked={selectedMaterials.some(m => m.lotNo === mat.lotNo)}
                          onChange={(e) => {
                            if (e.target.checked) { setSelectedMaterials([...selectedMaterials, { ...mat, inputQty: mat.qty }]); }
                            else { setSelectedMaterials(selectedMaterials.filter(m => m.lotNo !== mat.lotNo)); }
                          }} className="w-4 h-4" />
                      </td>
                      <td className="px-3 py-2 font-mono text-xs">{mat.code}</td>
                      <td className="px-3 py-2">{mat.name}</td>
                      <td className="px-3 py-2 font-mono text-xs">{mat.lotNo}</td>
                      <td className="px-3 py-2 text-center">{mat.qty} {mat.unit}</td>
                      <td className="px-3 py-2 text-center">
                        <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">{mat.iqcStatus}</span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="p-6 border-t flex justify-between items-center">
              <div className="text-sm">선택: <span className="font-bold text-blue-600">{selectedMaterials.length}건</span></div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={() => setShowMaterialSelectModal(false)}>취소</Button>
                <Button variant="primary" onClick={() => {
                  if (selectedMaterials.length === 0) { alert('투입할 자재를 선택해주세요.'); return; }
                  alert(`${selectedMaterials.length}건의 자재가 투입 등록되었습니다.\n\n투입 로트: ${selectedMaterials.map(m => m.lotNo).join(', ')}`);
                  setShowMaterialSelectModal(false);
                }}>
                  <Package className="w-4 h-4" /> 자재 투입 확정
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 중간검사성적서 자동 생성 모달 */}
      {showInspectionCertModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-3xl mx-4 max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b">
              <h3 className="text-lg font-bold">중간검사성적서 자동 생성</h3>
              <p className="text-sm text-gray-500 mt-1">작업일지 기반으로 중간검사성적서가 자동 생성됩니다.</p>
            </div>
            <div className="p-6 space-y-6">
              {/* LOT 번호 정보 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">중간검사 LOT 번호</label>
                  <input type="text" className="w-full px-3 py-2 border rounded-lg bg-gray-50 font-mono"
                    value={`KD-WE-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-01-${workOrder?.currentStep || '중간검사'}`} readOnly />
                  <p className="text-xs text-gray-500 mt-1">형식: KD-WE-YYMMDD-##-공정</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">검사일자</label>
                  <input type="date" className="w-full px-3 py-2 border rounded-lg" value={inspectionCertData.inspectionDate}
                    onChange={(e) => setInspectionCertData({ ...inspectionCertData, inspectionDate: e.target.value })} />
                </div>
              </div>
              {/* 작업지시 정보 */}
              <div className="p-4 bg-gray-50 rounded-lg">
                <h4 className="text-sm font-medium text-gray-700 mb-3">작업지시 정보</h4>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div><span className="text-gray-500">작업지시번호:</span> <span className="font-medium">{workOrder?.workOrderNo}</span></div>
                  <div><span className="text-gray-500">공정:</span> <span className="font-medium">{workOrder?.processType}</span></div>
                  <div><span className="text-gray-500">품목:</span> <span className="font-medium">{workOrder?.itemName}</span></div>
                  <div><span className="text-gray-500">생산수량:</span> <span className="font-medium">{workOrder?.plannedQty}개</span></div>
                </div>
              </div>
              {/* 투입 원자재 */}
              <div className="border rounded-lg p-4">
                <h4 className="text-sm font-medium text-gray-700 mb-3">투입 원자재 (입고로트 추적)</h4>
                {selectedMaterials.length > 0 ? (
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-3 py-2 text-left">자재명</th>
                        <th className="px-3 py-2 text-left">입고로트</th>
                        <th className="px-3 py-2 text-center">투입수량</th>
                        <th className="px-3 py-2 text-center">IQC</th>
                      </tr>
                    </thead>
                    <tbody>
                      {selectedMaterials.map((mat, idx) => (
                        <tr key={idx} className="border-t">
                          <td className="px-3 py-2">{mat.name}</td>
                          <td className="px-3 py-2 font-mono text-xs">{mat.lotNo}</td>
                          <td className="px-3 py-2 text-center">{mat.inputQty || mat.qty} {mat.unit}</td>
                          <td className="px-3 py-2 text-center"><Button variant="outline" size="sm"><FileText className="w-3 h-3" /> 조회</Button></td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                ) : (
                  <div className="text-center py-4 text-gray-400">
                    <p className="text-sm">투입 자재가 등록되지 않았습니다.</p>
                    <Button variant="outline" size="sm" className="mt-2" onClick={() => { setShowInspectionCertModal(false); setShowMaterialSelectModal(true); }}>
                      <Plus className="w-4 h-4" /> 투입 자재 선택
                    </Button>
                  </div>
                )}
              </div>
              {/* 검사 항목 */}
              <div className="border rounded-lg p-4">
                <h4 className="text-sm font-medium text-gray-700 mb-3">검사 항목 (자동 생성)</h4>
                <table className="w-full text-sm">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-3 py-2 text-left">검사항목</th>
                      <th className="px-3 py-2 text-center">규격</th>
                      <th className="px-3 py-2 text-center">측정값</th>
                      <th className="px-3 py-2 text-center">판정</th>
                    </tr>
                  </thead>
                  <tbody>
                    {[
                      { item: '외관검사', spec: '스크래치/이물 없음', value: '양호', result: '합격' },
                      { item: '치수검사', spec: '±0.5mm', value: '0.3mm', result: '합격' },
                      { item: '동작검사', spec: '정상작동', value: '정상', result: '합격' },
                      { item: '중량검사', spec: '규격 ±5%', value: '2.8kg (-3%)', result: '합격' },
                    ].map((item, idx) => (
                      <tr key={idx} className="border-t">
                        <td className="px-3 py-2">{item.item}</td>
                        <td className="px-3 py-2 text-center">{item.spec}</td>
                        <td className="px-3 py-2 text-center">{item.value}</td>
                        <td className="px-3 py-2 text-center">
                          <span className={`px-2 py-0.5 rounded text-xs ${item.result === '합격' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>{item.result}</span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {/* 검사자 정보 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">검사자</label>
                  <select className="w-full px-3 py-2 border rounded-lg" value={inspectionCertData.inspector}
                    onChange={(e) => setInspectionCertData({ ...inspectionCertData, inspector: e.target.value })}>
                    <option value="">검사자 선택</option>
                    <option value="이검사">이검사 (품질팀)</option>
                    <option value="최품질">최품질 (품질팀장)</option>
                    <option value="김검사">김검사 (품질팀)</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">종합 판정</label>
                  <select className="w-full px-3 py-2 border rounded-lg" value={inspectionCertData.result}
                    onChange={(e) => setInspectionCertData({ ...inspectionCertData, result: e.target.value })}>
                    <option value="pending">판정 대기</option>
                    <option value="pass">합격</option>
                    <option value="fail">불합격</option>
                    <option value="conditional">조건부 합격</option>
                  </select>
                </div>
              </div>
            </div>
            <div className="p-6 border-t flex justify-between">
              <Button variant="outline" onClick={() => setShowInspectionCertModal(false)}>취소</Button>
              <div className="flex gap-2">
                <Button variant="outline"><Printer className="w-4 h-4" /> 미리보기</Button>
                <Button variant="primary" onClick={() => {
                  if (!inspectionCertData.inspector) { alert('검사자를 선택해주세요.'); return; }
                  if (inspectionCertData.result === 'pending') { alert('종합 판정을 선택해주세요.'); return; }
                  const lotNo = `KD-WE-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-01-${workOrder?.currentStep || '중간검사'}`;
                  alert(`중간검사성적서가 생성되었습니다.\n\nLOT 번호: ${lotNo}\n검사자: ${inspectionCertData.inspector}\n판정: ${inspectionCertData.result === 'pass' ? '합격' : inspectionCertData.result === 'fail' ? '불합격' : '조건부 합격'}\n\n투입 로트 추적 정보가 저장되었습니다.`);
                  setShowInspectionCertModal(false);
                }}>
                  <Save className="w-4 h-4" /> 성적서 저장
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 작업일지 양식보기 모달 - 실제 데이터 연동 */}
      {showWorkLogDataPreview && (
        <WorkLogDataPreviewModal
          workOrder={workOrder}
          workResults={relatedResults}
          order={relatedOrder}
          onClose={() => setShowWorkLogDataPreview(false)}
        />
      )}
    </div>
  );
};

// ============ 작업지시서 + 작업일지 함께 출력 컴포넌트 ============
const CombinedWorkOrderSheet = ({ workOrder, order, workLog, approvalStatus, onClose }) => {
  const printRef = React.useRef(null);
  const processType = workOrder?.processType || '스크린';

  const handlePrint = () => {
    const printContent = printRef.current;
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <html>
        <head>
          <title>작업지시서 및 작업일지 - ${workOrder?.workOrderNo}</title>
          <style>
            @media print {
              @page { size: A4; margin: 10mm; }
              .no-print { display: none !important; }
              .page-break { page-break-before: always; }
            }
            body { font-family: '맑은 고딕', sans-serif; font-size: 11px; margin: 0; padding: 0; }
            .sheet { width: 210mm; min-height: 297mm; padding: 10mm; box-sizing: border-box; }
            .header { text-align: center; margin-bottom: 15px; }
            .title { font-size: 24px; font-weight: bold; letter-spacing: 0.5em; margin-bottom: 10px; }
            .doc-no { font-size: 12px; color: #333; }
            table { width: 100%; border-collapse: collapse; margin-bottom: 10px; }
            th, td { border: 1px solid #000; padding: 6px 8px; font-size: 11px; }
            th { background: #f5f5f5; font-weight: bold; text-align: center; }
            .section-title { background: #000; color: #fff; padding: 6px 12px; font-weight: bold; letter-spacing: 0.2em; margin: 15px 0 5px; }
            .approval-box { position: absolute; top: 10mm; right: 10mm; }
            .approval-table th, .approval-table td { width: 50px; height: 35px; text-align: center; font-size: 10px; }
            .approval-signed { color: green; }
            .summary-box { display: flex; gap: 20px; margin: 10px 0; }
            .summary-item { flex: 1; text-align: center; padding: 10px; background: #f8f9fa; border: 1px solid #ddd; }
            .summary-value { font-size: 20px; font-weight: bold; }
          </style>
        </head>
        <body>${printContent.innerHTML}</body>
      </html>
    `);
    printWindow.document.close();
    printWindow.print();
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 overflow-auto py-8">
      <div className="bg-white rounded-xl shadow-xl max-w-4xl w-full mx-4 max-h-[95vh] overflow-auto">
        {/* 헤더 */}
        <div className="sticky top-0 bg-white p-4 border-b flex items-center justify-between z-10">
          <h3 className="text-lg font-bold flex items-center gap-2">
            <FileText className="w-5 h-5 text-blue-500" />
            작업지시서 + 작업일지 출력
          </h3>
          <div className="flex gap-2">
            <Button variant="outline" onClick={onClose}>닫기</Button>
            <Button variant="primary" onClick={handlePrint}>
              <Printer className="w-4 h-4" /> 인쇄
            </Button>
          </div>
        </div>

        {/* 출력 미리보기 */}
        <div ref={printRef} className="p-8">
          {/* ========== 1. 작업지시서 ========== */}
          <div className="sheet">
            {/* 결재란 */}
            <div style={{ position: 'relative' }}>
              <table className="approval-table" style={{ position: 'absolute', top: 0, right: 0, width: 'auto' }}>
                <thead>
                  <tr>
                    <th style={{ width: 55 }}>담당</th>
                    <th style={{ width: 55 }}>부서장</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td style={{ height: 40 }} className={approvalStatus?.status !== 'draft' ? 'approval-signed' : ''}>
                      {approvalStatus?.status !== 'draft' && '✓'}
                    </td>
                    <td style={{ height: 40 }} className={approvalStatus?.status === 'approved' ? 'approval-signed' : ''}>
                      {approvalStatus?.status === 'approved' && '✓'}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <div className="header" style={{ marginTop: 60 }}>
              <div className="title">작 업 지 시 서</div>
              <div className="doc-no">문서번호: {workOrder?.workOrderNo}</div>
            </div>

            {/* 기본정보 */}
            <div className="section-title">작 업 지 시 정 보</div>
            <table>
              <tbody>
                <tr>
                  <th style={{ width: '15%' }}>지시번호</th>
                  <td style={{ width: '35%' }}>{workOrder?.workOrderNo}</td>
                  <th style={{ width: '15%' }}>지시일자</th>
                  <td style={{ width: '35%' }}>{workOrder?.orderDate}</td>
                </tr>
                <tr>
                  <th>수주LOT</th>
                  <td>{order?.lotNo || workOrder?.orderNo}</td>
                  <th>납기일</th>
                  <td style={{ color: 'red', fontWeight: 'bold' }}>{workOrder?.dueDate}</td>
                </tr>
                <tr>
                  <th>거래처</th>
                  <td>{workOrder?.customerName}</td>
                  <th>현장명</th>
                  <td>{workOrder?.siteName}</td>
                </tr>
                <tr>
                  <th>공정</th>
                  <td>{workOrder?.processType}</td>
                  <th>작업자</th>
                  <td>{workOrder?.assignee || '-'}</td>
                </tr>
              </tbody>
            </table>

            {/* 작업품목 */}
            <div className="section-title">작 업 품 목</div>
            <table>
              <thead>
                <tr>
                  <th>No</th>
                  <th>품목코드</th>
                  <th>품목명</th>
                  <th>규격</th>
                  <th>지시수량</th>
                  <th>단위</th>
                  <th>비고</th>
                </tr>
              </thead>
              <tbody>
                {workOrder?.items?.map((item, idx) => (
                  <tr key={item.id}>
                    <td style={{ textAlign: 'center' }}>{idx + 1}</td>
                    <td>{item.productCode}</td>
                    <td>{item.productName}</td>
                    <td style={{ textAlign: 'center' }}>{item.spec}</td>
                    <td style={{ textAlign: 'right' }}>{item.qty}</td>
                    <td style={{ textAlign: 'center' }}>{item.unit}</td>
                    <td>{item.floor ? `${item.floor} / ${item.location}` : ''}</td>
                  </tr>
                ))}
              </tbody>
            </table>

            {/* 지시사항 */}
            <div className="section-title">지 시 사 항</div>
            <div style={{ border: '1px solid #000', minHeight: 60, padding: 8 }}>
              {workOrder?.note || '특이사항 없음'}
            </div>
          </div>

          {/* 페이지 구분 */}
          <div className="page-break" />

          {/* ========== 2. 작업일지 ========== */}
          <div className="sheet">
            {/* 결재란 */}
            <div style={{ position: 'relative' }}>
              <table className="approval-table" style={{ position: 'absolute', top: 0, right: 0, width: 'auto' }}>
                <thead>
                  <tr>
                    <th style={{ width: 55 }}>담당</th>
                    <th style={{ width: 55 }}>부서장</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td style={{ height: 40 }} className={approvalStatus?.status !== 'draft' ? 'approval-signed' : ''}>
                      {approvalStatus?.status !== 'draft' && (
                        <div style={{ fontSize: 9 }}>
                          <div>✓</div>
                          <div>{approvalStatus?.submittedBy}</div>
                        </div>
                      )}
                    </td>
                    <td style={{ height: 40 }} className={approvalStatus?.status === 'approved' ? 'approval-signed' : ''}>
                      {approvalStatus?.status === 'approved' && (
                        <div style={{ fontSize: 9 }}>
                          <div>✓</div>
                          <div>{approvalStatus?.approvedBy}</div>
                        </div>
                      )}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <div className="header" style={{ marginTop: 60 }}>
              <div className="title">{processType} 작 업 일 지</div>
              <div className="doc-no">문서번호: WL-{processType === '스크린' ? 'SCR' : processType === '슬랫' ? 'SLT' : 'FLD'}-{workLog?.workDate?.replace(/-/g, '') || ''}-01</div>
            </div>

            {/* 기본정보 */}
            <div className="section-title">기 본 정 보</div>
            <table>
              <tbody>
                <tr>
                  <th style={{ width: '15%' }}>작업일자</th>
                  <td style={{ width: '35%' }}>{workLog?.workDate}</td>
                  <th style={{ width: '15%' }}>담당자</th>
                  <td style={{ width: '35%' }}>{workLog?.productionManager || workOrder?.assignee}</td>
                </tr>
                <tr>
                  <th>거래처</th>
                  <td>{workOrder?.customerName}</td>
                  <th>현장명</th>
                  <td>{workOrder?.siteName}</td>
                </tr>
                <tr>
                  <th>제품LOT</th>
                  <td>{workLog?.productLotNo || '-'}</td>
                  <th>지시번호</th>
                  <td>{workOrder?.workOrderNo}</td>
                </tr>
              </tbody>
            </table>

            {/* 생산실적 요약 */}
            <div className="section-title">생 산 실 적</div>
            <div className="summary-box" style={{ display: 'flex', gap: 15, margin: '10px 0' }}>
              <div className="summary-item" style={{ flex: 1, textAlign: 'center', padding: 12, background: '#e3f2fd', border: '1px solid #2196f3' }}>
                <div style={{ fontSize: 11, color: '#1565c0' }}>생산량</div>
                <div className="summary-value" style={{ fontSize: 22, fontWeight: 'bold', color: '#1565c0' }}>
                  {workLog?.productionResult?.totalProduced || workLog?.totalProduction?.sus + workLog?.totalProduction?.egi || 0}
                </div>
              </div>
              <div className="summary-item" style={{ flex: 1, textAlign: 'center', padding: 12, background: '#e8f5e9', border: '1px solid #4caf50' }}>
                <div style={{ fontSize: 11, color: '#2e7d32' }}>양품</div>
                <div className="summary-value" style={{ fontSize: 22, fontWeight: 'bold', color: '#2e7d32' }}>
                  {workLog?.productionResult?.goodQty || 0}
                </div>
              </div>
              <div className="summary-item" style={{ flex: 1, textAlign: 'center', padding: 12, background: '#ffebee', border: '1px solid #f44336' }}>
                <div style={{ fontSize: 11, color: '#c62828' }}>불량</div>
                <div className="summary-value" style={{ fontSize: 22, fontWeight: 'bold', color: '#c62828' }}>
                  {workLog?.productionResult?.defectQty || 0}
                </div>
              </div>
            </div>

            {/* 작업내역 (공정별) */}
            <div className="section-title">작 업 내 역</div>
            {processType === '스크린' && workLog?.workItems && (
              <table>
                <thead>
                  <tr>
                    <th>공정</th>
                    <th>수량</th>
                    <th>단위</th>
                  </tr>
                </thead>
                <tbody>
                  {workLog.workItems.filter(item => item.qty).map(item => (
                    <tr key={item.id}>
                      <td>{item.step}</td>
                      <td style={{ textAlign: 'right' }}>{item.qty}</td>
                      <td style={{ textAlign: 'center' }}>{item.unit}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
            {processType === '슬랫' && workLog?.cuttingDetails && (
              <table>
                <thead>
                  <tr>
                    <th>길이</th>
                    <th>수량(EA)</th>
                  </tr>
                </thead>
                <tbody>
                  {workLog.cuttingDetails.filter(item => item.qty).map(item => (
                    <tr key={item.id}>
                      <td style={{ textAlign: 'center' }}>{item.length}</td>
                      <td style={{ textAlign: 'right' }}>{item.qty}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
            {processType === '절곡' && (
              <>
                {workLog?.guideRail?.some(item => item.qty) && (
                  <table style={{ marginBottom: 10 }}>
                    <thead>
                      <tr>
                        <th colSpan={3}>벽면형 (120·70)</th>
                      </tr>
                      <tr>
                        <th>부품</th>
                        <th>규격</th>
                        <th>수량</th>
                      </tr>
                    </thead>
                    <tbody>
                      {workLog.guideRail.filter(item => item.qty).map(item => (
                        <tr key={item.id}>
                          <td>{item.name}</td>
                          <td style={{ textAlign: 'center' }}>{item.spec}</td>
                          <td style={{ textAlign: 'right' }}>{item.qty}개</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
              </>
            )}

            {/* 비고 */}
            <div className="section-title">비 고</div>
            <div style={{ border: '1px solid #000', minHeight: 50, padding: 8 }}>
              {workLog?.remarks || '특이사항 없음'}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============ 작업실적 ============

// 작업실적 입력
const WorkResultInput = ({ workOrder, onNavigate, onBack, onSave }) => {
  const [formData, setFormData] = useState({
    workOrderNo: workOrder?.workOrderNo || '',
    workDate: new Date().toISOString().split('T')[0],
    productCode: workOrder?.items?.[0]?.productCode || '',
    productionQty: 1,
    goodQty: 1,
    defectQty: 0,
    defectType: '',
    inspectionCompleted: false,
    packingCompleted: false,
    worker: '',
    note: '',
  });

  const defectTypes = ['치수불량', '외관불량', '작동불량', '자재불량', '기타'];

  const handleChange = (field, value) => {
    setFormData(prev => {
      const updated = { ...prev, [field]: value };
      // 불량수량 자동 계산
      if (field === 'productionQty' || field === 'goodQty') {
        const prodQty = field === 'productionQty' ? value : prev.productionQty;
        const goodQty = field === 'goodQty' ? value : prev.goodQty;
        updated.defectQty = Math.max(0, prodQty - goodQty);
      }
      return updated;
    });
  };

  const handleSubmit = () => {
    // LOT번호 자동 생성
    const lotNo = `LOT-${formData.workDate.replace(/-/g, '')}-${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`;
    const newResult = {
      ...formData,
      lotNo,
      processType: workOrder?.processType,
      productName: workOrder?.items?.find(i => i.productCode === formData.productCode)?.productName || '',
      spec: workOrder?.items?.find(i => i.productCode === formData.productCode)?.spec || '',
    };
    onSave?.(newResult);
    onBack();
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button onClick={onBack} className="p-2 hover:bg-gray-100 rounded-lg">
            <ArrowLeft className="w-5 h-5 text-gray-500" />
          </button>
          <BarChart3 className="w-6 h-6 text-green-500" />
          <h1 className="text-xl font-bold text-gray-900">작업실적 입력</h1>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={onBack}>취소</Button>
          <Button variant="primary" onClick={handleSubmit}>
            <Check className="w-4 h-4" /> 저장
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6">
        <Card title="작업지시 정보">
          <div className="grid grid-cols-2 gap-4">
            <InfoRow label="작업지시번호" value={workOrder?.workOrderNo} />
            <InfoRow label="공정" value={workOrder?.processType} />
            <InfoRow label="발주처" value={workOrder?.customerName} />
            <InfoRow label="현장명" value={workOrder?.siteName} />
            <InfoRow label="지시수량" value={workOrder?.totalQty} />
            <InfoRow label="잔여수량" value={workOrder?.totalQty - workOrder?.completedQty} />
          </div>
        </Card>

        <Card title="실적 입력">
          <div className="space-y-4">
            <FormField label="작업일자" required>
              <input
                type="date"
                value={formData.workDate}
                onChange={(e) => handleChange('workDate', e.target.value)}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </FormField>

            <FormField label="품목 선택" required>
              <select
                value={formData.productCode}
                onChange={(e) => handleChange('productCode', e.target.value)}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {workOrder?.items?.map(item => (
                  <option key={item.id} value={item.productCode}>
                    {item.productCode} - {item.productName} ({item.spec})
                  </option>
                ))}
              </select>
            </FormField>

            <div className="grid grid-cols-3 gap-4">
              <FormField label="생산수량" required>
                <input
                  type="number"
                  min="1"
                  value={formData.productionQty}
                  onChange={(e) => handleChange('productionQty', parseInt(e.target.value) || 0)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </FormField>
              <FormField label="양품수량" required>
                <input
                  type="number"
                  min="0"
                  max={formData.productionQty}
                  value={formData.goodQty}
                  onChange={(e) => handleChange('goodQty', parseInt(e.target.value) || 0)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </FormField>
              <FormField label="불량수량">
                <input
                  type="number"
                  value={formData.defectQty}
                  disabled
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-red-600 font-medium"
                />
              </FormField>
            </div>

            {formData.defectQty > 0 && (
              <FormField label="불량유형" required>
                <select
                  value={formData.defectType}
                  onChange={(e) => handleChange('defectType', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">선택하세요</option>
                  {defectTypes.map(type => (
                    <option key={type} value={type}>{type}</option>
                  ))}
                </select>
              </FormField>
            )}

            <FormField label="작업자" required>
              <TextInput
                placeholder="작업자명 입력"
                value={formData.worker}
                onChange={(v) => handleChange('worker', v)}
              />
            </FormField>

            <div className="flex gap-6 pt-2">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={formData.inspectionCompleted}
                  onChange={(e) => handleChange('inspectionCompleted', e.target.checked)}
                  className="w-5 h-5 rounded border-gray-300 text-blue-500 focus:ring-blue-500"
                />
                <span className="text-sm font-medium">중간검사 완료</span>
              </label>
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={formData.packingCompleted}
                  onChange={(e) => handleChange('packingCompleted', e.target.checked)}
                  className="w-5 h-5 rounded border-gray-300 text-blue-500 focus:ring-blue-500"
                />
                <span className="text-sm font-medium">포장 완료</span>
              </label>
            </div>

            <FormField label="비고">
              <textarea
                value={formData.note}
                onChange={(e) => handleChange('note', e.target.value)}
                placeholder="특이사항 입력"
                rows={3}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </FormField>
          </div>
        </Card>
      </div>

      {/* LOT 자동생성 안내 */}
      <div className="flex items-start gap-2 p-4 bg-blue-50 rounded-lg text-sm text-blue-700">
        <AlertCircle className="w-5 h-5 mt-0.5 flex-shrink-0" />
        <div>
          <p className="font-medium">LOT번호 자동생성</p>
          <p className="text-blue-600 mt-1">
            저장 시 LOT번호가 자동으로 생성됩니다. (형식: LOT-YYYYMMDD-XXX)
          </p>
        </div>
      </div>
    </div>
  );
};

// 작업실적 조회
const WorkResultList = ({ workResults, onNavigate }) => {
  const [search, setSearch] = useState('');

  // ID 내림차순 정렬 - 최신 등록 최상단
  const filtered = workResults
    .filter(r =>
      r.lotNo.toLowerCase().includes(search.toLowerCase()) ||
      r.workOrderNo.toLowerCase().includes(search.toLowerCase()) ||
      r.productName.includes(search)
    )
    .sort((a, b) => b.id - a.id);

  // 통계
  const totalProduction = workResults.reduce((sum, r) => sum + r.productionQty, 0);
  const totalGood = workResults.reduce((sum, r) => sum + r.goodQty, 0);
  const totalDefect = workResults.reduce((sum, r) => sum + r.defectQty, 0);
  const defectRate = totalProduction > 0 ? ((totalDefect / totalProduction) * 100).toFixed(1) : 0;

  return (
    <div className="space-y-6">
      <PageHeader
        icon={BarChart3}
        title="작업실적 조회"
        actions={
          <Button variant="outline">
            <Download className="w-4 h-4" /> 엑셀 다운로드
          </Button>
        }
      />

      {/* 대시보드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <DashboardCard icon={Factory} title="총 생산수량" value={`${totalProduction}개`} color="blue" />
        <DashboardCard icon={CheckCircle} title="양품수량" value={`${totalGood}개`} color="green" />
        <DashboardCard icon={XCircle} title="불량수량" value={`${totalDefect}개`} color="yellow" />
        <DashboardCard icon={BarChart3} title="불량률" value={`${defectRate}%`} color="purple" />
      </div>

      {/* 검색바 */}
      <SearchInput
        placeholder="로트번호, 작업지시번호, 품목명 검색..."
        value={search}
        onChange={setSearch}
      />

      <div className="bg-white rounded-xl border overflow-hidden">
        {/* 일괄 내보내기 기능 추가 예정 - 체크박스 비활성화 상태 */}
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-3 py-3 text-center">
                <input type="checkbox" disabled className="rounded border-gray-300 cursor-not-allowed opacity-50" title="일괄 내보내기 기능 추가 예정" />
              </th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">로트번호</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">작업일</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">작업지시번호</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">공정</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">규격</th>
              <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">생산</th>
              <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">양품</th>
              <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">불량</th>
              <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">불량률</th>
              <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">검사</th>
              <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">포장</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">작업자</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map(result => (
              <tr key={result.id} className="hover:bg-gray-50">
                <td className="px-3 py-3 text-center">
                  <input type="checkbox" disabled className="rounded border-gray-300 cursor-not-allowed opacity-50" title="일괄 내보내기 기능 추가 예정" />
                </td>
                <td className="px-4 py-3 text-sm font-mono text-blue-600">{result.lotNo}</td>
                <td className="px-4 py-3 text-sm">{result.workDate}</td>
                <td className="px-4 py-3 text-sm font-mono text-gray-600">{result.workOrderNo}</td>
                <td className="px-4 py-3">
                  <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium
                    ${result.processType === '스크린' ? 'bg-blue-100 text-blue-700' : ''}
                    ${result.processType === '슬랫' ? 'bg-purple-100 text-purple-700' : ''}
                    ${result.processType === '절곡' ? 'bg-orange-100 text-orange-700' : ''}
                  `}>
                    {result.processType}
                  </span>
                </td>
                <td className="px-4 py-3 text-sm">{result.productName}</td>
                <td className="px-4 py-3 text-sm">{result.spec}</td>
                <td className="px-4 py-3 text-sm text-right">{result.productionQty}</td>
                <td className="px-4 py-3 text-sm text-right text-green-600">{result.goodQty}</td>
                <td className="px-4 py-3 text-sm text-right text-red-600">{result.defectQty}</td>
                <td className="px-4 py-3 text-sm text-center">
                  {result.productionQty > 0
                    ? <span className={result.defectQty > 0 ? 'text-red-600' : 'text-green-600'}>
                      {((result.defectQty / result.productionQty) * 100).toFixed(1)}%
                    </span>
                    : '-'
                  }
                </td>
                <td className="px-4 py-3 text-center">
                  {result.inspectionCompleted
                    ? <CheckCircle className="w-4 h-4 text-green-500 mx-auto" />
                    : <span className="text-gray-400">-</span>
                  }
                </td>
                <td className="px-4 py-3 text-center">
                  {result.packingCompleted
                    ? <CheckCircle className="w-4 h-4 text-green-500 mx-auto" />
                    : <span className="text-gray-400">-</span>
                  }
                </td>
                <td className="px-4 py-3 text-sm">{result.worker}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// ============ 출고 관리 (수주 연동) ============

/**
 * 출고관리 구조 설계
 * ===================
 *
 * 📋 출고 관리자 기능
 * - 출고 준비 확인: 출고단위별 공장별 작업 완료 확인
 * - 반제품/부품 출고구역 도착 확인
 * - 출고 우선순위 지정
 *
 * 🚚 배송 방식별 관리
 * 1. 직접배차 (발주처 차량): 입차시간 확인/조율, 휴대폰/카톡 소통
 * 2. 상차 (물류업체): 물량(차량톤수) 확정, 배송지 확인, 상차시간 조율, 입차시간 확정
 * 3. 택배/화물/직접배송: 운송담당자 지정, 운송시간 관리
 *
 * 📊 출고 변경 관리
 * - 출고일 변경
 * - 출고 취소
 * - 미출고 사유 관리
 *
 * 📦 상차 작업
 * - 상차담당자 지정
 * - 품목 체크리스트: 부품/부자재 누락 방지, 품목 리스트 확인, 수량 체크, 부자재 로트번호 입력
 *
 * 수주 연동 구조:
 * - 수주 → 출고 (lotNo 기준 연동)
 * - 수주분할번호(splitNo)로 출고 식별
 * - 수주의 생산완료 상태에서만 출고 가능
 */

// 배차유형 옵션
const dispatchTypes = ['직접배차', '상차', '택배', '화물', '직접배송'];
const vehicleTypes = ['1톤', '2.5톤', '5톤', '11톤', '25톤'];
const logisticsCompanies = ['한진물류', 'CJ대한통운', '롯데택배', '로젠택배', '우체국택배', '경동택배', '기타'];

// 출고 우선순위 옵션
const priorityOptions = [
  { value: 1, label: '긴급', color: 'bg-red-100 text-red-700' },
  { value: 2, label: '높음', color: 'bg-orange-100 text-orange-700' },
  { value: 3, label: '보통', color: 'bg-blue-100 text-blue-700' },
  { value: 4, label: '낮음', color: 'bg-gray-100 text-gray-700' },
];

// 미출고 사유 옵션
const nonShipmentReasons = [
  '생산 지연',
  '품질 이슈',
  '자재 미입고',
  '고객 요청',
  '배송 일정 조율',
  '입금 미확인',
  '서류 미비',
  '기타',
];

// 출고일정 캘린더 뷰 컴포넌트
const ShipmentCalendarView = ({ shipments, calendarDate, setCalendarDate, selectedCalendarDate, setSelectedCalendarDate, onNavigate }) => {
  const year = calendarDate.getFullYear();
  const month = calendarDate.getMonth();
  const startDayOfWeek = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const goToPrevMonth = () => setCalendarDate(new Date(year, month - 1, 1));
  const goToNextMonth = () => setCalendarDate(new Date(year, month + 1, 1));
  const goToToday = () => setCalendarDate(new Date());
  const getShipmentsForDate = (dateStr) => shipments.filter(s => s.shipmentDate === dateStr);
  const getStatusColor = (status) => {
    switch (status) {
      case '출고대기': case '출고지시': return 'bg-yellow-500';
      case '출고준비': case '출하준비': return 'bg-blue-500';
      case '상차대기': case '출하대기': return 'bg-purple-500';
      case '배송중': return 'bg-orange-500';
      case '배송완료': return 'bg-green-500';
      default: return 'bg-gray-400';
    }
  };
  const monthStr = `${year}-${String(month + 1).padStart(2, '0')}`;
  const monthlyStats = {
    total: shipments.filter(s => s.shipmentDate?.startsWith(monthStr)).length,
    waiting: shipments.filter(s => s.shipmentDate?.startsWith(monthStr) && (s.status === '출고대기' || s.status === '출고지시')).length,
    shipping: shipments.filter(s => s.shipmentDate?.startsWith(monthStr) && s.status === '배송중').length,
    complete: shipments.filter(s => s.shipmentDate?.startsWith(monthStr) && s.status === '배송완료').length,
  };
  const renderCalendarCells = () => {
    const cells = [];
    const today = new Date().toISOString().split('T')[0];
    for (let i = 0; i < startDayOfWeek; i++) cells.push(<div key={`empty-${i}`} className="h-28 bg-gray-50 border border-gray-100" />);
    for (let day = 1; day <= daysInMonth; day++) {
      const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
      const dayShipments = getShipmentsForDate(dateStr);
      const isToday = dateStr === today;
      const isSelected = dateStr === selectedCalendarDate;
      const dayOfWeek = new Date(year, month, day).getDay();
      cells.push(
        <div key={day} onClick={() => setSelectedCalendarDate(dateStr === selectedCalendarDate ? null : dateStr)} className={`h-28 border border-gray-200 p-1 cursor-pointer transition-all hover:bg-blue-50 ${isToday ? 'bg-blue-50 border-blue-300' : 'bg-white'} ${isSelected ? 'ring-2 ring-blue-500' : ''}`}>
          <div className="flex justify-between items-center mb-1">
            <span className={`text-sm font-medium ${isToday ? 'bg-blue-600 text-white w-6 h-6 rounded-full flex items-center justify-center' : ''} ${dayOfWeek === 0 && !isToday ? 'text-red-500' : ''} ${dayOfWeek === 6 && !isToday ? 'text-blue-500' : ''}`}>{day}</span>
            {dayShipments.length > 0 && <span className="text-xs bg-gray-100 text-gray-600 px-1.5 py-0.5 rounded">{dayShipments.length}건</span>}
          </div>
          <div className="space-y-0.5 overflow-y-auto max-h-16">
            {dayShipments.slice(0, 3).map((shipment, idx) => (<div key={idx} onClick={(e) => { e.stopPropagation(); onNavigate('shipment-detail', shipment); }} className={`text-xs px-1.5 py-0.5 rounded truncate text-white ${getStatusColor(shipment.status)} hover:opacity-80`} title={`${shipment.splitNo} - ${shipment.customerName}`}>{shipment.customerName?.substring(0, 6)}</div>))}
            {dayShipments.length > 3 && <div className="text-xs text-gray-500 text-center">+{dayShipments.length - 3}건</div>}
          </div>
        </div>
      );
    }
    return cells;
  };
  const selectedDateShipments = selectedCalendarDate ? getShipmentsForDate(selectedCalendarDate) : [];
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-4 gap-4">
        <div className="bg-white rounded-lg border p-4"><div className="text-sm text-gray-500">이달 전체 출고</div><div className="text-2xl font-bold text-gray-900">{monthlyStats.total}건</div></div>
        <div className="bg-white rounded-lg border p-4"><div className="text-sm text-gray-500">출고대기</div><div className="text-2xl font-bold text-yellow-600">{monthlyStats.waiting}건</div></div>
        <div className="bg-white rounded-lg border p-4"><div className="text-sm text-gray-500">배송중</div><div className="text-2xl font-bold text-orange-600">{monthlyStats.shipping}건</div></div>
        <div className="bg-white rounded-lg border p-4"><div className="text-sm text-gray-500">배송완료</div><div className="text-2xl font-bold text-green-600">{monthlyStats.complete}건</div></div>
      </div>
      <div className="bg-white rounded-xl border overflow-hidden">
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <div className="flex items-center gap-4"><h3 className="text-lg font-bold text-gray-900">{year}년 {month + 1}월</h3><button onClick={goToToday} className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200">오늘</button></div>
          <div className="flex items-center gap-2"><button onClick={goToPrevMonth} className="p-2 hover:bg-gray-100 rounded-lg"><ChevronLeft className="w-5 h-5" /></button><button onClick={goToNextMonth} className="p-2 hover:bg-gray-100 rounded-lg"><ChevronRight className="w-5 h-5" /></button></div>
        </div>
        <div className="grid grid-cols-7 bg-gray-50 border-b">{['일', '월', '화', '수', '목', '금', '토'].map((d, idx) => (<div key={d} className={`py-3 text-center text-sm font-medium ${idx === 0 ? 'text-red-500' : ''} ${idx === 6 ? 'text-blue-500' : ''} ${idx > 0 && idx < 6 ? 'text-gray-600' : ''}`}>{d}</div>))}</div>
        <div className="grid grid-cols-7">{renderCalendarCells()}</div>
        <div className="flex items-center gap-4 px-6 py-3 border-t bg-gray-50">
          <span className="text-xs text-gray-500">상태:</span>
          <div className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-yellow-500"></span><span className="text-xs text-gray-600">출고대기</span></div>
          <div className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-blue-500"></span><span className="text-xs text-gray-600">출고준비</span></div>
          <div className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-purple-500"></span><span className="text-xs text-gray-600">상차대기</span></div>
          <div className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-orange-500"></span><span className="text-xs text-gray-600">배송중</span></div>
          <div className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-green-500"></span><span className="text-xs text-gray-600">배송완료</span></div>
        </div>
      </div>
      {selectedCalendarDate && (
        <div className="bg-white rounded-xl border overflow-hidden">
          <div className="px-6 py-4 border-b bg-gray-50"><h4 className="font-medium text-gray-900">{selectedCalendarDate} 출고 일정 ({selectedDateShipments.length}건)</h4></div>
          {selectedDateShipments.length > 0 ? (
            <div className="divide-y">{selectedDateShipments.map((shipment, idx) => {
              const priority = priorityOptions.find(p => p.value === shipment.shipmentPriority) || priorityOptions[2];
              return (<div key={idx} onClick={() => onNavigate('shipment-detail', shipment)} className="px-6 py-4 hover:bg-gray-50 cursor-pointer flex items-center justify-between">
                <div className="flex items-center gap-4"><span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${priority.color}`}>{priority.label}</span><div><div className="font-medium text-gray-900">{shipment.splitNo}</div><div className="text-sm text-gray-500">{shipment.customerName} - {shipment.siteName}</div></div></div>
                <div className="flex items-center gap-4"><span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${shipment.dispatchType === '직접배차' ? 'bg-purple-100 text-purple-700' : shipment.dispatchType === '상차' ? 'bg-blue-100 text-blue-700' : shipment.dispatchType === '택배' ? 'bg-green-100 text-green-700' : shipment.dispatchType === '화물' ? 'bg-orange-100 text-orange-700' : 'bg-gray-100 text-gray-700'}`}>{shipment.dispatchType}</span><StatusBadge status={shipment.status} /><ChevronRight className="w-4 h-4 text-gray-400" /></div>
              </div>);
            })}</div>
          ) : (<div className="text-center py-12 text-gray-500"><Calendar className="w-12 h-12 mx-auto mb-3 text-gray-300" /><p>해당 날짜에 출고 일정이 없습니다.</p></div>)}
        </div>
      )}
    </div>
  );
};

// 출하 목록 (수주 연동)
const ShipmentList = ({ shipments, orders = [], onNavigate, onDeleteShipments }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [dispatchFilter, setDispatchFilter] = useState('all');
  const [priorityFilter, setPriorityFilter] = useState('all');
  const [selectedIds, setSelectedIds] = useState([]);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showCancelModal, setShowCancelModal] = useState(false);
  const [cancelReason, setCancelReason] = useState('');
  const [selectedForCancel, setSelectedForCancel] = useState(null);
  const [showPriorityModal, setShowPriorityModal] = useState(false);
  const [selectedForPriority, setSelectedForPriority] = useState(null);
  const [newPriority, setNewPriority] = useState(3);

  // 캘린더 관련 상태
  const [calendarDate, setCalendarDate] = useState(new Date());
  const [selectedCalendarDate, setSelectedCalendarDate] = useState(null);

  // 수주 정보 가져오기 헬퍼
  const getOrderInfo = (lotNo) => orders.find(o => o.lotNo === lotNo || o.orderNo === lotNo);

  const tabs = [
    { id: 'all', label: '전체', count: shipments.length },
    { id: 'waiting', label: '출고예정', count: shipments.filter(s => s.status === '출고예정' || s.status === '출고대기' || s.status === '출고지시').length },
    { id: 'ready', label: '출하대기', count: shipments.filter(s => s.status === '출하대기' || s.status === '출고준비' || s.status === '출하준비').length },
    { id: 'shipping', label: '배송중', count: shipments.filter(s => s.status === '배송중').length },
    { id: 'complete', label: '배송완료', count: shipments.filter(s => s.status === '배송완료').length },
    { id: 'calendar', label: '출하일정', icon: Calendar },
  ];

  const statusFilter = {
    all: () => true,
    waiting: (s) => s.status === '출고대기' || s.status === '출고지시',
    ready: (s) => s.status === '출고준비' || s.status === '출하준비',
    loading: (s) => s.status === '상차대기' || s.status === '출하대기',
    shipping: (s) => s.status === '배송중',
    complete: (s) => s.status === '배송완료',
  };

  // 우선순위별 필터
  const applyPriorityFilter = (list) => {
    if (priorityFilter === 'all') return list;
    return list.filter(s => s.shipmentPriority === parseInt(priorityFilter));
  };

  const filtered = applyPriorityFilter(
    shipments
      .filter(statusFilter[activeTab] || (() => true))
      .filter(s => dispatchFilter === 'all' || s.dispatchType === dispatchFilter)
      .filter(s =>
        s.splitNo?.toLowerCase().includes(search.toLowerCase()) ||
        s.customerName?.includes(search) ||
        s.siteName?.includes(search) ||
        s.lotNo?.toLowerCase().includes(search.toLowerCase())
      )
      .sort((a, b) => b.id - a.id) // ID 기준 내림차순 (최신 등록 최상단)
  );

  // 전체 선택/해제
  const handleSelectAll = (e) => {
    if (e.target.checked) {
      setSelectedIds(filtered.map(s => s.id));
    } else {
      setSelectedIds([]);
    }
  };

  // 개별 선택
  const handleSelectOne = (id, e) => {
    e.stopPropagation();
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  };

  // 삭제 확인
  const handleDeleteConfirm = () => {
    if (onDeleteShipments && selectedIds.length > 0) {
      onDeleteShipments(selectedIds);
    }
    setSelectedIds([]);
    setShowDeleteModal(false);
  };

  // 통계
  const todayShipments = shipments.filter(s => s.shipmentDate === new Date().toISOString().split('T')[0]).length;
  const unpaidShipments = shipments.filter(s =>
    (!s.paymentConfirmed || !s.taxInvoiceIssued) && s.status !== '배송완료'
  ).length;
  const urgentShipments = shipments.filter(s => s.shipmentPriority === 1 && s.status !== '배송완료').length;

  // 출고 취소 핸들러
  const handleCancelShipment = () => {
    if (selectedForCancel && cancelReason) {
      // 실제로는 onUpdate를 통해 출고 취소 처리
      alert(`출고가 취소되었습니다.\n\n출고번호: ${selectedForCancel.releaseNo || '-'}\n취소사유: ${cancelReason}`);
      setShowCancelModal(false);
      setSelectedForCancel(null);
      setCancelReason('');
    }
  };

  // 우선순위 변경 핸들러
  const handlePriorityChange = () => {
    if (selectedForPriority) {
      // 실제로는 onUpdate를 통해 우선순위 변경 처리
      alert(`우선순위가 변경되었습니다.\n\n출고번호: ${selectedForPriority.releaseNo || '-'}\n변경 우선순위: ${priorityOptions.find(p => p.value === newPriority)?.label}`);
      setShowPriorityModal(false);
      setSelectedForPriority(null);
    }
  };

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Truck}
        title="출하 목록"
        actions={
          <Button variant="primary" onClick={() => onNavigate('shipment-create')}>
            <Plus className="w-4 h-4" /> 출하 등록
          </Button>
        }
      />

      {/* 리포트 카드 - 핵심 지표 4개 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white border rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-gray-500">오늘 출하</p>
              <p className="text-2xl font-bold">{todayShipments}<span className="text-sm font-normal text-gray-500 ml-1">건</span></p>
            </div>
            <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
              <Calendar className="w-5 h-5 text-blue-600" />
            </div>
          </div>
        </div>
        <div className="bg-white border rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-gray-500">출고 대기</p>
              <p className="text-2xl font-bold">{shipments.filter(s => s.status === '출고대기' || s.status === '출고지시' || s.status === '출고예정').length}<span className="text-sm font-normal text-gray-500 ml-1">건</span></p>
            </div>
            <div className="w-10 h-10 rounded-full bg-yellow-100 flex items-center justify-center">
              <Clock className="w-5 h-5 text-yellow-600" />
            </div>
          </div>
        </div>
        <div className="bg-white border rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-gray-500">배송중</p>
              <p className="text-2xl font-bold">{shipments.filter(s => s.status === '배송중').length}<span className="text-sm font-normal text-gray-500 ml-1">건</span></p>
            </div>
            <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
              <Truck className="w-5 h-5 text-blue-600" />
            </div>
          </div>
        </div>
        <div className="bg-white border rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-gray-500">긴급 출하</p>
              <p className="text-2xl font-bold text-red-600">{urgentShipments}<span className="text-sm font-normal text-gray-500 ml-1">건</span></p>
            </div>
            <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
              <AlertCircle className="w-5 h-5 text-red-600" />
            </div>
          </div>
        </div>
      </div>

      {/* 출고불가 경고 */}
      {unpaidShipments > 0 && (
        <div className="flex items-center gap-2 p-4 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
          <AlertCircle className="w-5 h-5" />
          <span><strong>출고불가 {unpaidShipments}건</strong> - 입금확인 및 세금계산서 발행 완료 후 출고 진행이 가능합니다.</span>
        </div>
      )}

      {/* 검색 */}
      <div className="flex flex-wrap gap-4">
        <div className="flex-1">
          <SearchInput
            placeholder="분할번호, 로트번호, 발주처, 현장명 검색..."
            value={search}
            onChange={setSearch}
          />
        </div>
      </div>

      <TabFilter tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />

      {/* 출고일정 캘린더 뷰 */}
      {activeTab === 'calendar' ? (
        <ShipmentCalendarView
          shipments={shipments}
          calendarDate={calendarDate}
          setCalendarDate={setCalendarDate}
          selectedCalendarDate={selectedCalendarDate}
          setSelectedCalendarDate={setSelectedCalendarDate}
          onNavigate={onNavigate}
        />
      ) : (
        <div className="bg-white rounded-xl border overflow-hidden">
          {/* 선택 삭제 버튼 (2개 이상 선택 시) */}
          {selectedIds.length >= 2 && (
            <div className="px-4 py-3 bg-gray-50 border-b flex items-center justify-between">
              <span className="text-sm text-gray-600">
                {selectedIds.length}개 항목 선택됨
              </span>
              <button
                onClick={() => setShowDeleteModal(true)}
                className="px-4 py-2 bg-red-600 text-white text-sm rounded-lg hover:bg-red-700 flex items-center gap-2"
              >
                <Trash2 className="w-4 h-4" />
                선택 삭제({selectedIds.length})
              </button>
            </div>
          )}
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-3 py-3 text-center text-xs font-medium text-gray-500 w-12">
                  <input
                    type="checkbox"
                    className="rounded"
                    checked={filtered.length > 0 && selectedIds.length === filtered.length}
                    onChange={handleSelectAll}
                  />
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">번호</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">출고번호</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">로트번호</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">출고예정일</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">상태</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">거래처등급</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">출하가능</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">배차</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">발주처</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">현장명</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">담당자</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">입차/수령시간</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {filtered.map((shipment, idx) => {
                // 거래처 등급에 따른 출하가능 여부 판단
                // A등급: 무조건 출하가능, B등급: 입금확인 필요, C등급: 입금+세금계산서 필요
                const creditGrade = shipment.creditGrade || 'B';
                const canShip = creditGrade === 'A'
                  ? true
                  : creditGrade === 'B'
                    ? shipment.paymentConfirmed
                    : (shipment.paymentConfirmed && shipment.taxInvoiceIssued);
                const isSelected = selectedIds.includes(shipment.id);
                const isOnlySelected = selectedIds.length === 1 && isSelected;
                const priority = priorityOptions.find(p => p.value === shipment.shipmentPriority) || priorityOptions[2];
                // 수주 정보 가져오기
                const orderInfo = getOrderInfo(shipment.lotNo);

                return (
                  <tr
                    key={shipment.id}
                    className={`hover:bg-gray-50 cursor-pointer ${isSelected ? 'bg-blue-50' : ''} ${!canShip && shipment.status !== '배송완료' && !isSelected ? 'bg-red-50' : ''}`}
                    onClick={() => onNavigate('shipment-detail', shipment)}
                  >
                    <td className="px-3 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                      <input
                        type="checkbox"
                        className="rounded"
                        checked={isSelected}
                        onChange={(e) => handleSelectOne(shipment.id, e)}
                      />
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-500">{filtered.length - idx}</td>
                    <td className="px-4 py-3 text-sm font-mono text-blue-600">{shipment.releaseNo || '-'}</td>
                    <td className="px-4 py-3 text-sm font-mono text-gray-600">{shipment.lotNo}</td>
                    <td className="px-4 py-3 text-sm text-gray-900">{shipment.shipmentDate}</td>
                    <td className="px-4 py-3"><StatusBadge status={shipment.status} /></td>
                    {/* 거래처등급 */}
                    <td className="px-4 py-3 text-center">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${creditGrade === 'A' ? 'bg-green-100 text-green-700' :
                          creditGrade === 'B' ? 'bg-blue-100 text-blue-700' :
                            'bg-orange-100 text-orange-700'
                        }`}>
                        {creditGrade}등급
                      </span>
                    </td>
                    {/* 출하가능 */}
                    <td className="px-4 py-3 text-center">
                      {canShip || shipment.status === '배송완료'
                        ? <span className="text-xs px-2 py-0.5 rounded-full bg-green-100 text-green-700">가능</span>
                        : <span className="text-xs px-2 py-0.5 rounded-full bg-red-100 text-red-700">불가</span>
                      }
                    </td>
                    {/* 배차 */}
                    <td className="px-4 py-3 text-center">
                      <span className={`text-xs px-2 py-0.5 rounded-full ${shipment.dispatchType === '직접배차' ? 'bg-purple-100 text-purple-700' :
                          shipment.dispatchType === '상차' ? 'bg-blue-100 text-blue-700' :
                            shipment.dispatchType === '택배' ? 'bg-green-100 text-green-700' :
                              shipment.dispatchType === '화물' ? 'bg-orange-100 text-orange-700' :
                                'bg-gray-100 text-gray-700'
                        }`}>
                        {shipment.dispatchType || '미배정'}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-900">{shipment.customerName}</td>
                    <td className="px-4 py-3 text-sm text-gray-900 max-w-[150px] truncate">{shipment.siteName}</td>
                    <td className="px-4 py-3 text-sm text-center text-gray-900">{shipment.personInCharge || '-'}</td>
                    <td className="px-4 py-3 text-sm text-center text-gray-900">{shipment.arrivalTime || '-'}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {filtered.length === 0 && (
            <div className="text-center py-12 text-gray-500">
              <Truck className="w-12 h-12 mx-auto mb-3 text-gray-300" />
              <p>검색 결과가 없습니다.</p>
            </div>
          )}
        </div>
      )}

      {/* 삭제 확인 모달 */}
      {showDeleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4">
            <div className="p-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
                  <AlertTriangle className="w-6 h-6 text-red-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">삭제 확인</h3>
                  <p className="text-sm text-gray-500">선택한 항목을 삭제하시겠습니까?</p>
                </div>
              </div>
              <div className="bg-red-50 border border-red-200 rounded-lg p-3 mb-4">
                <p className="text-sm text-red-700">
                  <strong>{selectedIds.length}개</strong>의 출고가 삭제됩니다.
                  삭제된 데이터는 복구할 수 없습니다.
                </p>
              </div>
              <div className="flex justify-end gap-3">
                <button
                  onClick={() => setShowDeleteModal(false)}
                  className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  취소
                </button>
                <button
                  onClick={handleDeleteConfirm}
                  className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center gap-2"
                >
                  <Trash2 className="w-4 h-4" />
                  삭제
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 우선순위 변경 모달 */}
      {showPriorityModal && selectedForPriority && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4">
            <div className="p-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                  <AlertCircle className="w-6 h-6 text-blue-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">출고 우선순위 변경</h3>
                  <p className="text-sm text-gray-500">{selectedForPriority.splitNo}</p>
                </div>
              </div>
              <div className="space-y-3 mb-4">
                <p className="text-sm text-gray-600">출고 우선순위를 선택하세요:</p>
                <div className="grid grid-cols-2 gap-2">
                  {priorityOptions.map(p => (
                    <button
                      key={p.value}
                      onClick={() => setNewPriority(p.value)}
                      className={`px-4 py-3 rounded-lg border-2 transition-colors ${newPriority === p.value
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 hover:border-gray-300'
                        }`}
                    >
                      <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${p.color}`}>
                        {p.label}
                      </span>
                    </button>
                  ))}
                </div>
              </div>
              <div className="flex justify-end gap-3">
                <button
                  onClick={() => {
                    setShowPriorityModal(false);
                    setSelectedForPriority(null);
                  }}
                  className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  취소
                </button>
                <button
                  onClick={handlePriorityChange}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  변경
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 출고 취소 모달 */}
      {showCancelModal && selectedForCancel && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4">
            <div className="p-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-12 h-12 bg-orange-100 rounded-full flex items-center justify-center">
                  <X className="w-6 h-6 text-orange-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">출고 취소</h3>
                  <p className="text-sm text-gray-500">{selectedForCancel.splitNo}</p>
                </div>
              </div>
              <div className="space-y-4 mb-4">
                <div className="bg-orange-50 border border-orange-200 rounded-lg p-3">
                  <p className="text-sm text-orange-700">
                    <strong>{selectedForCancel.customerName}</strong> - {selectedForCancel.siteName}
                  </p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">취소 사유 선택</label>
                  <select
                    value={cancelReason}
                    onChange={(e) => setCancelReason(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
                  >
                    <option value="">취소 사유를 선택하세요</option>
                    {nonShipmentReasons.map(reason => (
                      <option key={reason} value={reason}>{reason}</option>
                    ))}
                  </select>
                </div>
                {cancelReason === '기타' && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">상세 사유</label>
                    <textarea
                      placeholder="취소 사유를 입력하세요"
                      rows={3}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
                    />
                  </div>
                )}
              </div>
              <div className="flex justify-end gap-3">
                <button
                  onClick={() => {
                    setShowCancelModal(false);
                    setSelectedForCancel(null);
                    setCancelReason('');
                  }}
                  className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  닫기
                </button>
                <button
                  onClick={handleCancelShipment}
                  disabled={!cancelReason}
                  className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  출고 취소
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 출고 등록 (수주 연동)
const ShipmentCreate = ({ orders, onNavigate, onBack, onSave }) => {
  const [formData, setFormData] = useState({
    orderNo: '',
    splitNo: '',
    shipmentDate: new Date().toISOString().split('T')[0],
    shipmentPriority: 3, // 기본 우선순위: 보통
    dispatchType: '상차',
    logisticsCompany: '',
    vehicleType: '',
    vehicleNo: '',
    driverName: '',
    driverPhone: '',
    scheduledArrival: '',
    shippingCost: 0,
    loadingWorker: '', // 상차담당자
    note: '',
  });

  const [selectedOrder, setSelectedOrder] = useState(null);
  const [selectedSplit, setSelectedSplit] = useState(null);

  // 유효성 검사 규칙
  const validationRules = {
    orderNo: { required: true, label: '로트번호', message: '로트(수주)를 선택해주세요.' },
    shipmentDate: { required: true, label: '출고예정일', message: '출고예정일을 선택해주세요.' },
  };
  const { errors, touched, hasError, getFieldError, validateForm, handleBlur, clearFieldError } = useFormValidation(formData, validationRules);

  // 수주 선택 시
  const handleOrderSelect = (orderNo) => {
    const order = orders.find(o => o.orderNo === orderNo);
    setSelectedOrder(order);
    setSelectedSplit(null);
    setFormData(prev => ({
      ...prev,
      orderNo,
      splitNo: '',
    }));
  };

  // 분할 선택 시
  const handleSplitSelect = (splitNo) => {
    const split = selectedOrder?.splits?.find(s => s.splitNo === splitNo);
    setSelectedSplit(split);
    setFormData(prev => ({
      ...prev,
      splitNo,
    }));
  };

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleSubmit = () => {
    // 유효성 검사
    if (!validateForm()) {
      return;
    }

    // 출하 조건 체크
    if (!selectedOrder) {
      alert('수주를 선택해주세요.');
      return;
    }

    // 생산완료 체크
    if (selectedOrder.status !== '생산완료' && selectedOrder.status !== '출하대기') {
      alert(`⚠️ 출하 불가\n\n현재 상태: ${selectedOrder.status}\n\n생산이 완료된 수주만 출하 등록이 가능합니다.`);
      return;
    }

    // B/C등급 입금확인 체크
    if ((selectedOrder.creditGrade === 'B' || selectedOrder.creditGrade === 'C') &&
      selectedOrder.paymentStatus !== '전액입금') {
      alert(`⚠️ 출하 불가 (입금 미확인)\n\n거래처 등급: ${selectedOrder.creditGrade}등급\n입금 상태: ${selectedOrder.paymentStatus || '미입금'}\n\n${selectedOrder.creditGrade}등급 거래처는 입금 확인 후 출하가 가능합니다.\n\n[수주관리 > 해당 수주 > 회계현황]에서\n입금 확인을 먼저 진행해주세요.`);
      return;
    }

    // C등급 경리승인 체크
    if (selectedOrder.creditGrade === 'C' && selectedOrder.accountingStatus !== '회계확인완료') {
      alert(`⚠️ 출하 불가 (경리승인 미완료)\n\n거래처 등급: C등급\n회계 상태: ${selectedOrder.accountingStatus || '미확인'}\n\nC등급 거래처는 경리 승인 후 출하가 가능합니다.\n\n[수주관리 > 해당 수주 > 회계현황]에서\n경리 승인을 먼저 진행해주세요.`);
      return;
    }

    // 품목 데이터 구성
    let items = [];
    if (selectedSplit && selectedOrder) {
      items = selectedOrder.items
        .filter(item => selectedSplit.itemIds.includes(item.id))
        .map(item => ({
          ...item,
          lotNo: null,
          arrivedAtLoadingArea: false,
          loadingChecked: false,
          accessoryLotNo: '',
        }));
    } else if (selectedOrder) {
      items = selectedOrder.items.map(item => ({
        ...item,
        lotNo: null,
        arrivedAtLoadingArea: false,
        loadingChecked: false,
        accessoryLotNo: '',
      }));
    }

    // splitNo (수주분할번호)
    const splitNo = selectedSplit
      ? selectedSplit.splitNo
      : `${formData.orderNo}-01`; // 분할 없으면 -01 자동 부여

    // releaseNo (출고번호) - 채번규칙: 날짜-P-순번 (예: 251217-P-01)
    const today = new Date();
    const yy = String(today.getFullYear()).slice(-2);
    const mm = String(today.getMonth() + 1).padStart(2, '0');
    const dd = String(today.getDate()).padStart(2, '0');
    const dateCode = `${yy}${mm}${dd}`;
    const seq = String(Math.floor(Math.random() * 99) + 1).padStart(2, '0'); // 실제로는 DB에서 순번 조회
    const releaseNo = `${dateCode}-P-${seq}`;

    const newShipment = {
      ...formData,
      id: Date.now(),
      releaseNo, // 출고번호 (채번규칙 적용)
      splitNo, // 수주분할번호
      lotNo: selectedOrder?.lotNo || selectedOrder?.orderNo,
      customerName: selectedOrder?.customerName,
      siteName: selectedOrder?.siteName,
      creditGrade: selectedOrder?.creditGrade,
      deliveryAddress: selectedOrder?.deliveryAddress,
      receiverName: selectedOrder?.receiverName,
      receiverPhone: selectedOrder?.receiverPhone,
      personInCharge: formData.loadingWorker, // 상차담당자 → 담당자 컬럼 매핑
      arrivalTime: formData.scheduledArrival, // 입차시간 → 입차/수령시간 컬럼 매핑
      status: '출고대기',
      paymentConfirmed: selectedOrder?.paymentStatus === '전액입금',
      taxInvoiceIssued: selectedOrder?.taxInvoiceIssued || false,
      items,
      changeHistory: [{
        id: 1,
        changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
        changeType: '출고등록',
        description: '출고 등록 완료',
        changedBy: '현재 사용자',
      }],
      loadingCompleted: false,
      cancelReason: null,
      canceledAt: null,
      canceledBy: null,
      createdAt: new Date().toISOString().split('T')[0],
      createdBy: '현재 사용자',
    };

    onSave?.(newShipment);
    alert(`✅ 출고가 등록되었습니다.\n\n출고번호: ${releaseNo}\n발주처: ${selectedOrder.customerName}\n현장: ${selectedOrder.siteName}`);
    onBack();
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button onClick={onBack} className="p-2 hover:bg-gray-100 rounded-lg">
            <ArrowLeft className="w-5 h-5 text-gray-500" />
          </button>
          <Truck className="w-6 h-6 text-green-500" />
          <h1 className="text-xl font-bold text-gray-900">출하 등록</h1>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={onBack}>취소</Button>
          <Button variant="primary" onClick={handleSubmit} disabled={!selectedOrder}>
            <Check className="w-4 h-4" /> 저장
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6">
        {/* 수주 선택 */}
        <Card title="수주 선택">
          <div className="space-y-4">
            <FormField label="로트번호" required error={hasError('orderNo')} errorMessage={getFieldError('orderNo')}>
              <select
                value={formData.orderNo}
                onChange={(e) => {
                  handleOrderSelect(e.target.value);
                  clearFieldError('orderNo');
                }}
                onBlur={() => handleBlur('orderNo')}
                className={getInputClassName(hasError('orderNo'))}
              >
                <option value="">로트 선택</option>
                {orders.filter(o => o.status === '생산완료' || o.status === '출하대기').map(order => (
                  <option key={order.id} value={order.orderNo}>
                    {order.orderNo} - {order.customerName} / {order.siteName}
                  </option>
                ))}
              </select>
            </FormField>

            {selectedOrder?.splits?.length > 0 && (
              <FormField label="분할 선택">
                <select
                  value={formData.splitNo}
                  onChange={(e) => handleSplitSelect(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">전체 출고</option>
                  {selectedOrder.splits.map(split => (
                    <option key={split.id} value={split.splitNo}>
                      {split.splitNo} ({split.dueDate}) - {split.shipmentStatus}
                    </option>
                  ))}
                </select>
              </FormField>
            )}

            {selectedOrder && (
              <div className="p-4 bg-gray-50 rounded-lg space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">발주처</span>
                  <span className="font-medium">{selectedOrder.customerName}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">현장명</span>
                  <span className="font-medium">{selectedOrder.siteName}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">배송주소</span>
                  <span className="font-medium">{selectedOrder.deliveryAddress}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">결제상태</span>
                  <StatusBadge status={selectedOrder.paymentStatus} />
                </div>
              </div>
            )}
          </div>
        </Card>

        {/* 출고 정보 */}
        <Card title="출고 정보">
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <FormField label="출고예정일" required error={hasError('shipmentDate')} errorMessage={getFieldError('shipmentDate')}>
                <input
                  type="date"
                  value={formData.shipmentDate}
                  onChange={(e) => {
                    handleChange('shipmentDate', e.target.value);
                    clearFieldError('shipmentDate');
                  }}
                  onBlur={() => handleBlur('shipmentDate')}
                  className={getInputClassName(hasError('shipmentDate'))}
                />
              </FormField>

              <FormField label="출고 우선순위" required>
                <select
                  value={formData.shipmentPriority}
                  onChange={(e) => handleChange('shipmentPriority', parseInt(e.target.value))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  {priorityOptions.map(p => (
                    <option key={p.value} value={p.value}>{p.label}</option>
                  ))}
                </select>
              </FormField>
            </div>

            <FormField label="배송방식" required>
              <select
                value={formData.dispatchType}
                onChange={(e) => handleChange('dispatchType', e.target.value)}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {dispatchTypes.map(type => (
                  <option key={type} value={type}>{type}</option>
                ))}
              </select>
            </FormField>

            {/* 직접배차 (발주처 차량) 옵션 */}
            {formData.dispatchType === '직접배차' && (
              <div className="p-4 bg-purple-50 rounded-lg space-y-4">
                <p className="text-sm text-purple-700 font-medium">직접배차 (발주처 차량)</p>
                <FormField label="입차예정시간">
                  <input
                    type="datetime-local"
                    value={formData.scheduledArrival}
                    onChange={(e) => handleChange('scheduledArrival', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </FormField>
                <div className="text-xs text-purple-600">
                  발주처와 휴대폰/카톡으로 입차시간 조율 후 입력하세요.
                </div>
              </div>
            )}

            {/* 상차 (물류업체) 옵션 */}
            {formData.dispatchType === '상차' && (
              <div className="p-4 bg-blue-50 rounded-lg space-y-4">
                <p className="text-sm text-blue-700 font-medium">상차 (물류업체)</p>
                <div className="grid grid-cols-2 gap-4">
                  <FormField label="물류사">
                    <select
                      value={formData.logisticsCompany}
                      onChange={(e) => handleChange('logisticsCompany', e.target.value)}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="">선택하세요</option>
                      {logisticsCompanies.map(company => (
                        <option key={company} value={company}>{company}</option>
                      ))}
                    </select>
                  </FormField>
                  <FormField label="차량 톤수 (물량)">
                    <select
                      value={formData.vehicleType}
                      onChange={(e) => handleChange('vehicleType', e.target.value)}
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="">선택하세요</option>
                      {vehicleTypes.map(type => (
                        <option key={type} value={type}>{type}</option>
                      ))}
                    </select>
                  </FormField>
                </div>
                <FormField label="상차시간 (입차예정)">
                  <input
                    type="datetime-local"
                    value={formData.scheduledArrival}
                    onChange={(e) => handleChange('scheduledArrival', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </FormField>
                <div className="text-xs text-blue-600">
                  물류업체와 입차시간 확정 후 입력하세요.
                </div>
              </div>
            )}

            {/* 택배/화물/직접배송 옵션 */}
            {(formData.dispatchType === '택배' || formData.dispatchType === '화물' || formData.dispatchType === '직접배송') && (
              <div className="p-4 bg-green-50 rounded-lg space-y-4">
                <p className="text-sm text-green-700 font-medium">{formData.dispatchType}</p>
                <div className="grid grid-cols-2 gap-4">
                  <FormField label="운송담당자">
                    <input
                      type="text"
                      value={formData.driverName}
                      onChange={(e) => handleChange('driverName', e.target.value)}
                      placeholder="담당자명"
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </FormField>
                  <FormField label="담당자 연락처">
                    <input
                      type="text"
                      value={formData.driverPhone}
                      onChange={(e) => handleChange('driverPhone', e.target.value)}
                      placeholder="010-0000-0000"
                      className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </FormField>
                </div>
                <FormField label="운송예정시간">
                  <input
                    type="datetime-local"
                    value={formData.scheduledArrival}
                    onChange={(e) => handleChange('scheduledArrival', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </FormField>
              </div>
            )}

            <FormField label="상차담당자">
              <input
                type="text"
                value={formData.loadingWorker}
                onChange={(e) => handleChange('loadingWorker', e.target.value)}
                placeholder="상차 작업 담당자명"
                className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </FormField>

            <FormField label="비고">
              <textarea
                value={formData.note}
                onChange={(e) => handleChange('note', e.target.value)}
                placeholder="특이사항 입력"
                rows={3}
                className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </FormField>
          </div>
        </Card>

        {/* 출하 품목 */}
        {selectedOrder && (
          <Card title="출하 품목">
            <table className="w-full">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">No</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목코드</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">층</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">부호</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">규격</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">수량</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {(selectedSplit
                  ? selectedOrder.items.filter(item => selectedSplit.itemIds.includes(item.id))
                  : selectedOrder.items
                ).map((item, idx) => (
                  <tr key={item.id}>
                    <td className="px-4 py-3 text-sm text-gray-500">{idx + 1}</td>
                    <td className="px-4 py-3 text-sm font-mono">{item.productCode}</td>
                    <td className="px-4 py-3 text-sm">{item.productName}</td>
                    <td className="px-4 py-3 text-sm">{item.floor}</td>
                    <td className="px-4 py-3 text-sm">{item.location}</td>
                    <td className="px-4 py-3 text-sm">{item.spec}</td>
                    <td className="px-4 py-3 text-sm text-right font-medium">{item.qty}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        )}
      </div>
    </div>
  );
};

// 출하 상세
const ShipmentDetail = ({ shipment, shipments, orders = [], onNavigate, onBack, onUpdate }) => {
  const [showPriorityModal, setShowPriorityModal] = useState(false);
  const [showCancelModal, setShowCancelModal] = useState(false);
  const [cancelReason, setCancelReason] = useState('');
  const [cancelReasonDetail, setCancelReasonDetail] = useState('');
  const [showShipmentDocModal, setShowShipmentDocModal] = useState(false);
  const [showDeliveryConfirmationModal, setShowDeliveryConfirmationModal] = useState(false);
  const [showTransactionStatementModal, setShowTransactionStatementModal] = useState(false);

  // 연결된 수주 정보 조회
  const linkedOrder = orders.find(o => o.lotNo === shipment.lotNo);

  // 동일 로트의 다른 출하 조회
  const relatedShipments = shipments?.filter(s => s.lotNo === shipment.lotNo) || [];

  // 상차 체크 핸들러
  const handleLoadingCheck = (itemId, field, value) => {
    const updatedItems = shipment.items.map(item =>
      item.id === itemId ? { ...item, [field]: value } : item
    );
    onUpdate?.({ ...shipment, items: updatedItems });
  };

  // 상차 완료 처리
  const handleLoadingComplete = () => {
    const allChecked = shipment.items.every(item => item.loadingChecked);
    if (!allChecked) {
      alert('모든 품목의 상차를 확인해주세요.');
      return;
    }
    onUpdate?.({
      ...shipment,
      loadingCompleted: true,
      loadingCompletedAt: new Date().toISOString(),
      loadingWorker: '현재 사용자',
      status: '상차완료',
    });
  };

  // 상태 변경
  const handleStatusChange = (newStatus) => {
    const history = {
      id: (shipment.changeHistory?.length || 0) + 1,
      changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
      changeType: '상태 변경',
      beforeValue: shipment.status,
      afterValue: newStatus,
      reason: '',
      changedBy: '현재 사용자',
    };
    onUpdate?.({
      ...shipment,
      status: newStatus,
      changeHistory: [...(shipment.changeHistory || []), history],
      ...(newStatus === '배송완료' ? { completedAt: new Date().toISOString() } : {}),
    });
  };

  // 거래처 등급에 따른 출하가능 여부 판단
  // A등급: 무조건 출하가능, B등급: 입금확인 필요, C등급: 입금+세금계산서 필요
  const creditGrade = shipment.creditGrade || 'B';
  const canShip = creditGrade === 'A'
    ? true
    : creditGrade === 'B'
      ? shipment.paymentConfirmed
      : (shipment.paymentConfirmed && shipment.taxInvoiceIssued);

  // 우선순위 정보
  const currentPriority = priorityOptions.find(p => p.value === shipment.shipmentPriority) || priorityOptions[2];

  // 우선순위 변경 핸들러
  const handlePriorityChange = (newPriority) => {
    const history = {
      id: (shipment.changeHistory?.length || 0) + 1,
      changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
      changeType: '우선순위 변경',
      beforeValue: currentPriority.label,
      afterValue: priorityOptions.find(p => p.value === newPriority)?.label,
      reason: '',
      changedBy: '현재 사용자',
    };
    onUpdate?.({
      ...shipment,
      shipmentPriority: newPriority,
      changeHistory: [...(shipment.changeHistory || []), history],
    });
    setShowPriorityModal(false);
  };

  // 출고 취소 핸들러
  const handleCancelShipment = () => {
    if (!cancelReason) {
      alert('취소 사유를 선택해주세요.');
      return;
    }
    const history = {
      id: (shipment.changeHistory?.length || 0) + 1,
      changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
      changeType: '출고 취소',
      beforeValue: shipment.status,
      afterValue: '출고취소',
      reason: cancelReason + (cancelReasonDetail ? ` - ${cancelReasonDetail}` : ''),
      changedBy: '현재 사용자',
    };
    onUpdate?.({
      ...shipment,
      status: '출고취소',
      cancelReason: cancelReason,
      cancelReasonDetail: cancelReasonDetail,
      cancelledAt: new Date().toISOString(),
      changeHistory: [...(shipment.changeHistory || []), history],
    });
    setShowCancelModal(false);
  };

  return (
    <div className="space-y-6">
      {/* 상단 헤더 - 타이틀 위, 버튼 아래 */}
      <div className="space-y-3">
        {/* 타이틀 영역 */}
        <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
          <Truck className="w-6 h-6 text-blue-500" />
          출하 상세
        </h1>
        {/* 버튼 영역 - 좌측: 문서버튼 / 우측: 액션버튼 */}
        <div className="flex items-center justify-between">
          {/* 좌측: 문서 버튼 */}
          <div className="flex items-center gap-2">
            <button onClick={() => setShowShipmentDocModal(true)} className="flex items-center gap-1 px-3 py-1.5 text-sm border border-gray-300 rounded hover:bg-gray-50">
              <Printer className="w-4 h-4" /> 출고증
            </button>
            <button onClick={() => setShowTransactionStatementModal(true)} className="flex items-center gap-1 px-3 py-1.5 text-sm border border-gray-300 rounded hover:bg-gray-50">
              <FileText className="w-4 h-4" /> 거래명세서
            </button>
            <button onClick={() => setShowDeliveryConfirmationModal(true)} className="flex items-center gap-1 px-3 py-1.5 text-sm border border-gray-300 rounded hover:bg-gray-50">
              <FileText className="w-4 h-4" /> 납품확인서
            </button>
          </div>
          {/* 우측: 액션 버튼 */}
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={onBack}>목록</Button>
            {shipment.status !== '출고취소' && shipment.status !== '배송완료' && (
              <Button variant="outline" className="text-red-600 border-red-300 hover:bg-red-50" onClick={() => setShowCancelModal(true)}>
                <X className="w-4 h-4" /> 출고취소
              </Button>
            )}
            <Button variant="outline" onClick={() => onNavigate('shipment-edit', shipment)}>
              <Edit className="w-4 h-4" /> 수정
            </Button>
            {shipment.status === '출고대기' && (
              <Button variant="primary" onClick={() => handleStatusChange('출고준비')}>
                <Package className="w-4 h-4" /> 출고준비
              </Button>
            )}
            {shipment.status === '출고준비' && (
              <Button variant="primary" onClick={() => handleStatusChange('상차대기')}>
                <Truck className="w-4 h-4" /> 상차대기
              </Button>
            )}
            {shipment.status === '상차대기' && shipment.loadingCompleted && canShip && (
              <Button variant="primary" onClick={() => handleStatusChange('배송중')}>
                <Truck className="w-4 h-4" /> 배송시작
              </Button>
            )}
            {shipment.status === '배송중' && (
              <Button variant="success" onClick={() => handleStatusChange('배송완료')}>
                <CheckCircle className="w-4 h-4" /> 배송완료
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* 출고불가 경고 */}
      {!canShip && shipment.status !== '배송완료' && shipment.status !== '출고취소' && (
        <div className="flex items-center gap-2 p-4 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
          <AlertCircle className="w-5 h-5" />
          <span>
            <strong>출고 불가</strong> -
            {!shipment.paymentConfirmed && ' 입금확인'}
            {!shipment.paymentConfirmed && !shipment.taxInvoiceIssued && ' 및'}
            {!shipment.taxInvoiceIssued && ' 세금계산서 발행'}
            이 완료되어야 출고 진행이 가능합니다. 회계팀에 확인 요청하세요.
          </span>
        </div>
      )}

      {/* 출고 취소 상태 표시 */}
      {shipment.status === '출고취소' && (
        <div className="flex items-center gap-2 p-4 bg-gray-100 border border-gray-300 rounded-lg text-sm text-gray-700">
          <X className="w-5 h-5" />
          <span>
            <strong>출고 취소됨</strong> -
            사유: {shipment.cancelReason || '미입력'}
            {shipment.cancelReasonDetail && ` (${shipment.cancelReasonDetail})`}
          </span>
        </div>
      )}

      {/* 기본정보 섹션 */}
      <div className="grid grid-cols-1 gap-6">
        <Card title="출고 정보">
          <div className="grid grid-cols-2 gap-4">
            <InfoRow label="출고번호" value={shipment.releaseNo || '-'} />
            <InfoRow label="출고예정일" value={shipment.shipmentDate} />
            <InfoRow label="로트번호" value={
              <button className="text-blue-600 hover:underline font-mono">{shipment.lotNo}</button>
            } />
            <InfoRow label="출고상태" value={<StatusBadge status={shipment.status} />} />
            <InfoRow label="출고 우선순위" value={
              <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${currentPriority.color}`}>
                {currentPriority.label}
              </span>
            } />
            <InfoRow label="배송방식" value={
              <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium
                  ${shipment.dispatchType === '직접배차' ? 'bg-purple-100 text-purple-700' : ''}
                  ${shipment.dispatchType === '상차' ? 'bg-blue-100 text-blue-700' : ''}
                  ${shipment.dispatchType === '택배' ? 'bg-green-100 text-green-700' : ''}
                  ${shipment.dispatchType === '화물' ? 'bg-orange-100 text-orange-700' : ''}
                  ${shipment.dispatchType === '직접배송' ? 'bg-gray-100 text-gray-700' : ''}
                `}>
                {shipment.dispatchType}
              </span>
            } />
            <InfoRow label="입금확인" value={
              shipment.paymentConfirmed
                ? <span className="text-green-600 font-medium">✓ 확인됨</span>
                : <span className="text-gray-400">- 미확인</span>
            } />
            <InfoRow label="세금계산서" value={
              shipment.taxInvoiceIssued
                ? <span className="text-green-600 font-medium">✓ 발행됨</span>
                : <span className="text-gray-400">- 미발행</span>
            } />
            <InfoRow label="거래처 등급" value={
              <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium
                  ${creditGrade === 'A' ? 'bg-green-100 text-green-700' : ''}
                  ${creditGrade === 'B' ? 'bg-blue-100 text-blue-700' : ''}
                  ${creditGrade === 'C' ? 'bg-orange-100 text-orange-700' : ''}
                `}>
                {creditGrade}등급
              </span>
            } />
            <InfoRow label="출하가능" value={
              canShip
                ? <span className="text-green-600 font-medium">✓ 가능</span>
                : <span className="text-red-500 font-medium">✗ 불가 (조건 미충족)</span>
            } />
            <InfoRow label="상차담당자" value={shipment.loadingWorker || '미배정'} />
            <InfoRow label="상차완료" value={
              shipment.loadingCompleted
                ? <span className="text-green-600 font-medium">✓ 완료 {shipment.loadingCompletedAt && `(${new Date(shipment.loadingCompletedAt).toLocaleDateString()})`}</span>
                : <span className="text-gray-400">- 미완료</span>
            } />
            <InfoRow label="등록자" value={shipment.createdBy} />
          </div>
        </Card>

        <Card title="발주처/배송 정보">
          <div className="grid grid-cols-2 gap-4">
            <InfoRow label="발주처" value={shipment.customerName} />
            <InfoRow label="현장명" value={shipment.siteName} />
            <div className="col-span-2">
              <InfoRow label="배송주소" value={shipment.deliveryAddress} />
            </div>
            <InfoRow label="인수자" value={shipment.receiverName} />
            <InfoRow label="연락처" value={shipment.receiverPhone} />
          </div>
        </Card>

        <Card title="출고 품목">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">No</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목코드</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">층/부호</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">규격</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">수량</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">LOT번호</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {shipment.items.map((item, idx) => (
                <tr key={item.id}>
                  <td className="px-4 py-3 text-sm text-gray-500">{idx + 1}</td>
                  <td className="px-4 py-3 text-sm font-mono">{item.productCode}</td>
                  <td className="px-4 py-3 text-sm">{item.productName}</td>
                  <td className="px-4 py-3 text-sm">{item.floor}/{item.location}</td>
                  <td className="px-4 py-3 text-sm">{item.spec}</td>
                  <td className="px-4 py-3 text-sm text-right font-medium">{item.qty}</td>
                  <td className="px-4 py-3 text-sm font-mono text-gray-500">{item.lotNo || '-'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>

      {/* 배차정보 섹션 */}
      <div className="grid grid-cols-1 gap-6">
        <Card title="배차 정보">
          <div className="grid grid-cols-2 gap-4">
            <InfoRow label="배송방식" value={
              <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium
                  ${shipment.dispatchType === '직접배차' ? 'bg-purple-100 text-purple-700' : ''}
                  ${shipment.dispatchType === '상차' ? 'bg-blue-100 text-blue-700' : ''}
                  ${shipment.dispatchType === '택배' ? 'bg-green-100 text-green-700' : ''}
                  ${shipment.dispatchType === '화물' ? 'bg-orange-100 text-orange-700' : ''}
                  ${shipment.dispatchType === '직접배송' ? 'bg-gray-100 text-gray-700' : ''}
                `}>
                {shipment.dispatchType}
              </span>
            } />
            <InfoRow label="물류사" value={shipment.logisticsCompany || '-'} />
            <InfoRow label="차량 톤수" value={shipment.vehicleType || '-'} />
            <InfoRow label="운송비" value={shipment.shippingCost ? `${shipment.shippingCost.toLocaleString()}원` : '-'} />
          </div>
        </Card>

        <Card title="차량/운전자 정보">
          <div className="grid grid-cols-2 gap-4">
            <InfoRow label="차량번호" value={shipment.vehicleNo || '미배정'} />
            <InfoRow label="운전자" value={shipment.driverName || '미배정'} />
            <InfoRow label="운전자 연락처" value={shipment.driverPhone || '-'} />
            {shipment.trackingNo && (
              <InfoRow label="운송장번호" value={shipment.trackingNo} />
            )}
          </div>
        </Card>

        {shipment.note && (
          <Card title="비고">
            <p className="text-sm text-gray-700 whitespace-pre-wrap">{shipment.note}</p>
          </Card>
        )}
      </div>

      {/* 우선순위 변경 모달 */}
      {showPriorityModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg w-96 max-h-[80vh] overflow-y-auto">
            <div className="p-4 border-b flex items-center justify-between">
              <h3 className="font-medium">우선순위 변경</h3>
              <button onClick={() => setShowPriorityModal(false)} className="p-1 hover:bg-gray-100 rounded">
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>
            <div className="p-4 space-y-3">
              <p className="text-sm text-gray-500 mb-4">출고 우선순위를 선택하세요.</p>
              {priorityOptions.map(p => (
                <button
                  key={p.value}
                  onClick={() => handlePriorityChange(p.value)}
                  className={`w-full p-3 rounded-lg border-2 text-left flex items-center justify-between
                    ${shipment.shipmentPriority === p.value ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'}`}
                >
                  <span className={`inline-flex items-center px-2 py-1 rounded text-sm font-medium ${p.color}`}>
                    {p.label}
                  </span>
                  {shipment.shipmentPriority === p.value && (
                    <CheckCircle className="w-5 h-5 text-blue-500" />
                  )}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* 출고 취소 모달 */}
      {showCancelModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg w-[500px] max-h-[80vh] overflow-y-auto">
            <div className="p-4 border-b flex items-center justify-between">
              <h3 className="font-medium text-red-600">출고 취소</h3>
              <button onClick={() => setShowCancelModal(false)} className="p-1 hover:bg-gray-100 rounded">
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
                <AlertCircle className="w-4 h-4 inline mr-2" />
                출고를 취소하면 해당 건은 미출고 처리됩니다. 취소 사유를 반드시 입력해주세요.
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700">취소 사유 *</label>
                <select
                  value={cancelReason}
                  onChange={(e) => setCancelReason(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">선택하세요</option>
                  {nonShipmentReasons.map(reason => (
                    <option key={reason} value={reason}>{reason}</option>
                  ))}
                </select>
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700">상세 사유</label>
                <textarea
                  value={cancelReasonDetail}
                  onChange={(e) => setCancelReasonDetail(e.target.value)}
                  placeholder="상세 사유를 입력하세요"
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button variant="outline" onClick={() => setShowCancelModal(false)}>취소</Button>
                <Button
                  variant="primary"
                  className="bg-red-600 hover:bg-red-700"
                  onClick={handleCancelShipment}
                  disabled={!cancelReason}
                >
                  출고 취소 확정
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 출고증 출력 모달 - 문서양식관리 양식 연동 */}
      {showShipmentDocModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl max-w-[90vw] max-h-[90vh] overflow-auto">
            <div className="sticky top-0 bg-white border-b px-6 py-4 flex items-center justify-between">
              <h3 className="text-lg font-bold">출고증 미리보기</h3>
              <div className="flex items-center gap-2">
                <Button variant="primary" onClick={() => window.print()}>
                  <Printer className="w-4 h-4" /> 인쇄
                </Button>
                <button
                  onClick={() => setShowShipmentDocModal(false)}
                  className="p-2 hover:bg-gray-100 rounded-lg"
                >
                  <X className="w-5 h-5 text-gray-500" />
                </button>
              </div>
            </div>
            <div className="p-6 bg-gray-100">
              {/* 출고증 양식 - 문서양식관리 TS 양식 */}
              <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '8mm', fontSize: '10px' }}>
                {/* 헤더 - KD 로고 + 출고증 + 결재란 */}
                <table className="w-full border-collapse mb-2" style={{ border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td rowSpan="4" className="text-center align-middle p-2" style={{ width: '100px', borderRight: '1px solid black' }}>
                        <div className="text-2xl font-black text-blue-700">KD</div>
                        <div className="text-xs font-bold">경동기업</div>
                        <div style={{ fontSize: '8px' }} className="text-gray-500">KYUNGDONG COMPANY</div>
                      </td>
                      <td rowSpan="2" className="text-center align-middle" style={{ width: '45%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                        <div className="text-2xl font-black tracking-widest">출 고 증</div>
                      </td>
                      <td rowSpan="4" className="text-center align-middle" style={{ width: '30px', borderRight: '1px solid black' }}>
                        <div className="text-xs font-bold">결</div>
                        <div className="text-xs font-bold mt-4">재</div>
                      </td>
                      <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>작성</td>
                      <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검토</td>
                      <td className="text-center text-xs font-semibold py-1" style={{ width: '60px', borderBottom: '1px solid black' }}>승인</td>
                    </tr>
                    <tr>
                      <td className="text-center py-1" style={{ height: '50px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>
                        <div className="text-base font-bold text-blue-600">{shipment.createdBy || ''}</div>
                        <div className="text-xs text-gray-500 mt-1">{shipment.shipmentDate?.slice(5, 10) || ''}</div>
                      </td>
                      <td className="text-center py-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                      <td className="text-center py-1" style={{ borderBottom: '1px solid black' }}></td>
                    </tr>
                    <tr>
                      <td rowSpan="2" className="text-center py-2 font-bold align-middle" style={{ borderRight: '1px solid black', backgroundColor: '#E0F2FE' }}>
                        출하 관리
                      </td>
                      <td className="text-center py-1 text-xs" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>판매/전진</td>
                      <td className="text-center py-1 text-xs" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>출하</td>
                      <td className="text-center py-1 text-xs font-semibold" style={{ borderBottom: '1px solid black' }}>생산관리</td>
                    </tr>
                  </tbody>
                </table>

                {/* LOT번호 */}
                <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td className="text-center bg-yellow-300 py-1.5 font-bold" style={{ width: '100px', borderRight: '1px solid black' }}>제품 LOT NO.</td>
                      <td className="px-2 py-1.5 font-bold">{shipment.lotNo}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 전화 / 팩스 / 이메일 */}
                <div className="text-xs text-center mb-2 text-gray-600">
                  전화 : 031-938-5130 | 팩스 : 02-6911-6315 | 이메일 : kd5130@naver.com
                </div>

                {/* 상품명 / 제품명 / 인정번호 */}
                <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '70px', borderRight: '1px solid black' }}>상 품 명</td>
                      <td className="px-2 py-1.5 font-bold" style={{ borderRight: '1px solid black' }}>{linkedOrder?.productName || '국민방화스크린플러스셔터'}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '60px', borderRight: '1px solid black' }}>제품명</td>
                      <td className="px-2 py-1.5 font-bold" style={{ width: '80px', borderRight: '1px solid black' }}>{shipment.productCode || 'KWE01'}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '60px', borderRight: '1px solid black' }}>인정번호</td>
                      <td className="px-2 py-1.5" style={{ width: '120px' }}>{shipment.certNo || 'FDS-OTS23-0117-4'}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 신청업체 / 신청내용 / 납품정보 - 3단 구조 */}
                <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '40%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>신 청 업 체</td>
                      <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '30%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>신 청 내 용</td>
                      <td colSpan="2" className="text-center font-bold py-1 bg-gray-200 text-sm" style={{ width: '30%', borderBottom: '1px solid black' }}>납 품 정 보</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 일</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{linkedOrder?.orderDate || shipment.orderDate || '-'}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>현 장 명</td>
                      <td className="px-2 py-1.5 font-bold text-yellow-600" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shipment.siteName}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ width: '70px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>인수담당자</td>
                      <td className="px-2 py-1.5 font-bold" style={{ borderBottom: '1px solid black' }}>{shipment.receiverName || '-'}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 처</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shipment.customerName}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>납기요청일</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{linkedOrder?.dueDate || shipment.dueDate || '-'}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>인수자연락처</td>
                      <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}>{shipment.receiverPhone || '-'}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발주 담당자</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{linkedOrder?.contactPerson || '-'}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>출 고 일</td>
                      <td className="px-2 py-1.5 font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shipment.shipmentDate}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>배 송 방 법</td>
                      <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}>
                        <span className={shipment.dispatchType === '상차' ? 'font-bold' : ''}>{shipment.dispatchType}</span>
                        <span className="ml-4">{shipment.paymentMethod || '선불'}</span>
                      </td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>담당자 연락처</td>
                      <td className="px-2 py-1.5" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{linkedOrder?.contactPhone || '-'}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>셔터총수량</td>
                      <td className="px-2 py-1.5 font-bold text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shipment.items?.reduce((sum, item) => sum + item.qty, 0) || 0}</td>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>개소</td>
                      <td className="px-2 py-1.5" style={{ borderBottom: '1px solid black' }}></td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-1.5 font-semibold" style={{ borderRight: '1px solid black' }}>배송지 주소</td>
                      <td className="px-2 py-1.5" colSpan="5">{shipment.deliveryAddress}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 1. 부자재 - 감기샤프트, 각파이프, 앵글 */}
                <div className="text-sm font-bold mb-1">1. 부자재 - 감기샤프트, 각파이프, 앵글</div>
                <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td className="align-top p-1" style={{ borderRight: '1px solid black', width: '25%' }}>
                        <div className="text-xs font-bold mb-1">감기샤프트</div>
                        <div className="text-xs text-gray-600 mb-1">4인치</div>
                        <table className="w-full text-xs">
                          <tbody>
                            <tr><td>L : 3,000</td><td className="text-right font-bold text-red-600">{shipment.items?.length > 0 ? Math.ceil(shipment.items.length * 0.5) : 0}</td></tr>
                            <tr><td>L : 4,500</td><td className="text-right font-bold text-red-600">{shipment.items?.length > 0 ? Math.ceil(shipment.items.length * 0.3) : 0}</td></tr>
                          </tbody>
                        </table>
                      </td>
                      <td className="align-top p-1 text-center font-bold text-lg" style={{ borderRight: '1px solid black', width: '8%' }}>
                        <div className="text-xs text-gray-500 mb-1">수량</div>
                        <div className="text-red-600">{shipment.items?.reduce((sum, item) => sum + item.qty, 0) || 0}</div>
                      </td>
                      <td className="align-top p-1" style={{ borderRight: '1px solid black', width: '25%' }}>
                        <div className="text-xs font-bold mb-1">감기샤프트</div>
                        <div className="text-xs text-gray-600 mb-1">5인치</div>
                        <table className="w-full text-xs">
                          <tbody>
                            <tr><td>L : 6,000</td><td className="text-right font-bold text-red-600">{shipment.items?.length > 2 ? Math.ceil(shipment.items.length * 0.2) : 0}</td></tr>
                            <tr><td>L : 7,000</td><td className="text-right font-bold text-red-600">{shipment.items?.length > 3 ? 2 : 0}</td></tr>
                          </tbody>
                        </table>
                      </td>
                      <td className="align-top p-1 text-center font-bold text-lg" style={{ borderRight: '1px solid black', width: '8%' }}>
                        <div className="text-xs text-gray-500 mb-1">수량</div>
                      </td>
                      <td className="align-top p-1" style={{ borderRight: '1px solid black', width: '25%' }}>
                        <div className="text-xs font-bold mb-1">각파이프</div>
                        <div className="text-xs text-gray-600">(50*30*1.4T)</div>
                        <div className="text-xs mt-1">L : 6,000</div>
                      </td>
                      <td className="align-top p-1 text-center font-bold text-lg" style={{ width: '9%' }}>
                        <div className="text-xs text-gray-500 mb-1">수량</div>
                        <div className="text-red-600">{(shipment.items?.reduce((sum, item) => sum + item.qty, 0) || 0) * 5}</div>
                      </td>
                    </tr>
                    <tr style={{ borderTop: '1px solid black' }}>
                      <td colSpan="4" className="p-1 text-xs text-gray-600">
                        ※ 별도 추가사항 - 부자재
                      </td>
                      <td className="align-top p-1" style={{ borderRight: '1px solid black' }}>
                        <div className="text-xs font-bold mb-1">앵글</div>
                        <div className="text-xs text-gray-600">(40*40*3T)</div>
                      </td>
                      <td className="align-top p-1 text-center font-bold text-lg">
                        <div className="text-xs text-gray-500 mb-1">수량</div>
                        <div className="text-red-600">{(shipment.items?.reduce((sum, item) => sum + item.qty, 0) || 0) * 4}</div>
                      </td>
                    </tr>
                  </tbody>
                </table>

                {/* 2. 모터 */}
                <div className="text-sm font-bold mb-1">2. 모터</div>
                <table className="w-full border-collapse mb-2" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td colSpan="3" className="p-1" style={{ borderRight: '1px solid black', borderBottom: '1px solid black', width: '50%' }}>
                        <div className="text-xs font-bold mb-2">2-1. 모터(220V 단상)</div>
                        <table className="w-full text-xs">
                          <thead>
                            <tr className="bg-gray-100">
                              <th className="py-1 border-b border-gray-300 text-left px-1">모터 용량</th>
                              <th className="py-1 border-b border-gray-300 text-center" style={{ width: '50px' }}>수량</th>
                              <th className="py-1 border-b border-gray-300 text-center">입고 LOT NO.</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr><td className="py-1 px-1">KD-150K</td><td className="text-center font-bold text-red-600">{shipment.items?.length >= 3 ? Math.ceil(shipment.items.length * 0.3) : 0}</td><td></td></tr>
                            <tr><td className="py-1 px-1">KD-300K</td><td className="text-center font-bold text-red-600">{shipment.items?.length >= 3 ? Math.ceil(shipment.items.length * 0.5) : 0}</td><td></td></tr>
                          </tbody>
                        </table>
                      </td>
                      <td colSpan="3" className="p-1" style={{ borderBottom: '1px solid black' }}>
                        <div className="text-xs font-bold mb-2">2-2. 모터(380V 삼상)</div>
                        <table className="w-full text-xs">
                          <thead>
                            <tr className="bg-gray-100">
                              <th className="py-1 border-b border-gray-300 text-left px-1">모터 용량</th>
                              <th className="py-1 border-b border-gray-300 text-center" style={{ width: '50px' }}>수량</th>
                              <th className="py-1 border-b border-gray-300 text-center">입고 LOT NO.</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr><td className="py-1 px-1">KD-300K</td><td className="text-center font-bold text-red-600">{shipment.items?.length >= 5 ? Math.ceil(shipment.items.length * 0.2) : 0}</td><td></td></tr>
                            <tr><td className="py-1 px-1">KD-400K</td><td className="text-center"></td><td></td></tr>
                          </tbody>
                        </table>
                      </td>
                    </tr>
                    <tr>
                      <td colSpan="3" className="p-1" style={{ borderRight: '1px solid black' }}>
                        <div className="text-xs font-bold mb-2">2-3. 브라켓트</div>
                        <table className="w-full text-xs">
                          <tbody>
                            <tr><td className="py-1 px-1">380*180 (2-4")</td><td className="text-center font-bold text-red-600" style={{ width: '50px' }}>{shipment.items?.length >= 3 ? shipment.items.length : 0}</td></tr>
                            <tr><td className="py-1 px-1">380*180 (2-5")</td><td className="text-center font-bold text-red-600">{shipment.items?.length >= 5 ? Math.ceil(shipment.items.length * 0.4) : 0}</td></tr>
                          </tbody>
                        </table>
                      </td>
                      <td colSpan="3" className="p-1">
                        <div className="text-xs font-bold mb-2">2-4. 연동제어기</div>
                        <table className="w-full text-xs">
                          <tbody>
                            <tr><td className="py-1 px-1">매립형</td><td className="text-center font-bold text-red-600" style={{ width: '50px' }}>{shipment.items?.reduce((sum, item) => sum + item.qty, 0) || 0}</td></tr>
                            <tr><td className="py-1 px-1">노출형</td><td className="text-center"></td></tr>
                          </tbody>
                        </table>
                      </td>
                    </tr>
                  </tbody>
                </table>

                {/* 하단 서명 영역 */}
                <div className="flex justify-end mt-4">
                  <table className="border-collapse" style={{ fontSize: '10px', border: '1px solid black' }}>
                    <tbody>
                      <tr>
                        <td className="px-4 py-2 text-center bg-gray-100 font-semibold" style={{ borderRight: '1px solid black' }}>출고 담당</td>
                        <td className="px-8 py-4 text-center" style={{ width: '100px' }}></td>
                      </tr>
                      <tr>
                        <td className="px-4 py-2 text-center bg-gray-100 font-semibold" style={{ borderRight: '1px solid black', borderTop: '1px solid black' }}>인수 확인</td>
                        <td className="px-8 py-4 text-center" style={{ borderTop: '1px solid black' }}></td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 거래명세서 출력 모달 */}
      {showTransactionStatementModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl max-w-[90vw] max-h-[90vh] overflow-auto">
            <div className="sticky top-0 bg-white border-b px-6 py-4 flex items-center justify-between">
              <h3 className="text-lg font-bold">거래명세서 미리보기</h3>
              <div className="flex items-center gap-2">
                <Button variant="primary" onClick={() => window.print()}>
                  <Printer className="w-4 h-4" /> 인쇄
                </Button>
                <button
                  onClick={() => setShowTransactionStatementModal(false)}
                  className="p-2 hover:bg-gray-100 rounded-lg"
                >
                  <X className="w-5 h-5 text-gray-500" />
                </button>
              </div>
            </div>
            <div className="p-6 bg-gray-100">
              {/* 거래명세서 양식 */}
              <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '10mm', fontSize: '11px' }}>
                {/* 헤더 */}
                <div className="text-center mb-6">
                  <h1 className="text-2xl font-black tracking-widest mb-2">거 래 명 세 서</h1>
                  <p className="text-sm text-gray-600">TRANSACTION STATEMENT</p>
                </div>

                {/* 공급자/공급받는자 정보 */}
                <div className="grid grid-cols-2 gap-4 mb-6">
                  {/* 공급받는자 */}
                  <div className="border-2 border-gray-400 p-3">
                    <p className="text-xs font-bold text-gray-500 mb-2">공급받는자</p>
                    <table className="w-full text-sm">
                      <tbody>
                        <tr>
                          <td className="py-1 w-20 text-gray-600">상 호</td>
                          <td className="py-1 font-medium">{shipment.customerName}</td>
                        </tr>
                        <tr>
                          <td className="py-1 text-gray-600">현장명</td>
                          <td className="py-1">{shipment.siteName}</td>
                        </tr>
                        <tr>
                          <td className="py-1 text-gray-600">주 소</td>
                          <td className="py-1">{shipment.deliveryAddress}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>

                  {/* 공급자 */}
                  <div className="border-2 border-gray-400 p-3">
                    <p className="text-xs font-bold text-gray-500 mb-2">공급자</p>
                    <table className="w-full text-sm">
                      <tbody>
                        <tr>
                          <td className="py-1 w-20 text-gray-600">상 호</td>
                          <td className="py-1 font-medium">경동기업</td>
                        </tr>
                        <tr>
                          <td className="py-1 text-gray-600">대표자</td>
                          <td className="py-1">홍길동</td>
                        </tr>
                        <tr>
                          <td className="py-1 text-gray-600">주 소</td>
                          <td className="py-1">경기도 화성시 팔탄면 산업로 123</td>
                        </tr>
                        <tr>
                          <td className="py-1 text-gray-600">연락처</td>
                          <td className="py-1">031-123-4567</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>

                {/* 거래정보 */}
                <div className="mb-4">
                  <table className="w-full text-sm border-collapse">
                    <tbody>
                      <tr className="border-y border-gray-400">
                        <td className="py-2 px-3 bg-gray-100 w-24 font-medium">거래일자</td>
                        <td className="py-2 px-3">{shipment.shipmentDate}</td>
                        <td className="py-2 px-3 bg-gray-100 w-24 font-medium">출고번호</td>
                        <td className="py-2 px-3 font-mono">{shipment.releaseNo || '-'}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>

                {/* 품목 테이블 */}
                <table className="w-full text-sm border-collapse mb-6">
                  <thead>
                    <tr className="bg-gray-200">
                      <th className="border border-gray-400 py-2 px-2 w-10">No</th>
                      <th className="border border-gray-400 py-2 px-2">품 목 명</th>
                      <th className="border border-gray-400 py-2 px-2">규 격</th>
                      <th className="border border-gray-400 py-2 px-2 w-16">수량</th>
                      <th className="border border-gray-400 py-2 px-2 w-20">단가</th>
                      <th className="border border-gray-400 py-2 px-2 w-24">금액</th>
                      <th className="border border-gray-400 py-2 px-2">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {shipment.items.map((item, idx) => (
                      <tr key={item.id}>
                        <td className="border border-gray-400 py-2 px-2 text-center">{idx + 1}</td>
                        <td className="border border-gray-400 py-2 px-2">{item.productName}</td>
                        <td className="border border-gray-400 py-2 px-2">{item.spec}</td>
                        <td className="border border-gray-400 py-2 px-2 text-center">{item.qty}</td>
                        <td className="border border-gray-400 py-2 px-2 text-right">{(item.unitPrice || 0).toLocaleString()}</td>
                        <td className="border border-gray-400 py-2 px-2 text-right">{((item.unitPrice || 0) * (item.qty || 0)).toLocaleString()}</td>
                        <td className="border border-gray-400 py-2 px-2">{item.floor}/{item.location}</td>
                      </tr>
                    ))}
                    {/* 빈 행 추가 */}
                    {Array.from({ length: Math.max(0, 8 - shipment.items.length) }).map((_, idx) => (
                      <tr key={`empty-${idx}`}>
                        <td className="border border-gray-400 py-2 px-2">&nbsp;</td>
                        <td className="border border-gray-400 py-2 px-2"></td>
                        <td className="border border-gray-400 py-2 px-2"></td>
                        <td className="border border-gray-400 py-2 px-2"></td>
                        <td className="border border-gray-400 py-2 px-2"></td>
                        <td className="border border-gray-400 py-2 px-2"></td>
                        <td className="border border-gray-400 py-2 px-2"></td>
                      </tr>
                    ))}
                  </tbody>
                  <tfoot>
                    <tr className="bg-gray-100 font-bold">
                      <td colSpan="5" className="border border-gray-400 py-2 px-3 text-center">합 계</td>
                      <td className="border border-gray-400 py-2 px-2 text-right">
                        {shipment.items.reduce((sum, item) => sum + ((item.unitPrice || 0) * (item.qty || 0)), 0).toLocaleString()}
                      </td>
                      <td className="border border-gray-400 py-2 px-2"></td>
                    </tr>
                  </tfoot>
                </table>

                {/* 하단 안내 */}
                <div className="text-center text-sm text-gray-600 mt-8">
                  <p>위와 같이 거래하였음을 확인합니다.</p>
                  <p className="mt-4 font-bold">경 동 기 업</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 납품확인서 출력 모달 - 문서양식관리 DC 형식 */}
      {showDeliveryConfirmationModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-4xl max-h-[95vh] overflow-hidden flex flex-col">
            {/* 헤더 */}
            <div className="flex items-center justify-between p-4 border-b bg-gray-50">
              <div className="flex items-center gap-2">
                <Clipboard className="w-5 h-5 text-green-600" />
                <h2 className="text-lg font-bold text-gray-900">납품확인서</h2>
              </div>
              <div className="flex items-center gap-2">
                <button className="p-2 hover:bg-gray-200 rounded-lg text-gray-600">
                  <Printer className="w-4 h-4" />
                </button>
                <button className="p-2 hover:bg-gray-200 rounded-lg text-gray-600">
                  <Download className="w-4 h-4" />
                </button>
                <button onClick={() => setShowDeliveryConfirmationModal(false)} className="p-2 hover:bg-gray-200 rounded-lg">
                  <X className="w-5 h-5" />
                </button>
              </div>
            </div>

            {/* 납품확인서 내용 - A4 세로 */}
            <div className="flex-1 overflow-y-auto p-4 bg-gray-100">
              <div className="bg-white shadow-lg mx-auto" style={{ width: '210mm', minHeight: '297mm', padding: '10mm', fontSize: '10px' }}>
                {/* 헤더 - KD 로고 + 타이틀 + 결재란 */}
                <div className="flex items-start justify-between mb-4">
                  {/* 좌측: 로고 */}
                  <div className="flex items-center gap-2">
                    <div>
                      <div className="text-3xl font-bold text-blue-800" style={{ fontFamily: 'serif' }}>KD</div>
                      <div className="text-xs text-blue-800 font-medium">경동기업</div>
                    </div>
                  </div>

                  {/* 중앙: 타이틀 */}
                  <div className="text-center flex-1">
                    <h1 className="text-2xl font-bold tracking-widest mb-1">납 품 확 인 서</h1>
                    <p className="text-xs text-gray-500">출하 관리부서</p>
                  </div>

                  {/* 우측: 결재란 */}
                  <table className="border-collapse text-xs" style={{ border: '1px solid black' }}>
                    <tbody>
                      <tr>
                        <td className="px-2 py-1 text-center font-bold bg-gray-100" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>결</td>
                        <td className="px-3 py-1 text-center text-xs" style={{ width: '50px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>작성</td>
                        <td className="px-3 py-1 text-center text-xs" style={{ width: '50px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>검토</td>
                        <td className="px-3 py-1 text-center text-xs" style={{ width: '50px', borderBottom: '1px solid black' }}>승인</td>
                      </tr>
                      <tr>
                        <td className="px-2 py-3 text-center font-bold bg-gray-100" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>재</td>
                        <td className="px-3 py-3" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                        <td className="px-3 py-3" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                        <td className="px-3 py-3" style={{ borderBottom: '1px solid black' }}></td>
                      </tr>
                      <tr>
                        <td className="px-2 py-1 text-center font-bold bg-gray-100" style={{ borderRight: '1px solid black' }}></td>
                        <td className="px-3 py-1 text-center text-xs text-gray-500" style={{ borderRight: '1px solid black' }}>판매/전진</td>
                        <td className="px-3 py-1 text-center text-xs text-gray-500" style={{ borderRight: '1px solid black' }}>출하</td>
                        <td className="px-3 py-1 text-center text-xs text-gray-500">품질</td>
                      </tr>
                    </tbody>
                  </table>
                </div>

                {/* 전화 / 팩스 / 이메일 */}
                <div className="text-xs text-center mb-3 text-gray-600">
                  전화 : 031-938-5130 | 팩스 : 02-6911-6315 | 이메일 : kd5130@naver.com
                </div>

                {/* 납품 정보 테이블 */}
                <table className="w-full border-collapse mb-3" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td colSpan="2" className="text-center font-bold py-1.5 bg-gray-200 text-sm" style={{ width: '50%', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 정 보</td>
                      <td colSpan="2" className="text-center font-bold py-1.5 bg-gray-200 text-sm" style={{ width: '50%', borderBottom: '1px solid black' }}>납 품 정 보</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-2 font-semibold" style={{ width: '80px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 일</td>
                      <td className="px-2 py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{linkedOrder?.orderDate || shipment.orderDate || '-'}</td>
                      <td className="text-center bg-gray-100 py-2 font-semibold" style={{ width: '80px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>납 품 일</td>
                      <td className="px-2 py-2 font-bold" style={{ borderBottom: '1px solid black' }}>{shipment.shipmentDate || '-'}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>발 주 처</td>
                      <td className="px-2 py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{linkedOrder?.customerName || shipment.customerName || '-'}</td>
                      <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>현 장 명</td>
                      <td className="px-2 py-2 font-bold" style={{ borderBottom: '1px solid black' }}>{linkedOrder?.siteName || shipment.siteName || '-'}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>담 당 자</td>
                      <td className="px-2 py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{linkedOrder?.contactPerson || '-'}</td>
                      <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>인수담당자</td>
                      <td className="px-2 py-2 font-bold" style={{ borderBottom: '1px solid black' }}>{shipment.receiverName || '-'}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>연 락 처</td>
                      <td className="px-2 py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{linkedOrder?.contactPhone || '-'}</td>
                      <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>인수자연락처</td>
                      <td className="px-2 py-2" style={{ borderBottom: '1px solid black' }}>{shipment.receiverPhone || '-'}</td>
                    </tr>
                    <tr>
                      <td className="text-center bg-yellow-300 py-2 font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>제품 LOT NO.</td>
                      <td className="px-2 py-2 font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shipment.lotNo || '-'}</td>
                      <td className="text-center bg-gray-100 py-2 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>납품지 주소</td>
                      <td className="px-2 py-2" style={{ borderBottom: '1px solid black' }}>{shipment.deliveryAddress || '-'}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 납품 품목 테이블 */}
                <div className="text-sm font-bold mb-2">납품 품목</div>
                <table className="w-full border-collapse mb-4" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <thead>
                    <tr className="bg-gray-200">
                      <th className="py-2 text-center font-bold" style={{ width: '40px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>No</th>
                      <th className="py-2 text-center font-bold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>품 명</th>
                      <th className="py-2 text-center font-bold" style={{ width: '120px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>규 격</th>
                      <th className="py-2 text-center font-bold" style={{ width: '50px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>단위</th>
                      <th className="py-2 text-center font-bold" style={{ width: '60px', borderRight: '1px solid black', borderBottom: '1px solid black' }}>수량</th>
                      <th className="py-2 text-center font-bold" style={{ width: '100px', borderBottom: '1px solid black' }}>비 고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {shipment.items.map((item, idx) => (
                      <tr key={item.id}>
                        <td className="py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{idx + 1}</td>
                        <td className="py-2 px-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.productName}</td>
                        <td className="py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.spec}</td>
                        <td className="py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>SET</td>
                        <td className="py-2 text-center font-bold text-red-600" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{item.qty}</td>
                        <td className="py-2 px-2" style={{ borderBottom: '1px solid black' }}>{item.floor}/{item.location}</td>
                      </tr>
                    ))}
                    {/* 빈 행 추가 (총 10행) */}
                    {Array.from({ length: Math.max(0, 10 - shipment.items.length) }).map((_, idx) => (
                      <tr key={`empty-${idx}`}>
                        <td className="py-2 text-center" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>{shipment.items.length + idx + 1}</td>
                        <td className="py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                        <td className="py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                        <td className="py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                        <td className="py-2" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}></td>
                        <td className="py-2" style={{ borderBottom: '1px solid black' }}></td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* 특기사항 */}
                <div className="text-sm font-bold mb-2">특기사항</div>
                <table className="w-full border-collapse mb-6" style={{ fontSize: '9px', border: '2px solid black' }}>
                  <tbody>
                    <tr>
                      <td className="p-3" style={{ height: '60px' }}>
                        위 물품을 상기와 같이 납품합니다.
                      </td>
                    </tr>
                  </tbody>
                </table>

                {/* 하단 - 서명 영역 */}
                <div className="flex justify-between mt-8">
                  {/* 납품자 서명 */}
                  <table className="border-collapse" style={{ fontSize: '10px', border: '1px solid black' }}>
                    <tbody>
                      <tr>
                        <td colSpan="2" className="px-4 py-2 text-center bg-gray-200 font-bold" style={{ borderBottom: '1px solid black' }}>납 품 자</td>
                      </tr>
                      <tr>
                        <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>회 사 명</td>
                        <td className="px-4 py-2" style={{ width: '150px', borderBottom: '1px solid black' }}>경동기업</td>
                      </tr>
                      <tr>
                        <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>담 당 자</td>
                        <td className="px-4 py-2" style={{ borderBottom: '1px solid black' }}>전진</td>
                      </tr>
                      <tr>
                        <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black' }}>서명/날인</td>
                        <td className="px-4 py-6 text-center"></td>
                      </tr>
                    </tbody>
                  </table>

                  {/* 인수자 서명 */}
                  <table className="border-collapse" style={{ fontSize: '10px', border: '1px solid black' }}>
                    <tbody>
                      <tr>
                        <td colSpan="2" className="px-4 py-2 text-center bg-gray-200 font-bold" style={{ borderBottom: '1px solid black' }}>인 수 자</td>
                      </tr>
                      <tr>
                        <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>회 사 명</td>
                        <td className="px-4 py-2" style={{ width: '150px', borderBottom: '1px solid black' }}></td>
                      </tr>
                      <tr>
                        <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black', borderBottom: '1px solid black' }}>담 당 자</td>
                        <td className="px-4 py-2" style={{ borderBottom: '1px solid black' }}></td>
                      </tr>
                      <tr>
                        <td className="px-4 py-2 bg-gray-100 font-semibold" style={{ borderRight: '1px solid black' }}>서명/날인</td>
                        <td className="px-4 py-6 text-center"></td>
                      </tr>
                    </tbody>
                  </table>
                </div>

                {/* 하단 안내문 */}
                <div className="text-xs text-center text-gray-500 mt-6">
                  상기 물품을 정히 인수하였음을 확인합니다.
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 출고 수정
const ShipmentEdit = ({ shipment, onNavigate, onBack, onSave }) => {
  const [formData, setFormData] = useState({
    shipmentDate: shipment.shipmentDate,
    dispatchType: shipment.dispatchType,
    shipmentPriority: shipment.shipmentPriority || 3,
    loadingWorker: shipment.loadingWorker || '',
    logisticsCompany: shipment.logisticsCompany || '',
    vehicleType: shipment.vehicleType || '',
    vehicleNo: shipment.vehicleNo || '',
    driverName: shipment.driverName || '',
    driverPhone: shipment.driverPhone || '',
    scheduledArrival: shipment.scheduledArrival || '',
    confirmedArrival: shipment.confirmedArrival || '',
    shippingCost: shipment.shippingCost || 0,
    trackingNo: shipment.trackingNo || '',
    note: shipment.note || '',
    changeReason: '',
  });

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleSubmit = () => {
    // 변경 이력 추가
    const changes = [];
    if (formData.shipmentDate !== shipment.shipmentDate) {
      changes.push({
        changeType: '출고일 변경',
        beforeValue: shipment.shipmentDate,
        afterValue: formData.shipmentDate,
      });
    }
    if (formData.dispatchType !== shipment.dispatchType) {
      changes.push({
        changeType: '배송방식 변경',
        beforeValue: shipment.dispatchType,
        afterValue: formData.dispatchType,
      });
    }
    if (formData.shipmentPriority !== shipment.shipmentPriority) {
      const oldPriority = priorityOptions.find(p => p.value === shipment.shipmentPriority)?.label || '보통';
      const newPriority = priorityOptions.find(p => p.value === formData.shipmentPriority)?.label || '보통';
      changes.push({
        changeType: '우선순위 변경',
        beforeValue: oldPriority,
        afterValue: newPriority,
      });
    }
    if (formData.loadingWorker !== (shipment.loadingWorker || '')) {
      changes.push({
        changeType: '상차담당자 변경',
        beforeValue: shipment.loadingWorker || '미배정',
        afterValue: formData.loadingWorker || '미배정',
      });
    }

    const newHistory = changes.map((change, idx) => ({
      id: (shipment.changeHistory?.length || 0) + idx + 1,
      changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
      ...change,
      reason: formData.changeReason,
      changedBy: '현재 사용자',
    }));

    const updatedShipment = {
      ...shipment,
      ...formData,
      changeHistory: [...(shipment.changeHistory || []), ...newHistory],
    };
    delete updatedShipment.changeReason;

    onSave?.(updatedShipment);
    onBack();
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button onClick={onBack} className="p-2 hover:bg-gray-100 rounded-lg">
            <ArrowLeft className="w-5 h-5 text-gray-500" />
          </button>
          <Truck className="w-6 h-6 text-green-500" />
          <div>
            <h1 className="text-xl font-bold text-gray-900">출고 수정</h1>
            <p className="text-sm text-gray-500 font-mono">{shipment.splitNo}</p>
          </div>
          <StatusBadge status={shipment.status} />
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={onBack}>취소</Button>
          <Button variant="primary" onClick={handleSubmit}>
            <Check className="w-4 h-4" /> 저장
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6">
        {/* 기본 정보 (읽기 전용) */}
        <Card title="기본 정보">
          <div className="grid grid-cols-2 gap-4">
            <InfoRow label="출고번호" value={shipment.releaseNo || '-'} />
            <InfoRow label="로트번호" value={shipment.lotNo} />
            <InfoRow label="발주처" value={shipment.customerName} />
            <InfoRow label="현장명" value={shipment.siteName} />
            <div className="col-span-2">
              <InfoRow label="배송주소" value={shipment.deliveryAddress} />
            </div>
          </div>
        </Card>

        {/* 출고 정보 수정 */}
        <Card title="출고 정보">
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <FormField label="출고예정일" required>
                <input
                  type="date"
                  value={formData.shipmentDate}
                  onChange={(e) => handleChange('shipmentDate', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </FormField>

              <FormField label="출고 우선순위" required>
                <select
                  value={formData.shipmentPriority}
                  onChange={(e) => handleChange('shipmentPriority', parseInt(e.target.value))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  {priorityOptions.map(p => (
                    <option key={p.value} value={p.value}>{p.label}</option>
                  ))}
                </select>
              </FormField>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField label="배송방식" required>
                <select
                  value={formData.dispatchType}
                  onChange={(e) => handleChange('dispatchType', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  {dispatchTypes.map(type => (
                    <option key={type} value={type}>{type}</option>
                  ))}
                </select>
              </FormField>

              <FormField label="상차담당자">
                <TextInput
                  value={formData.loadingWorker}
                  onChange={(v) => handleChange('loadingWorker', v)}
                  placeholder="상차담당자명"
                />
              </FormField>
            </div>

            {formData.dispatchType === '상차' && (
              <>
                <FormField label="물류사">
                  <select
                    value={formData.logisticsCompany}
                    onChange={(e) => handleChange('logisticsCompany', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">선택하세요</option>
                    {logisticsCompanies.map(company => (
                      <option key={company} value={company}>{company}</option>
                    ))}
                  </select>
                </FormField>
                <FormField label="차량 톤수">
                  <select
                    value={formData.vehicleType}
                    onChange={(e) => handleChange('vehicleType', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">선택하세요</option>
                    {vehicleTypes.map(type => (
                      <option key={type} value={type}>{type}</option>
                    ))}
                  </select>
                </FormField>
              </>
            )}

            {(formData.dispatchType === '택배' || formData.dispatchType === '화물') && (
              <FormField label="운송장번호">
                <TextInput
                  value={formData.trackingNo}
                  onChange={(v) => handleChange('trackingNo', v)}
                  placeholder="운송장번호 입력"
                />
              </FormField>
            )}
          </div>
        </Card>

        {/* 배차 정보 */}
        <Card title="배차 정보">
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <FormField label="차량번호">
                <TextInput
                  value={formData.vehicleNo}
                  onChange={(v) => handleChange('vehicleNo', v)}
                  placeholder="12가 3456"
                />
              </FormField>
              <FormField label="운송비">
                <input
                  type="number"
                  value={formData.shippingCost}
                  onChange={(e) => handleChange('shippingCost', parseInt(e.target.value) || 0)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </FormField>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField label="운전자명">
                <TextInput
                  value={formData.driverName}
                  onChange={(v) => handleChange('driverName', v)}
                  placeholder="운전자명"
                />
              </FormField>
              <FormField label="운전자 연락처">
                <TextInput
                  value={formData.driverPhone}
                  onChange={(v) => handleChange('driverPhone', v)}
                  placeholder="010-0000-0000"
                />
              </FormField>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField label="입차예정시간">
                <input
                  type="datetime-local"
                  value={formData.scheduledArrival}
                  onChange={(e) => handleChange('scheduledArrival', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </FormField>
              <FormField label="입차확정시간">
                <input
                  type="datetime-local"
                  value={formData.confirmedArrival}
                  onChange={(e) => handleChange('confirmedArrival', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </FormField>
            </div>
          </div>
        </Card>

        {/* 변경 사유 */}
        <Card title="변경 사유">
          <FormField label="변경 사유" required>
            <textarea
              value={formData.changeReason}
              onChange={(e) => handleChange('changeReason', e.target.value)}
              placeholder="변경 사유를 입력하세요 (예: 고객 요청, 물류사 일정 조율 등)"
              rows={3}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </FormField>
          <FormField label="비고">
            <textarea
              value={formData.note}
              onChange={(e) => handleChange('note', e.target.value)}
              placeholder="특이사항 입력"
              rows={3}
              className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </FormField>
        </Card>
      </div>
    </div>
  );
};

// ============ 품질관리 - 제품검사 ============

// 제품검사 목록
const ProductInspectionList = ({
  inspections,
  onNavigate,
  shipments = [], // 출하 정보
  onApprovalRequest, // 결재요청 콜백
  onShipmentCertify, // 출하증명 발행 콜백
}) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [showApprovalModal, setShowApprovalModal] = useState(false);
  const [selectedForApproval, setSelectedForApproval] = useState(null);

  // ★ 결재 처리 핸들러
  const handleApproval = (inspection, approverName) => {
    const today = new Date();
    const updatedApprovalLine = {
      ...inspection.approvalLine,
      roles: (inspection.approvalLine?.roles || []).map(role => {
        if (role.status === 'pending') {
          const pendingRoles = inspection.approvalLine.roles.filter(r => r.status === 'pending');
          if (pendingRoles[0]?.id === role.id) {
            return { ...role, name: approverName, date: today.toISOString().split('T')[0], status: 'approved' };
          }
        }
        return role;
      })
    };

    const allApproved = updatedApprovalLine.roles?.every(r => r.status === 'approved');

    // 결재 완료 시 후속 처리
    if (allApproved && inspection.result === '합격') {
      // 출하증명서 발행 가능
      onShipmentCertify?.({
        inspectionNo: inspection.inspectionNo,
        customerName: inspection.customerName,
        siteName: inspection.siteName,
        setLotNo: inspection.setLotNo,
        certifiedAt: today.toISOString(),
      });
    }

    // 결재 요청 콜백
    onApprovalRequest?.({
      ...inspection,
      approvalStatus: allApproved ? '결재완료' : '결재중',
      approvalLine: updatedApprovalLine,
      processFlow: {
        ...inspection.processFlow,
        currentStep: allApproved ? (inspection.result === '합격' ? '출하증명발행가능' : '재검사필요') : '결재진행중',
      }
    });

    setShowApprovalModal(false);
    setSelectedForApproval(null);

    if (allApproved) {
      alert(`✅ 결재가 완료되었습니다.\n\n검사번호: ${inspection.inspectionNo}\n${inspection.result === '합격' ? '출하증명서 발행이 가능합니다.' : '재검사가 필요합니다.'}`);
    }
  };

  // 현재 결재 단계 확인
  const getCurrentApprovalStep = (approvalLine) => {
    if (!approvalLine?.roles) return null;
    return approvalLine.roles.find(r => r.status === 'pending');
  };

  const tabs = [
    { id: 'all', label: '전체', count: inspections.length },
    { id: 'request', label: '검사신청', count: inspections.filter(i => i.status === '검사신청').length },
    { id: 'scheduled', label: '검사예정', count: inspections.filter(i => i.status === '검사예정').length },
    { id: 'progress', label: '검사중', count: inspections.filter(i => i.status === '검사중').length },
    { id: 'approval', label: '결재대기', count: inspections.filter(i => i.approvalStatus === '결재대기').length },
    { id: 'complete', label: '완료', count: inspections.filter(i => i.approvalStatus === '결재완료').length },
  ];

  const statusFilter = {
    all: () => true,
    request: (i) => i.status === '검사신청',
    scheduled: (i) => i.status === '검사예정',
    progress: (i) => i.status === '검사중',
    approval: (i) => i.approvalStatus === '결재대기',
    complete: (i) => i.approvalStatus === '결재완료',
  };

  const filtered = inspections
    .filter(statusFilter[activeTab])
    .filter(i =>
      i.inspectionNo.toLowerCase().includes(search.toLowerCase()) ||
      i.customerName.includes(search) ||
      i.siteName.includes(search)
    );

  return (
    <div className="space-y-6">
      <PageHeader
        icon={ShieldCheck}
        title="제품검사 목록"
        actions={
          <Button variant="primary" onClick={() => onNavigate('product-inspection-create')}>
            <Plus className="w-4 h-4" /> 검사 등록
          </Button>
        }
      />

      {/* 대시보드 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <DashboardCard icon={FileText} title="검사 신청" value={`${inspections.filter(i => i.status === '검사신청').length}건`} color="yellow" />
        <DashboardCard icon={Calendar} title="검사 예정" value={`${inspections.filter(i => i.status === '검사예정').length}건`} color="blue" />
        <DashboardCard icon={Clock} title="결재 대기" value={`${inspections.filter(i => i.approvalStatus === '결재대기').length}건`} color="purple" />
        <DashboardCard icon={CheckCircle} title="이번 달 완료" value={`${inspections.filter(i => i.approvalStatus === '결재완료').length}건`} color="green" />
      </div>

      {/* 검색 */}
      <SearchInput
        placeholder="검사번호, 발주처, 현장명 검색..."
        value={search}
        onChange={setSearch}
      />

      {/* 탭 필터 */}
      <TabFilter tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />

      {/* 테이블 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">번호</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">검사번호</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">신청일</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">상태</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">발주처</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">현장명</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">세트LOT</th>
              <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">검사항목</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">검사예정일</th>
              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">결재</th>
              <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map((inspection, idx) => (
              <tr
                key={inspection.id}
                className="hover:bg-gray-50 cursor-pointer"
                onClick={() => onNavigate('product-inspection-detail', inspection)}
              >
                <td className="px-4 py-3 text-sm text-gray-500">{filtered.length - idx}</td>
                <td className="px-4 py-3 text-sm font-mono text-blue-600">{inspection.inspectionNo}</td>
                <td className="px-4 py-3 text-sm text-gray-900">{inspection.requestDate}</td>
                <td className="px-4 py-3"><StatusBadge status={inspection.status} /></td>
                <td className="px-4 py-3 text-sm text-gray-900">{inspection.customerName}</td>
                <td className="px-4 py-3 text-sm text-gray-900">{inspection.siteName}</td>
                <td className="px-4 py-3 text-sm font-mono text-gray-500">{inspection.setLotNo || '-'}</td>
                <td className="px-4 py-3 text-sm text-center">
                  <span className="font-medium text-blue-600">{inspection.completedItems}</span>
                  <span className="text-gray-400">/{inspection.totalItems}</span>
                </td>
                <td className="px-4 py-3 text-sm text-gray-900">{inspection.scheduledDate || '-'}</td>
                <td className="px-4 py-3">
                  <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${inspection.approvalStatus === '결재완료' ? 'bg-green-100 text-green-700' :
                      inspection.approvalStatus === '결재대기' ? 'bg-yellow-100 text-yellow-700' :
                        'bg-gray-100 text-gray-500'
                    }`}>
                    {inspection.approvalStatus}
                  </span>
                </td>
                <td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                  <div className="flex gap-1 justify-center">
                    {inspection.approvalStatus === '결재대기' && (
                      <button
                        onClick={() => { setSelectedForApproval(inspection); setShowApprovalModal(true); }}
                        className="px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600"
                      >
                        결재
                      </button>
                    )}
                    {inspection.approvalStatus === '결재완료' && (
                      <button
                        onClick={() => alert(`출하증명서 발행: ${inspection.inspectionNo}`)}
                        className="px-2 py-1 bg-green-500 text-white text-xs rounded hover:bg-green-600"
                      >
                        증명서
                      </button>
                    )}
                    <button
                      onClick={() => alert(`검사성적서 출력: ${inspection.inspectionNo}`)}
                      className="px-2 py-1 bg-gray-500 text-white text-xs rounded hover:bg-gray-600"
                    >
                      출력
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* ★ 결재 모달 (APR-3LINE) */}
      {showApprovalModal && selectedForApproval && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-lg">
            <div className="p-4 border-b flex justify-between items-center">
              <h3 className="text-lg font-bold">제품검사 결재</h3>
              <button onClick={() => setShowApprovalModal(false)} className="p-1 hover:bg-gray-100 rounded text-gray-400 hover:text-gray-600 text-xl font-bold">
                ✕
              </button>
            </div>
            <div className="p-6 space-y-4">
              {/* 검사 정보 */}
              <div className="bg-blue-50 rounded-lg p-4">
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div><span className="text-gray-500">검사번호:</span> <span className="font-mono font-medium">{selectedForApproval.inspectionNo}</span></div>
                  <div><span className="text-gray-500">발주처:</span> <span>{selectedForApproval.customerName}</span></div>
                  <div><span className="text-gray-500">현장명:</span> <span className="font-medium">{selectedForApproval.siteName}</span></div>
                  <div><span className="text-gray-500">세트LOT:</span> <span className="font-mono">{selectedForApproval.setLotNo || '-'}</span></div>
                  <div>
                    <span className="text-gray-500">검사진행:</span>
                    <span className="ml-1 font-medium text-blue-600">{selectedForApproval.completedItems}/{selectedForApproval.totalItems}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">검사상태:</span>
                    <span className={`ml-1 px-2 py-0.5 rounded text-xs font-medium ${selectedForApproval.status === '완료' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
                      }`}>
                      {selectedForApproval.status}
                    </span>
                  </div>
                </div>
              </div>

              {/* 결재라인 표시 (APR-3LINE: 작성 → 검토 → 승인) */}
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2">결재라인 (3단계)</h4>
                <div className="flex items-center justify-center gap-2">
                  {(selectedForApproval.approvalLine?.roles || [
                    { id: 'writer', label: '작성', name: '', status: 'pending' },
                    { id: 'reviewer', label: '검토', name: '', status: 'pending' },
                    { id: 'approver', label: '승인', name: '', status: 'pending' },
                  ]).map((role, idx, arr) => (
                    <React.Fragment key={role.id}>
                      <div className={`text-center p-3 rounded-lg border-2 min-w-[80px] ${role.status === 'approved' ? 'border-green-500 bg-green-50' :
                          role.status === 'pending' && idx === arr.findIndex(r => r.status === 'pending')
                            ? 'border-blue-500 bg-blue-50' : 'border-gray-200 bg-gray-50'
                        }`}>
                        <div className="text-xs text-gray-500 mb-1">{role.label}</div>
                        <div className="font-medium text-sm">{role.name || '-'}</div>
                        <div className="text-xs text-gray-400 mt-1">
                          {role.status === 'approved' ? role.date : role.status === 'pending' ? '대기' : ''}
                        </div>
                        {role.status === 'approved' && (
                          <CheckCircle className="w-4 h-4 text-green-600 mx-auto mt-1" />
                        )}
                      </div>
                      {idx < arr.length - 1 && (
                        <ChevronRight className="w-5 h-5 text-gray-400" />
                      )}
                    </React.Fragment>
                  ))}
                </div>
              </div>

              {/* 현재 결재자 입력 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  결재자 <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  id="fqc-approver-name"
                  placeholder="결재자 이름"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>

              {/* 프로세스 플로우 정보 */}
              <div className="bg-gray-50 rounded-lg p-3 text-sm">
                <div className="flex items-center gap-2 text-gray-600">
                  <span className="font-medium">검사유형:</span>
                  <span className="px-2 py-0.5 bg-purple-100 text-purple-700 rounded text-xs">
                    출하 후 고객 요청 검사
                  </span>
                </div>
                <div className="text-xs text-gray-500 mt-1">
                  결재완료 시: 합격→출하증명서 발행 가능 / 불합격→재검사 또는 불량 처리
                </div>
              </div>
            </div>
            <div className="p-4 border-t flex justify-end gap-2">
              <button
                onClick={() => setShowApprovalModal(false)}
                className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={() => {
                  const approverInput = document.getElementById('fqc-approver-name');
                  if (!approverInput?.value) {
                    alert('결재자 이름을 입력해주세요.');
                    return;
                  }
                  handleApproval(selectedForApproval, approverInput.value);
                }}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
              >
                결재승인
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 제품검사 상세
const ProductInspectionDetail = ({ inspection, onNavigate, onBack, onUpdate }) => {
  const [inspectionData, setInspectionData] = useState(inspection);

  // 제품검사성적서 검사항목 상태
  const [inspectionSheet, setInspectionSheet] = useState({
    productLotNo: inspection.setLotNo || '',
    productName: inspection.items?.[0]?.productName || '스크린 셔터',
    specification: inspection.items?.[0]?.orderSpec || '',
    inspectionDate: new Date().toISOString().split('T')[0],
    inspector: inspection.inspector || '',
    // 검사항목 (제품검사성적서 양식 기반)
    categories: [
      {
        id: 1,
        name: '겉모양',
        items: [
          { id: 1, name: '가공상태', standard: '사용상 해로운 결함이 없을 것', method: '육안검사', cycle: '전수검사', judgement: null },
          { id: 2, name: '재봉상태', standard: '내화실에 의해 견고하게 접합되어야 함', method: '육안검사', cycle: '전수검사', judgement: null },
          { id: 3, name: '조립상태', standard: '앤드락이 견고하게 조립되어야 함', method: '육안검사', cycle: '전수검사', judgement: null },
          { id: 4, name: '연기차단재', standard: '연기차단재 설치여부(케이스 W80, 가이드레일 W50)', method: '육안검사', cycle: '전수검사', judgement: null },
          { id: 5, name: '하단마감재', standard: '내부 무게평철 설치 유무', method: '육안검사', cycle: '전수검사', judgement: null },
        ]
      },
      {
        id: 2,
        name: '모터',
        items: [
          { id: 6, name: '모터', standard: '인정제품과 동일사양', method: '육안검사', cycle: '전수검사', judgement: null },
        ]
      },
      {
        id: 3,
        name: '재질',
        items: [
          { id: 7, name: '재질', standard: 'WY-SC780 인쇄상태 확인', method: '육안검사', cycle: '전수검사', judgement: null },
        ]
      },
      {
        id: 4,
        name: '치수(오픈사이즈)',
        items: [
          { id: 8, name: '길이', standard: '발주치수 ± 30mm', method: '체크검사', cycle: '전수검사', orderValue: '', measuredValue: '', judgement: null },
          { id: 9, name: '높이', standard: '발주치수 ± 30mm', method: '체크검사', cycle: '전수검사', orderValue: '', measuredValue: '', judgement: null },
          { id: 10, name: '가이드레일 홈간격', standard: '10 ± 5mm (ⓐ 높이 100 이내)', method: '체크검사', cycle: '전수검사', orderValue: '10', measuredValue: '', judgement: null },
          { id: 11, name: '하단마감재간격 (③+④)', standard: '가이드레일과 하단마감재 틈새 25mm 이내', method: '체크검사', cycle: '전수검사', orderValue: '25', measuredValue: '', judgement: null },
        ]
      },
      {
        id: 5,
        name: '작동테스트',
        items: [
          { id: 12, name: '개폐성능', standard: '작동 유무 확인(일부 및 완전폐쇄)', method: '실동작시험', cycle: '전수검사', judgement: null },
        ]
      },
      {
        id: 6,
        name: '내화시험',
        isExternalTest: true,
        items: [
          { id: 13, name: '비차열', standard: '6mm 균열게이지 관통 후 150mm 이동 유무', method: '공인시험기관', cycle: '1회/5년', judgement: null },
          { id: 14, name: '차열', standard: '25mm 균열게이지 관통 유무', method: '공인시험기관', cycle: '1회/5년', judgement: null },
          { id: 15, name: '열성', standard: '10초 이상 지속되는 화염발생 유무', method: '공인시험기관', cycle: '1회/5년', judgement: null },
        ]
      },
      {
        id: 7,
        name: '차연시험',
        isExternalTest: true,
        items: [
          { id: 16, name: '공기누설량', standard: '25Pa 일때 공기누설량 0.9㎥/min·㎡ 이하', method: '공인시험기관', cycle: '1회/5년', judgement: null },
        ]
      },
      {
        id: 8,
        name: '개폐시험',
        isExternalTest: true,
        items: [
          { id: 17, name: '개폐의 원활한 작동', standard: '개폐의 원활한 작동', method: '공인시험기관', cycle: '1회/5년', judgement: null },
          { id: 18, name: '평균속도(전도개폐)', standard: '2.5 ~ 6.5m/min', method: '공인시험기관', cycle: '1회/5년', judgement: null },
          { id: 19, name: '평균속도(자중강하)', standard: '3 ~ 7m/min', method: '공인시험기관', cycle: '1회/5년', judgement: null },
          { id: 20, name: '상하부 끝부분 자동정지', standard: '개폐 시 상부 및 하부 끝부분에서 자동정지', method: '공인시험기관', cycle: '1회/5년', judgement: null },
          { id: 21, name: '임의위치 정지', standard: '강하 중 임의의 위치에서 정지', method: '공인시험기관', cycle: '1회/5년', judgement: null },
        ]
      },
      {
        id: 9,
        name: '내충격시험',
        isExternalTest: true,
        items: [
          { id: 22, name: '내충격시험', standard: '방화상 유해한 파괴, 박리 탈락 유무', method: '공인시험기관', cycle: '1회/5년', judgement: null },
        ]
      },
    ],
    overallJudgement: null,
    specialNotes: '',
  });

  // 검사항목 판정 업데이트
  const handleInspectionSheetUpdate = (categoryId, itemId, field, value) => {
    setInspectionSheet(prev => ({
      ...prev,
      categories: prev.categories.map(cat =>
        cat.id === categoryId
          ? {
            ...cat,
            items: cat.items.map(item =>
              item.id === itemId ? { ...item, [field]: value } : item
            )
          }
          : cat
      )
    }));
  };

  // 종합판정 계산
  const calculateOverallJudgement = () => {
    const allItems = inspectionSheet.categories.flatMap(cat => cat.items);
    const judgedItems = allItems.filter(item => item.judgement !== null);
    const hasFailure = allItems.some(item => item.judgement === '부적합');

    if (judgedItems.length === allItems.length) {
      return hasFailure ? '부적합' : '적합';
    }
    return null;
  };

  // 검사 결과 입력
  const handleInspectionResult = (itemId, field, value) => {
    const updatedItems = inspectionData.items.map(item => {
      if (item.id === itemId) {
        const updated = { ...item, [field]: value };
        // 규격 일치 여부 자동 판정
        if (field === 'installedSpec' && updated.orderSpec) {
          updated.specMatch = value === updated.orderSpec;
        }
        // 적합/부적합에 따라 합격/불합격 자동 판정
        if (field === 'result') {
          updated.inspectedAt = new Date().toISOString().split('T')[0];
        }
        return updated;
      }
      return item;
    });

    const completedItems = updatedItems.filter(i => i.result !== null).length;
    const passedItems = updatedItems.filter(i => i.result === '합격').length;
    const failedItems = updatedItems.filter(i => i.result === '불합격').length;

    setInspectionData({
      ...inspectionData,
      items: updatedItems,
      completedItems,
      passedItems,
      failedItems,
    });
  };

  return (
    <div className="space-y-6">
      {/* 상단 헤더 - 타이틀 위, 버튼 아래 */}
      <div className="space-y-3">
        {/* 타이틀 영역 */}
        <div className="flex items-center gap-4">
          <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
            <ShieldCheck className="w-6 h-6 text-blue-500" />
            제품검사 상세
          </h1>
          <div className="flex items-center gap-2 text-sm text-gray-500">
            <span className="font-mono">{inspection.inspectionNo}</span>
            <StatusBadge status={inspection.status} />
            <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${inspection.approvalStatus === '결재완료' ? 'bg-green-100 text-green-700' :
                inspection.approvalStatus === '결재대기' ? 'bg-yellow-100 text-yellow-700' :
                  'bg-gray-100 text-gray-500'
              }`}>
              {inspection.approvalStatus}
            </span>
          </div>
        </div>
        {/* 버튼 영역 - 좌측: 문서버튼 / 우측: 액션버튼 */}
        <div className="flex items-center justify-between">
          {/* 좌측: 문서 버튼 */}
          <div className="flex items-center gap-2">
            <button className="flex items-center gap-1 px-3 py-1.5 text-sm border border-gray-300 rounded hover:bg-gray-50 transition-colors">
              <Printer className="w-4 h-4" />
              검사서 출력
            </button>
          </div>
          {/* 우측: 액션 버튼 */}
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={onBack}>목록</Button>
            {inspection.status === '검사신청' && (
              <Button variant="primary" size="sm"><Calendar className="w-4 h-4" /> 일정 확정</Button>
            )}
            {inspectionData.completedItems === inspectionData.totalItems && inspection.approvalStatus === '대기' && (
              <Button variant="success" size="sm"><CheckCircle className="w-4 h-4" /> 결재 요청</Button>
            )}
          </div>
        </div>
      </div>

      {/* 기본정보 섹션 */}
      <div className="grid grid-cols-1 gap-6">
        <Card title="검사 신청 정보">
          <div className="grid grid-cols-2 gap-4">
            <InfoRow label="검사번호" value={inspection.inspectionNo} />
            <InfoRow label="신청일" value={inspection.requestDate} />
            <InfoRow label="신청자" value={inspection.requestedBy} />
            <InfoRow label="검사상태" value={<StatusBadge status={inspection.status} />} />
            <InfoRow label="검사원" value={inspection.inspector || '미배정'} />
            <InfoRow label="등록자" value={inspection.createdBy} />
          </div>
        </Card>

        <Card title="현장 정보">
          <div className="grid grid-cols-2 gap-4">
            <InfoRow label="발주처" value={inspection.customerName} />
            <InfoRow label="현장명" value={inspection.siteName} />
            <InfoRow label="로트번호" value={
              <button className="text-blue-600 hover:underline font-mono">{inspection.lotNo}</button>
            } />
            <InfoRow label="분할번호" value={inspection.splitNo || '-'} />
          </div>
        </Card>

        <Card title="LOT 정보">
          <div className="space-y-4">
            <InfoRow label="세트LOT번호" value={
              inspection.setLotNo ? (
                <span className="font-mono text-blue-600">{inspection.setLotNo}</span>
              ) : (
                <Button size="sm" variant="outline">
                  <Plus className="w-4 h-4" /> 세트LOT 생성
                </Button>
              )
            } />
            {inspection.lotNos.length > 0 && (
              <div>
                <p className="text-sm text-gray-500 mb-2">포함된 LOT</p>
                <div className="flex flex-wrap gap-2">
                  {inspection.lotNos.map((lot, idx) => (
                    <span key={idx} className="px-2 py-1 bg-gray-100 rounded text-xs font-mono">{lot}</span>
                  ))}
                </div>
              </div>
            )}
          </div>
        </Card>

        <Card title="검사 일정">
          <div className="grid grid-cols-2 gap-4">
            <InfoRow label="검사예정일" value={inspection.scheduledDate || '미정'} />
            <InfoRow label="검사시간" value={inspection.scheduledTime || '미정'} />
          </div>
          {!inspection.scheduledDate && (
            <div className="mt-4 p-4 bg-yellow-50 rounded-lg text-sm text-yellow-700">
              <AlertCircle className="w-4 h-4 inline mr-1" />
              검사 일정이 확정되지 않았습니다. 발주처와 일정 조율 후 확정해주세요.
            </div>
          )}
        </Card>

        <Card title="검사 진행 현황">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="bg-gray-50 rounded-lg p-4 text-center">
              <p className="text-sm text-gray-500 mb-1">총 검사항목</p>
              <p className="text-2xl font-bold">{inspectionData.totalItems}</p>
            </div>
            <div className="bg-blue-50 rounded-lg p-4 text-center">
              <p className="text-sm text-gray-500 mb-1">검사완료</p>
              <p className="text-2xl font-bold text-blue-600">{inspectionData.completedItems}</p>
            </div>
            <div className="bg-green-50 rounded-lg p-4 text-center">
              <p className="text-sm text-gray-500 mb-1">합격</p>
              <p className="text-2xl font-bold text-green-600">{inspectionData.passedItems}</p>
            </div>
            <div className="bg-red-50 rounded-lg p-4 text-center">
              <p className="text-sm text-gray-500 mb-1">불합격</p>
              <p className="text-2xl font-bold text-red-600">{inspectionData.failedItems}</p>
            </div>
          </div>
          <div className="mt-4">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm text-gray-500">검사 진행률</span>
              <span className="text-sm font-medium">
                {inspectionData.totalItems > 0 ? Math.round((inspectionData.completedItems / inspectionData.totalItems) * 100) : 0}%
              </span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-3">
              <div
                className="bg-blue-500 h-3 rounded-full transition-all"
                style={{ width: `${inspectionData.totalItems > 0 ? (inspectionData.completedItems / inspectionData.totalItems) * 100 : 0}%` }}
              />
            </div>
          </div>
        </Card>
      </div>

      {/* 제품검사성적서 섹션 */}
      <div className="space-y-6">
        {/* 문서 헤더 */}
        <div className="bg-white rounded-lg border p-6">
          <div className="flex justify-between items-start mb-6">
            <div>
              <h2 className="text-xl font-bold">KD 경동기업</h2>
              <p className="text-sm text-gray-500">KYUNGDONG COMPANY</p>
            </div>
            <div className="text-center">
              <h1 className="text-2xl font-bold">제품검사성적서</h1>
            </div>
            <div className="text-right">
              <table className="border text-xs">
                <thead>
                  <tr className="bg-gray-100">
                    <th className="px-4 py-1 border-r">작성</th>
                    <th className="px-4 py-1">승인</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td className="px-4 py-3 border-r"></td>
                    <td className="px-4 py-3"></td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* 기본 정보 */}
          <div className="grid grid-cols-4 gap-4 mb-6 text-sm">
            <div className="border rounded p-3">
              <span className="text-gray-500 block mb-1">상품명</span>
              <span className="font-medium">{inspectionSheet.productName}</span>
            </div>
            <div className="border rounded p-3">
              <span className="text-gray-500 block mb-1">제품 LOT NO</span>
              <span className="font-mono font-medium">{inspectionSheet.productLotNo || '-'}</span>
            </div>
            <div className="border rounded p-3">
              <span className="text-gray-500 block mb-1">로트크기</span>
              <span className="font-medium">{inspectionData.totalItems} EA</span>
            </div>
            <div className="border rounded p-3">
              <span className="text-gray-500 block mb-1">검사일자</span>
              <span className="font-medium">{inspectionSheet.inspectionDate}</span>
            </div>
            <div className="border rounded p-3">
              <span className="text-gray-500 block mb-1">제품명</span>
              <span className="font-medium">{inspectionSheet.productName}</span>
            </div>
            <div className="border rounded p-3">
              <span className="text-gray-500 block mb-1">발주처</span>
              <span className="font-medium">{inspection.customerName}</span>
            </div>
            <div className="border rounded p-3">
              <span className="text-gray-500 block mb-1">현장명</span>
              <span className="font-medium">{inspection.siteName}</span>
            </div>
            <div className="border rounded p-3">
              <span className="text-gray-500 block mb-1">검사자</span>
              <input
                type="text"
                value={inspectionSheet.inspector}
                onChange={(e) => setInspectionSheet(prev => ({ ...prev, inspector: e.target.value }))}
                className="w-full border-b focus:outline-none"
                placeholder="검사자 입력"
              />
            </div>
          </div>

          {/* 검사항목 테이블 */}
          <div className="border rounded-lg overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-gray-100">
                <tr>
                  <th className="px-3 py-2 border-r text-left w-8">No</th>
                  <th className="px-3 py-2 border-r text-left w-32">검사항목</th>
                  <th className="px-3 py-2 border-r text-left">검사기준</th>
                  <th className="px-3 py-2 border-r text-center w-24">검사방법</th>
                  <th className="px-3 py-2 border-r text-center w-20">검사주기</th>
                  <th className="px-3 py-2 text-center w-32" colSpan="2">판정</th>
                </tr>
              </thead>
              <tbody>
                {inspectionSheet.categories.map((category, catIdx) => (
                  <>
                    {category.items.map((item, itemIdx) => (
                      <tr key={item.id} className={`border-t ${category.isExternalTest ? 'bg-yellow-50' : ''}`}>
                        {itemIdx === 0 && (
                          <td rowSpan={category.items.length} className="px-3 py-2 border-r text-center font-medium bg-gray-50">
                            {catIdx + 1}
                          </td>
                        )}
                        <td className="px-3 py-2 border-r">
                          {itemIdx === 0 && <span className="font-medium text-gray-700">{category.name}</span>}
                          {category.items.length > 1 && <div className="text-xs text-gray-500 mt-1">{item.name}</div>}
                          {category.items.length === 1 && <div className="text-xs text-gray-500">{item.name}</div>}
                        </td>
                        <td className="px-3 py-2 border-r text-xs text-gray-600">
                          {item.standard}
                          {item.orderValue !== undefined && (
                            <div className="mt-1 flex gap-2 items-center">
                              <span className="text-gray-400">도면치수:</span>
                              <input
                                type="text"
                                value={item.orderValue}
                                onChange={(e) => handleInspectionSheetUpdate(category.id, item.id, 'orderValue', e.target.value)}
                                className="w-16 px-1 border rounded text-center"
                              />
                              <span className="text-gray-400">측정값:</span>
                              <input
                                type="text"
                                value={item.measuredValue || ''}
                                onChange={(e) => handleInspectionSheetUpdate(category.id, item.id, 'measuredValue', e.target.value)}
                                className="w-16 px-1 border rounded text-center"
                              />
                            </div>
                          )}
                        </td>
                        <td className="px-3 py-2 border-r text-center text-xs">
                          {category.isExternalTest ? (
                            <span className="text-yellow-700">공인시험기관<br />시험성적서</span>
                          ) : (
                            item.method
                          )}
                        </td>
                        <td className="px-3 py-2 border-r text-center text-xs">{item.cycle}</td>
                        <td className="px-3 py-2 text-center">
                          <div className="flex gap-1 justify-center">
                            <button
                              onClick={() => handleInspectionSheetUpdate(category.id, item.id, 'judgement', '적합')}
                              className={`px-2 py-1 text-xs rounded border ${item.judgement === '적합'
                                  ? 'bg-green-500 text-white border-green-500'
                                  : 'bg-white text-gray-600 border-gray-300 hover:bg-green-50'
                                }`}
                            >
                              적합
                            </button>
                            <button
                              onClick={() => handleInspectionSheetUpdate(category.id, item.id, 'judgement', '부적합')}
                              className={`px-2 py-1 text-xs rounded border ${item.judgement === '부적합'
                                  ? 'bg-red-500 text-white border-red-500'
                                  : 'bg-white text-gray-600 border-gray-300 hover:bg-red-50'
                                }`}
                            >
                              부적합
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </>
                ))}
              </tbody>
            </table>
          </div>

          {/* 특이사항 및 종합판정 */}
          <div className="mt-6 grid grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">[특이사항]</label>
              <textarea
                value={inspectionSheet.specialNotes}
                onChange={(e) => setInspectionSheet(prev => ({ ...prev, specialNotes: e.target.value }))}
                rows={3}
                className="w-full border rounded-lg p-3 text-sm"
                placeholder="특이사항을 입력하세요..."
              />
              <p className="text-xs text-gray-500 mt-2">
                * 내화시험, 차연시험, 개폐시험, 내충격시험의 경우 공인시험기관에서 시험을 진행하며, 그 시험성적서로 갈음한다.
              </p>
            </div>
            <div className="flex flex-col justify-center items-center">
              <div className="text-lg font-medium text-gray-700 mb-3">종합판정</div>
              <div className={`text-3xl font-bold px-8 py-4 rounded-lg ${calculateOverallJudgement() === '적합' ? 'bg-green-100 text-green-700' :
                  calculateOverallJudgement() === '부적합' ? 'bg-red-100 text-red-700' :
                    'bg-gray-100 text-gray-500'
                }`}>
                {calculateOverallJudgement() || '검사 진행중'}
              </div>
              <p className="text-xs text-gray-500 mt-3">
                {inspectionSheet.categories.flatMap(c => c.items).filter(i => i.judgement !== null).length} /
                {inspectionSheet.categories.flatMap(c => c.items).length} 항목 검사 완료
              </p>
            </div>
          </div>

          {/* 문서 정보 */}
          <div className="mt-6 pt-4 border-t text-xs text-gray-400 flex justify-between">
            <span>KDQP-01-005</span>
            <span>㈜경동기업</span>
          </div>
        </div>
      </div>

      {/* 개소별 검사 섹션 */}
      <div className="space-y-6">
        <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-700">
          <p><strong>개소별 제품검사 안내</strong></p>
          <p className="mt-1">
            * 각 개소별로 납품사이즈와 실제 시공사이즈 일치 여부를 확인합니다.<br />
            * 적합/부적합 결과에 따라 합격/불합격이 자동 판정됩니다.<br />
            * 모든 항목 검사 완료 후 품질팀장에게 결재를 요청합니다.
          </p>
        </div>

        <Card title={`검사 항목 (${inspectionData.completedItems}/${inspectionData.totalItems} 완료)`}>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">No</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">층</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">부호</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">납품규격</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">시공규격</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">규격일치</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">검사결과</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">비고</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {inspectionData.items.map((item, idx) => (
                  <tr key={item.id} className={item.result ? 'bg-gray-50' : ''}>
                    <td className="px-4 py-3 text-sm text-gray-500">{idx + 1}</td>
                    <td className="px-4 py-3 text-sm font-medium">{item.floor}</td>
                    <td className="px-4 py-3 text-sm">{item.location}</td>
                    <td className="px-4 py-3 text-sm">{item.productName}</td>
                    <td className="px-4 py-3 text-sm font-mono">{item.orderSpec}</td>
                    <td className="px-4 py-3">
                      <input
                        type="text"
                        value={item.installedSpec || ''}
                        onChange={(e) => handleInspectionResult(item.id, 'installedSpec', e.target.value)}
                        placeholder="실제 시공 규격"
                        className="w-32 px-2 py-1 text-sm border rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                        disabled={item.result !== null}
                      />
                    </td>
                    <td className="px-4 py-3 text-center">
                      {item.specMatch === true && <CheckCircle className="w-5 h-5 text-green-500 mx-auto" />}
                      {item.specMatch === false && <XCircle className="w-5 h-5 text-red-500 mx-auto" />}
                      {item.specMatch === null && <span className="text-gray-300">-</span>}
                    </td>
                    <td className="px-4 py-3 text-center">
                      {item.result === null ? (
                        <div className="flex gap-1 justify-center">
                          <button
                            onClick={() => handleInspectionResult(item.id, 'result', '합격')}
                            className="px-2 py-1 text-xs bg-green-100 text-green-700 rounded hover:bg-green-200"
                          >
                            합격
                          </button>
                          <button
                            onClick={() => handleInspectionResult(item.id, 'result', '불합격')}
                            className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded hover:bg-red-200"
                          >
                            불합격
                          </button>
                        </div>
                      ) : (
                        <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${item.result === '합격' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                          }`}>
                          {item.result}
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <input
                        type="text"
                        value={item.note || ''}
                        onChange={(e) => handleInspectionResult(item.id, 'note', e.target.value)}
                        placeholder="변경사유/비고"
                        className="w-full px-2 py-1 text-sm border rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                      />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      </div>

      {/* 일정변경이력 섹션 */}
      <Card title="일정 변경 이력">
        {inspection.scheduleHistory?.length > 0 ? (
          <div className="space-y-4">
            {inspection.scheduleHistory.map((history, idx) => (
              <div key={idx} className="flex gap-4 p-4 bg-gray-50 rounded-lg">
                <div className="w-2 h-2 mt-2 bg-gray-400 rounded-full flex-shrink-0" />
                <div className="flex-1">
                  <div className="flex items-center justify-between">
                    <span className="font-medium">{history.changeType}</span>
                    <span className="text-sm text-gray-500">{history.changedAt}</span>
                  </div>
                  <p className="text-sm text-gray-600 mt-1">
                    {history.beforeDate} → {history.afterDate}
                  </p>
                  <p className="text-sm text-gray-500 mt-1">사유: {history.reason}</p>
                  <p className="text-xs text-gray-400 mt-1">{history.changedBy}</p>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-8 text-gray-500">
            <Calendar className="w-12 h-12 mx-auto mb-3 text-gray-300" />
            <p>일정 변경 이력이 없습니다.</p>
          </div>
        )}
        <div className="mt-4 p-4 bg-gray-50 rounded-lg text-sm text-gray-600">
          * 검사가 불가능하여 미실시하거나 일정 내에 검사를 완료하지 못한 경우<br />
          * 일정 변경을 등록하고 사유를 기록합니다.
        </div>
      </Card>
    </div>
  );
};

// ============ 사이드바 ============

const Sidebar = ({ activeMenu, onMenuChange, menuConfig, onOpenSettings, currentUser }) => {
  const [expandedMenus, setExpandedMenus] = useState(['master', 'sales', 'production']);

  // 전체 메뉴 정의
  const allMenuGroups = [
    {
      id: 'dashboard',
      label: '대시보드',
      icon: BarChart3,
      isTopLevel: true, // 서브메뉴 없이 바로 클릭
    },
    {
      id: 'master',
      label: '기준정보',
      icon: Settings,
      subMenus: [
        { id: 'item-master', label: '품목기준관리', icon: Layers },
        { id: 'process-master', label: '공정기준관리', icon: GitBranch },
        { id: 'quality-master', label: '품질기준관리', icon: ShieldCheck },
        { id: 'site-master', label: '현장기준관리', icon: MapPin },
        { id: 'order-master', label: '수주기준관리', icon: Package },
        { id: 'production-master', label: '생산기준관리', icon: Factory },
        { id: 'outbound-master', label: '출고기준관리', icon: Truck },
        { id: 'process', label: '공정관리', icon: GitBranch },
        { id: 'number-rule', label: '채번관리', icon: ClipboardList },
        { id: 'code-rule', label: '공통코드관리', icon: Layers },
        { id: 'quote-formula', label: '견적수식관리', icon: Calculator },
        { id: 'document-template', label: '문서양식관리', icon: FileText },
      ],
    },
    {
      id: 'sales',
      label: '판매관리',
      icon: DollarSign,
      subMenus: [
        { id: 'customer', label: '거래처관리', icon: Users },
        { id: 'quote', label: '견적관리', icon: FileText },
        { id: 'order', label: '수주관리', icon: Package },
        { id: 'site', label: '현장관리', icon: Building },
        { id: 'price', label: '단가관리', icon: DollarSign },
      ],
    },
    {
      id: 'production',
      label: '생산관리',
      icon: Factory,
      subMenus: [
        { id: 'item', label: '품목관리', icon: Package },
        { id: 'production-dashboard', label: '생산 현황판', icon: BarChart3 },
        { id: 'work-order', label: '작업지시 관리', icon: ClipboardList },
        { id: 'work-result', label: '작업실적', icon: Clipboard },
        { id: 'worker-task', label: '작업자 화면', icon: User },
      ],
    },
    {
      id: 'quality',
      label: '품질관리',
      icon: ShieldCheck,
      subMenus: [
        { id: 'inspection', label: '검사관리', icon: ShieldCheck },
        { id: 'defect', label: '부적합품관리', icon: XCircle },
      ],
    },
    {
      id: 'inventory',
      label: '자재관리',
      icon: Warehouse,
      subMenus: [
        { id: 'stock', label: '재고현황', icon: Box },
        { id: 'inbound', label: '입고관리', icon: Download },
      ],
    },
    {
      id: 'outbound',
      label: '출고관리',
      icon: Upload,
      subMenus: [
        { id: 'shipment', label: '출하관리', icon: Truck },
      ],
    },
    {
      id: 'accounting',
      label: '회계관리',
      icon: CreditCard,
      subMenus: [
        {
          id: 'acc-customer',
          label: '거래처관리',
          icon: Building,
          depth3: [
            { id: 'acc-customer-list', label: '목록', screenId: 'A0-1' },
            { id: 'acc-customer-register', label: '등록', screenId: 'A0-2' },
            { id: 'acc-customer-edit', label: '수정', screenId: 'A0-3' },
          ]
        },
        {
          id: 'sales-account',
          label: '매출관리',
          icon: BarChart3,
          depth3: [
            { id: 'sales-list', label: '목록', screenId: 'A1' },
            { id: 'sales-statement', label: '거래명세서', screenId: 'A1-1' },
            { id: 'sales-tax-invoice', label: '세금계산서', screenId: 'A1-2' },
          ]
        },
        {
          id: 'purchase',
          label: '매입관리',
          icon: ShoppingCart,
          depth3: [
            { id: 'purchase-list', label: '목록', screenId: 'A2' },
            { id: 'purchase-register', label: '등록', screenId: 'A2-1' },
            { id: 'expense-list', label: '지출결의서목록', screenId: 'A2-2' },
            { id: 'expense-register', label: '지출결의서등록', screenId: 'A2-3' },
            { id: 'expense-estimate', label: '지출예상', screenId: 'A2-4' },
          ]
        },
        {
          id: 'cashbook',
          label: '금전출납부',
          icon: Clipboard,
          depth3: [
            { id: 'cashbook-list', label: '목록', screenId: 'A3' },
            { id: 'cashbook-register', label: '등록', screenId: 'A3-1' },
            { id: 'cashbook-edit', label: '수정', screenId: 'A3-2' },
          ]
        },
        {
          id: 'collection',
          label: '수금관리',
          icon: DollarSign,
          depth3: [
            { id: 'collection-list', label: '목록', screenId: 'A4' },
            { id: 'collection-register', label: '등록', screenId: 'A4-1' },
            { id: 'receivable-list', label: '미수금관리', screenId: 'A4-2' },
            { id: 'bill-list', label: '어음관리', screenId: 'A4-3' },
          ]
        },
        {
          id: 'cost-analysis',
          label: '원가관리',
          icon: Calculator,
          depth3: [
            { id: 'cost-list', label: '목록', screenId: 'A5' },
            { id: 'cost-detail', label: '상세', screenId: 'A5-1' },
          ]
        },
      ],
    },
  ];

  // menuConfig에 따라 메뉴 필터링
  const menuGroups = allMenuGroups
    .filter(group => menuConfig[group.id]?.enabled)
    .map(group => ({
      ...group,
      subMenus: group.subMenus.filter(sub =>
        menuConfig[group.id]?.subMenus?.[sub.id] !== false
      )
    }))
    .filter(group => group.subMenus.length > 0);

  const toggleMenu = (menuId) => {
    setExpandedMenus(prev =>
      prev.includes(menuId)
        ? prev.filter(id => id !== menuId)
        : [...prev, menuId]
    );
  };

  return (
    <aside className="w-64 bg-white border-r h-screen overflow-y-auto flex flex-col">
      {/* 로고 */}
      <div className="p-4 border-b">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-blue-500 rounded-lg flex items-center justify-center text-white font-bold">
            S
          </div>
          <div>
            <h1 className="font-bold text-gray-900">SAM</h1>
            <p className="text-xs text-gray-500">Smart Automation Management</p>
          </div>
        </div>
      </div>

      {/* 메뉴 */}
      <nav className="p-3 space-y-1 flex-1">
        {menuGroups.map(group => (
          <div key={group.id}>
            {/* 대시보드: 서브메뉴 없이 바로 클릭 */}
            {group.isTopLevel ? (
              <button
                onClick={() => onMenuChange(group.id)}
                className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors
                  ${activeMenu === 'dashboard' ? 'bg-blue-500 text-white' : 'text-gray-700 hover:bg-gray-100'}`}
              >
                <group.icon className="w-5 h-5" />
                {group.label}
              </button>
            ) : (
              <>
                <button
                  onClick={() => toggleMenu(group.id)}
                  className={`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-sm font-medium transition-colors
                    ${expandedMenus.includes(group.id) ? 'bg-blue-50 text-blue-700' : 'text-gray-700 hover:bg-gray-100'}`}
                >
                  <div className="flex items-center gap-3">
                    <group.icon className="w-5 h-5" />
                    {group.label}
                  </div>
                  {expandedMenus.includes(group.id) ? (
                    <ChevronDown className="w-4 h-4" />
                  ) : (
                    <ChevronRight className="w-4 h-4" />
                  )}
                </button>
                {expandedMenus.includes(group.id) && group.subMenus && (
                  <div className="mt-1 ml-5 space-y-0.5">
                    {group.subMenus.map(sub => (
                      <div key={sub.id}>
                        {/* Depth3가 있는 메뉴 */}
                        {sub.depth3 ? (
                          <>
                            <button
                              onClick={() => toggleMenu(sub.id)}
                              className={`w-full flex items-center justify-between px-3 py-2 rounded-lg text-sm transition-colors
                                ${expandedMenus.includes(sub.id) ? 'bg-gray-100 text-gray-900' : 'text-gray-600 hover:bg-gray-100'}`}
                            >
                              <div className="flex items-center gap-3">
                                <sub.icon className="w-4 h-4" />
                                {sub.label}
                              </div>
                              {expandedMenus.includes(sub.id) ? (
                                <ChevronDown className="w-3 h-3" />
                              ) : (
                                <ChevronRight className="w-3 h-3" />
                              )}
                            </button>
                            {expandedMenus.includes(sub.id) && (
                              <div className="mt-0.5 ml-4 space-y-0.5">
                                {sub.depth3.map(d3 => (
                                  <button
                                    key={d3.id}
                                    onClick={() => onMenuChange(d3.id)}
                                    className={`w-full flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs transition-colors
                                      ${activeMenu === d3.id
                                        ? 'bg-blue-500 text-white'
                                        : 'text-gray-500 hover:bg-gray-100'}`}
                                  >
                                    <span className="w-1 h-1 rounded-full bg-current" />
                                    {d3.label}
                                  </button>
                                ))}
                              </div>
                            )}
                          </>
                        ) : (
                          /* Depth3가 없는 메뉴 */
                          <button
                            onClick={() => onMenuChange(sub.id)}
                            className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors
                              ${activeMenu === sub.id
                                ? 'bg-blue-500 text-white'
                                : 'text-gray-600 hover:bg-gray-100'}`}
                          >
                            <sub.icon className="w-4 h-4" />
                            {sub.label}
                          </button>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </>
            )}
          </div>
        ))}
      </nav>

      {/* 공통 UX 버튼 */}
      <div className="p-3 border-t">
        <button
          onClick={() => onMenuChange('common-ux')}
          className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${activeMenu === 'common-ux' ? 'bg-purple-500 text-white' : 'text-purple-700 hover:bg-purple-50 border border-purple-200'
            }`}
        >
          <Layers className="w-5 h-5" />
          공통 UX
        </button>
      </div>

      {/* 통합 테스트 버튼 */}
      <div className="p-3 border-t">
        <button
          onClick={() => onMenuChange('integrated-test')}
          className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${activeMenu === 'integrated-test' ? 'bg-green-500 text-white' : 'text-green-700 hover:bg-green-50 border border-green-200'
            }`}
        >
          <Database className="w-5 h-5" />
          통합 테스트
        </button>
      </div>

      {/* 설정 버튼 */}
      <div className="p-3 border-t">
        <button
          onClick={onOpenSettings}
          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm text-gray-600 hover:bg-gray-100 transition-colors"
        >
          <Settings className="w-5 h-5" />
          메뉴 설정
        </button>
      </div>
    </aside>
  );
};

// ============ 메뉴 설정 화면 ============

const MenuSettings = ({ menuConfig, onSave, onClose }) => {
  const [config, setConfig] = useState(menuConfig);
  const [selectedRole, setSelectedRole] = useState('custom');

  // 역할별 프리셋
  const rolePresets = {
    sales: {
      label: '판매팀',
      config: {
        sales: { enabled: true, subMenus: { customer: true, quote: true, order: true, site: true, price: true } },
        outbound: { enabled: true, subMenus: { shipment: true } },
        production: { enabled: false },
        quality: { enabled: false },
        inventory: { enabled: false },
        accounting: { enabled: false },
      }
    },
    shipping: {
      label: '출고팀',
      config: {
        sales: { enabled: false },
        outbound: { enabled: true, subMenus: { shipment: true } },
        production: { enabled: false },
        quality: { enabled: false },
        inventory: { enabled: true, subMenus: { stock: true, inbound: true, outbound: true } },
        accounting: { enabled: false },
      }
    },
    production: {
      label: '생산팀',
      config: {
        sales: { enabled: true, subMenus: { order: true } },
        outbound: { enabled: false },
        production: { enabled: true, subMenus: { 'production-dashboard': true, 'work-order': true, 'work-result': true, 'worker-task': true } },
        quality: { enabled: true, subMenus: { inspection: true, defect: true } },
        inventory: { enabled: true, subMenus: { stock: true, inbound: true, outbound: true } },
        accounting: { enabled: false },
      }
    },
    accounting: {
      label: '회계팀',
      config: {
        sales: { enabled: true, subMenus: { order: true } },
        outbound: { enabled: true, subMenus: { shipment: true } },
        production: { enabled: false },
        quality: { enabled: false },
        inventory: { enabled: false },
        accounting: { enabled: true, subMenus: { 'acc-customer': true, 'sales-account': true, purchase: true, cashbook: true, collection: true, 'cost-analysis': true } },
      }
    },
    admin: {
      label: '관리자 (전체)',
      config: {
        sales: { enabled: true, subMenus: { customer: true, quote: true, order: true, site: true, price: true } },
        outbound: { enabled: true, subMenus: { shipment: true } },
        production: { enabled: true, subMenus: { 'production-dashboard': true, 'work-order': true, 'work-result': true, 'worker-task': true } },
        quality: { enabled: true, subMenus: { inspection: true, defect: true } },
        inventory: { enabled: true, subMenus: { stock: true, inbound: true, outbound: true } },
        accounting: { enabled: true, subMenus: { 'acc-customer': true, 'sales-account': true, purchase: true, cashbook: true, collection: true, 'cost-analysis': true } },
      }
    },
  };

  const menuDefinitions = [
    {
      id: 'master',
      label: '기준정보',
      icon: Settings,
      subMenus: [
        { id: 'item-master', label: '품목기준관리' },
        { id: 'process-master', label: '공정기준관리' },
        { id: 'quality-master', label: '품질기준관리' },
        { id: 'customer-master', label: '거래처기준관리' },
        { id: 'site-master', label: '현장기준관리' },
        { id: 'order-master', label: '수주기준관리' },
        { id: 'process', label: '공정관리' },
        { id: 'number-rule', label: '채번관리' },
        { id: 'code-rule', label: '공통코드관리' },
      ],
    },
    {
      id: 'sales',
      label: '판매관리',
      icon: DollarSign,
      subMenus: [
        { id: 'customer', label: '거래처관리' },
        { id: 'quote', label: '견적관리' },
        { id: 'order', label: '수주관리' },
        { id: 'site', label: '현장관리' },
        { id: 'price', label: '단가관리' },
        { id: 'shipment', label: '출하관리' },
      ],
    },
    {
      id: 'production',
      label: '생산관리',
      icon: Factory,
      subMenus: [
        { id: 'item', label: '품목관리' },
        { id: 'production-dashboard', label: '생산 현황판' },
        { id: 'work-order', label: '작업지시 관리' },
        { id: 'work-result', label: '작업실적' },
        { id: 'worker-task', label: '작업자 화면' },
      ],
    },
    {
      id: 'quality',
      label: '품질관리',
      icon: ShieldCheck,
      subMenus: [
        { id: 'inspection', label: '검사관리' },
        { id: 'defect', label: '부적합품관리' },
      ],
    },
    {
      id: 'inventory',
      label: '자재관리',
      icon: Warehouse,
      subMenus: [
        { id: 'stock', label: '재고현황' },
        { id: 'inbound', label: '입고관리' },
      ],
    },
    {
      id: 'accounting',
      label: '회계관리',
      icon: CreditCard,
      subMenus: [
        { id: 'acc-customer', label: '거래처관리' },
        { id: 'sales-account', label: '매출관리' },
        { id: 'purchase', label: '매입관리' },
        { id: 'cashbook', label: '금전출납부' },
        { id: 'collection', label: '수금관리' },
        { id: 'cost-analysis', label: '원가관리' },
      ],
    },
  ];

  const handleRoleChange = (role) => {
    setSelectedRole(role);
    if (role !== 'custom') {
      setConfig(rolePresets[role].config);
    }
  };

  const toggleGroup = (groupId) => {
    setSelectedRole('custom');
    setConfig(prev => ({
      ...prev,
      [groupId]: {
        ...prev[groupId],
        enabled: !prev[groupId]?.enabled
      }
    }));
  };

  const toggleSubMenu = (groupId, subId) => {
    setSelectedRole('custom');
    setConfig(prev => ({
      ...prev,
      [groupId]: {
        ...prev[groupId],
        subMenus: {
          ...prev[groupId]?.subMenus,
          [subId]: prev[groupId]?.subMenus?.[subId] === false ? true : false
        }
      }
    }));
  };

  const handleSave = () => {
    onSave(config);
    onClose();
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl w-full max-w-3xl max-h-[80vh] overflow-hidden">
        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b">
          <div className="flex items-center gap-3">
            <Settings className="w-6 h-6 text-blue-500" />
            <h2 className="text-lg font-bold text-gray-900">메뉴 설정</h2>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg">
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* 역할 프리셋 */}
        <div className="p-4 border-b bg-gray-50">
          <p className="text-sm text-gray-600 mb-3">역할별 프리셋을 선택하거나 직접 설정하세요</p>
          <div className="flex flex-wrap gap-2">
            {Object.entries(rolePresets).map(([key, preset]) => (
              <button
                key={key}
                onClick={() => handleRoleChange(key)}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${selectedRole === key
                    ? 'bg-blue-500 text-white'
                    : 'bg-white border border-gray-200 text-gray-700 hover:border-blue-300'
                  }`}
              >
                {preset.label}
              </button>
            ))}
            <button
              onClick={() => setSelectedRole('custom')}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${selectedRole === 'custom'
                  ? 'bg-blue-500 text-white'
                  : 'bg-white border border-gray-200 text-gray-700 hover:border-blue-300'
                }`}
            >
              직접 설정
            </button>
          </div>
        </div>

        {/* 메뉴 설정 */}
        <div className="p-4 overflow-y-auto max-h-[400px]">
          <div className="space-y-4">
            {menuDefinitions.map(group => {
              const GroupIcon = group.icon;
              const isEnabled = config[group.id]?.enabled;

              return (
                <div key={group.id} className={`border rounded-lg ${isEnabled ? 'border-blue-200 bg-blue-50/50' : 'border-gray-200'}`}>
                  {/* 대메뉴 */}
                  <div className="flex items-center justify-between p-3">
                    <div className="flex items-center gap-3">
                      <GroupIcon className={`w-5 h-5 ${isEnabled ? 'text-blue-600' : 'text-gray-400'}`} />
                      <span className={`font-medium ${isEnabled ? 'text-gray-900' : 'text-gray-500'}`}>
                        {group.label}
                      </span>
                    </div>
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={isEnabled}
                        onChange={() => toggleGroup(group.id)}
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-500"></div>
                    </label>
                  </div>

                  {/* 서브메뉴 */}
                  {isEnabled && (
                    <div className="px-3 pb-3">
                      <div className="flex flex-wrap gap-2 ml-8">
                        {group.subMenus.map(sub => {
                          const isSubEnabled = config[group.id]?.subMenus?.[sub.id] !== false;
                          return (
                            <button
                              key={sub.id}
                              onClick={() => toggleSubMenu(group.id, sub.id)}
                              className={`px-3 py-1.5 rounded-full text-sm transition-colors ${isSubEnabled
                                  ? 'bg-blue-100 text-blue-700'
                                  : 'bg-gray-100 text-gray-400 line-through'
                                }`}
                            >
                              {sub.label}
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* 푸터 */}
        <div className="flex items-center justify-end gap-2 p-4 border-t bg-gray-50">
          <Button variant="outline" onClick={onClose}>취소</Button>
          <Button variant="primary" onClick={handleSave}>
            <Check className="w-4 h-4" /> 저장
          </Button>
        </div>
      </div>
    </div>
  );
};

// ============ 메인 앱 ============

export default function App() {
  const [activeMenu, setActiveMenu] = useState('dashboard');
  const [view, setView] = useState('dashboard');
  const [selectedItem, setSelectedItem] = useState(null);
  const [selectedData, setSelectedData] = useState(null);
  const [showSettings, setShowSettings] = useState(false);
  const [showMobileMenu, setShowMobileMenu] = useState(false);

  // ═══════════════════════════════════════════════════════════════════
  // 와이어프레임 모드 (기본 활성화)
  // ═══════════════════════════════════════════════════════════════════
  const wireframeMode = true; // 와이어프레임 모드 항상 활성화

  // ═══════════════════════════════════════════════════════════════════
  // 닉네임 시스템 (사용자 식별)
  // ═══════════════════════════════════════════════════════════════════
  const [userNickname, setUserNickname] = useState(() => {
    return localStorage.getItem('userNickname') || null;
  });
  const [showNicknameModal, setShowNicknameModal] = useState(false);

  // 닉네임 저장 (기존 뱃지들의 author도 함께 변경)
  const saveNickname = (nickname) => {
    const oldNickname = userNickname;
    localStorage.setItem('userNickname', nickname);
    setUserNickname(nickname);
    setShowNicknameModal(false);

    // 기존 닉네임이 있고, 새 닉네임과 다르면 모든 뱃지의 author 업데이트
    if (oldNickname && oldNickname !== nickname) {
      setFeatureBadges(prevBadges => {
        const updatedBadges = {};
        Object.keys(prevBadges).forEach(screenKey => {
          updatedBadges[screenKey] = prevBadges[screenKey].map(badge => {
            // 이전 닉네임으로 작성된 뱃지만 업데이트
            if (badge.author === oldNickname) {
              return { ...badge, author: nickname };
            }
            return badge;
          });
        });
        return updatedBadges;
      });
    }
  };

  // 처음 접속 시 닉네임 입력 모달 표시
  useEffect(() => {
    if (!userNickname) {
      setShowNicknameModal(true);
    }
  }, [userNickname]);

  // ═══════════════════════════════════════════════════════════════════
  // 기능정의서 시스템 (Feature Description System)
  // ═══════════════════════════════════════════════════════════════════
  const [showFeatureDescription, setShowFeatureDescription] = useState(false);
  // 현재 열린 모달/다이얼로그 추적 (기능정의서 뱃지 용)
  const [activeModal, setActiveModal] = useState(null);
  const [isFeatureAdmin, setIsFeatureAdmin] = useState(() => {
    return localStorage.getItem('featureAdmin') === 'true';
  });
  const [showAdminPasswordModal, setShowAdminPasswordModal] = useState(false);
  const [adminPassword, setAdminPassword] = useState('');
  const [adminPasswordError, setAdminPasswordError] = useState('');

  // 기능정의서 어드민 상태 저장
  useEffect(() => {
    localStorage.setItem('featureAdmin', isFeatureAdmin.toString());
  }, [isFeatureAdmin]);

  // 기능정의서 토글 핸들러 (최초 접근 시 비밀번호 요청)
  const handleToggleFeatureDescription = () => {
    if (showFeatureDescription) {
      // 이미 열려있으면 그냥 닫기
      setShowFeatureDescription(false);
    } else {
      // 최초 열 때 비밀번호 모달 표시
      setShowAdminPasswordModal(true);
      setAdminPassword('');
      setAdminPasswordError('');
    }
  };

  // 어드민 비밀번호 확인
  const handleAdminPasswordSubmit = () => {
    if (adminPassword === '4321') {
      setIsFeatureAdmin(true);
      setShowAdminPasswordModal(false);
      setShowFeatureDescription(true);
      setAdminPassword('');
      setAdminPasswordError('');
    } else if (adminPassword === '') {
      // 빈 입력 또는 일반 사용자로 진입
      setIsFeatureAdmin(false);
      setShowAdminPasswordModal(false);
      setShowFeatureDescription(true);
      setAdminPassword('');
    } else {
      setAdminPasswordError('비밀번호가 일치하지 않습니다.');
    }
  };

  // 현재 뱃지 데이터 (로컬 JSON 파일에서 로드)
  const [featureBadges, setFeatureBadges] = useState({});
  const [badgeMetadata, setBadgeMetadata] = useState({
    version: '1.0.0',
    lastModified: null,
    author: 'system'
  });
  const [isLoadingBadges, setIsLoadingBadges] = useState(true);

  // 컴포넌트 마운트 시 로컬 JSON 파일에서 데이터 로드
  useEffect(() => {
    const loadInitialData = async () => {
      setIsLoadingBadges(true);
      try {
        // 1. 먼저 localStorage의 임시 데이터 확인 (가장 최신)
        const tempData = localStorage.getItem('featureBadges_temp');
        if (tempData) {
          const parsed = JSON.parse(tempData);
          setFeatureBadges(parsed.badges || {});
          setBadgeMetadata(parsed.metadata || { version: '1.0.0', lastModified: null, author: 'system' });
          console.log('✅ localStorage에서 기능정의서 데이터 로드됨');
        } else {
          // 2. localStorage 없으면 JSON 파일에서 로드
          const data = await loadFeatureBadges();
          setFeatureBadges(data.badges || {});
          setBadgeMetadata(data.metadata || { version: '1.0.0', lastModified: null, author: 'system' });
          console.log('✅ JSON 파일에서 기능정의서 데이터 로드됨');
        }
      } catch (error) {
        console.error('기능정의서 데이터 로드 실패:', error);
      } finally {
        setIsLoadingBadges(false);
      }
    };
    loadInitialData();
  }, []);

  // 뱃지 데이터 변경 시 자동 저장 (디바운스 적용)
  useEffect(() => {
    if (isLoadingBadges) return; // 초기 로딩 중에는 저장 안함

    const autoSaveTimer = setTimeout(async () => {
      try {
        // 로컬 스토리지에 임시 저장 (빠른 복구용)
        localStorage.setItem('featureBadges_temp', JSON.stringify({
          badges: featureBadges,
          metadata: {
            ...badgeMetadata,
            lastModified: new Date().toISOString()
          }
        }));

        console.log('✅ 기능정의서 데이터 자동 저장됨 (로컬 스토리지)');
      } catch (error) {
        console.error('❌ 자동 저장 실패:', error);
      }
    }, 2000); // 2초 디바운스

    return () => clearTimeout(autoSaveTimer);
  }, [featureBadges, isLoadingBadges]);

  // ═══════════════════════════════════════════════════════════════════
  // 기능정의문서 패널 시스템 (UI별 기능 정의 조회)
  // ═══════════════════════════════════════════════════════════════════
  const [showFeatureDocPanel, setShowFeatureDocPanel] = useState(false);
  const [hoveredBadgeNumber, setHoveredBadgeNumber] = useState(null);

  // ═══════════════════════════════════════════════════════════════════
  // 버전 히스토리 시스템 (Git 스타일 버전 관리)
  // ═══════════════════════════════════════════════════════════════════
  const [showVersionHistory, setShowVersionHistory] = useState(false);

  // ═══════════════════════════════════════════════════════════════════
  // 유저플로우 패널 시스템 (모달 대신 우측 패널 사용)
  // ═══════════════════════════════════════════════════════════════════
  const [showUserFlow, setShowUserFlow] = useState(false);
  const [showFlowPanel, setShowFlowPanel] = useState(false);

  // ═══════════════════════════════════════════════════════════════════
  // 종합 플로우차트 및 전체 메뉴 기능정의서 패널
  // ═══════════════════════════════════════════════════════════════════
  const [showComprehensiveFlowPanel, setShowComprehensiveFlowPanel] = useState(false);
  const [comprehensiveFlowPanelWidth, setComprehensiveFlowPanelWidth] = useState(600); // 드래그 가능한 패널 너비
  const [showAllMenuFeatureDocPanel, setShowAllMenuFeatureDocPanel] = useState(false);
  const [showAllFeatureBadgesViewer, setShowAllFeatureBadgesViewer] = useState(false); // 전체 기능정의서 조회 모달

  // ═══════════════════════════════════════════════════════════════════
  // 상세 플로우 다이어그램 (ReactFlow 기반)
  // ═══════════════════════════════════════════════════════════════════
  const [showDetailedFlowDiagram, setShowDetailedFlowDiagram] = useState(false);
  const [detailedFlowType, setDetailedFlowType] = useState('quote-to-shipment');

  // ═══════════════════════════════════════════════════════════════════
  // 작업자 화면 자재투입 모달 상태
  // ═══════════════════════════════════════════════════════════════════
  const [showWorkerMaterialModal, setShowWorkerMaterialModal] = useState(false);
  const [workerMaterialTask, setWorkerMaterialTask] = useState(null);

  // ★ 자재 투입 시 재고 감소 핸들러
  const handleUseMaterial = (materialCode, qty, usage) => {
    setInventory(prev => prev.map(item =>
      item.materialCode === materialCode
        ? { ...item, stock: Math.max(0, item.stock - qty), lastUpdated: new Date().toISOString().split('T')[0] }
        : item
    ));
    console.log('자재 사용:', { materialCode, qty, usage });
  };

  // ═══════════════════════════════════════════════════════════════════
  // 공유 품목 마스터 상태 (품목관리 ↔ 단가관리 연동)
  // ═══════════════════════════════════════════════════════════════════
  const [sharedItems, setSharedItems] = useState(() => {
    // initialItems와 동일한 구조로 초기화
    return itemPriceMaster.map((item, idx) => ({
      id: idx + 1,
      itemCode: item.itemCode,
      itemName: item.itemName,
      category: item.category,
      itemType: item.category.includes('절곡') || item.category.includes('가이드') || item.category.includes('케이스') || item.category.includes('하단') || item.category.includes('연기') ? '반제품' :
        item.category.includes('전동') || item.category.includes('연동') || item.category.includes('샤프트') || item.category.includes('브라켓') || item.category.includes('앵글') ? '부품' :
          item.category.includes('검사') ? '서비스' : '원자재',
      unit: item.unit,
      spec: item.itemName.match(/\d+/) ? item.itemName.match(/[\d×\-]+/)?.[0] || '-' : '-',
      safetyStock: Math.floor(Math.random() * 20) + 5,
      currentStock: Math.floor(Math.random() * 50) + 10,
      leadTime: Math.floor(Math.random() * 7) + 1,
      isActive: true,
      createdAt: '2024-01-01',
      // 단가 정보
      purchasePrice: item.unitPrice || 0,
      sellingPrice: item.sellingPrice || 0,
      processingCost: 0,
      lossRate: 0,
      marginRate: item.sellingPrice && item.unitPrice ? Math.round((item.sellingPrice - item.unitPrice) / item.unitPrice * 100) : 20,
    }));
  });

  // 품목 추가 핸들러 (품목관리에서 호출)
  const handleAddItem = (newItem) => {
    const maxId = sharedItems.reduce((max, item) => Math.max(max, item.id), 0);
    const itemWithId = { ...newItem, id: maxId + 1, createdAt: new Date().toISOString().slice(0, 10) };
    setSharedItems(prev => [...prev, itemWithId]);
    return itemWithId;
  };

  // 품목 수정 핸들러 (품목관리에서 호출)
  const handleUpdateItem = (updatedItem) => {
    setSharedItems(prev => prev.map(item => item.id === updatedItem.id ? { ...item, ...updatedItem } : item));
  };

  // 품목 삭제 핸들러 (품목관리에서 호출)
  const handleDeleteItem = (itemId) => {
    setSharedItems(prev => prev.filter(item => item.id !== itemId));
  };

  // 단가 정보 업데이트 핸들러 (단가관리에서 호출)
  const handleUpdatePrice = (priceDataArray) => {
    // 단가관리에서 업데이트된 정보를 품목 마스터에 반영
    setSharedItems(prev => prev.map(item => {
      const priceInfo = priceDataArray.find(p => p.itemCode === item.itemCode);
      if (priceInfo) {
        return {
          ...item,
          purchasePrice: priceInfo.purchasePrice,
          sellingPrice: priceInfo.sellingPrice,
          processingCost: priceInfo.processingCost,
          lossRate: priceInfo.lossRate,
          marginRate: priceInfo.marginRate,
        };
      }
      return item;
    }));
  };

  // 버전 히스토리 목록
  const [versionHistory, setVersionHistory] = useState(() => {
    const saved = localStorage.getItem('versionHistory');
    return saved ? JSON.parse(saved) : [];
  });

  // 마지막 커밋된 스냅샷 (변경 감지용)
  const [lastCommittedSnapshot, setLastCommittedSnapshot] = useState(() => {
    const saved = localStorage.getItem('lastCommittedSnapshot');
    return saved ? JSON.parse(saved) : null;
  });

  // 버전 히스토리 저장
  useEffect(() => {
    localStorage.setItem('versionHistory', JSON.stringify(versionHistory));
  }, [versionHistory]);

  // 마지막 커밋 스냅샷 저장
  useEffect(() => {
    if (lastCommittedSnapshot) {
      localStorage.setItem('lastCommittedSnapshot', JSON.stringify(lastCommittedSnapshot));
    }
  }, [lastCommittedSnapshot]);

  // 현재 버전 번호
  const currentVersion = versionHistory.length > 0 ? versionHistory[0].version : 0;

  // 변경사항 있는지 확인
  const hasChanges = React.useMemo(() => {
    if (!lastCommittedSnapshot) return Object.keys(featureBadges).length > 0;
    return JSON.stringify(featureBadges) !== JSON.stringify(lastCommittedSnapshot);
  }, [featureBadges, lastCommittedSnapshot]);

  // 변경사항 요약 생성 (상세)
  const generateChangeSummary = React.useCallback((oldBadges, newBadges) => {
    const allScreens = new Set([...Object.keys(oldBadges || {}), ...Object.keys(newBadges || {})]);

    let addedCount = 0;
    let removedCount = 0;
    let modifiedCount = 0;
    const changeDetails = []; // 상세 변경 내역

    // 화면 이름 변환 맵
    const screenNameMap = {
      'dashboard': '대시보드',
      'quote': '견적관리',
      'order': '수주관리',
      'customer': '거래처관리',
      'shipment': '출하관리',
      'production': '생산계획',
      'workOrder': '작업지시',
      'workResult': '작업실적',
      'inventory': '재고관리',
      'inspection': '품질검사',
      'defect': '불량관리',
      'accounting': '회계관리',
      'collection': '수금관리',
      'cost': '원가관리',
      'system': '시스템설정',
      'masterConfig': '기준정보설정',
      'itemMaster': '품목기준관리',
      'processMaster': '공정기준관리',
      'qualityMaster': '품질기준관리',
      'customerMaster': '거래처기준관리',
      'orderMaster': '수주기준관리',
      'documentTemplate': '문서양식관리',
    };

    const getScreenDisplayName = (screen) => {
      const [menu, viewType] = screen.split('-');
      const menuName = screenNameMap[menu] || menu;
      const viewName = viewType === 'list' ? '목록' : viewType === 'detail' ? '상세' : viewType === 'create' ? '등록' : viewType === 'edit' ? '수정' : viewType || '';
      return viewName ? `${menuName} ${viewName}` : menuName;
    };

    allScreens.forEach(screen => {
      const oldList = oldBadges?.[screen] || [];
      const newList = newBadges?.[screen] || [];

      const oldIds = new Set(oldList.map(b => b.id));
      const newIds = new Set(newList.map(b => b.id));

      const screenDisplayName = getScreenDisplayName(screen);
      const screenChanges = { added: [], removed: [], modified: [] };

      // 추가된 뱃지
      newList.forEach(b => {
        if (!oldIds.has(b.id)) {
          addedCount++;
          screenChanges.added.push(b.label || `#${b.number || '?'}`);
        }
      });

      // 삭제된 뱃지
      oldList.forEach(b => {
        if (!newIds.has(b.id)) {
          removedCount++;
          screenChanges.removed.push(b.label || `#${b.number || '?'}`);
        }
      });

      // 수정된 뱃지
      newList.forEach(newB => {
        const oldB = oldList.find(b => b.id === newB.id);
        if (oldB && JSON.stringify(oldB) !== JSON.stringify(newB)) {
          modifiedCount++;
          screenChanges.modified.push(newB.label || `#${newB.number || '?'}`);
        }
      });

      // 화면별 상세 변경 내역 추가
      if (screenChanges.added.length || screenChanges.removed.length || screenChanges.modified.length) {
        const details = [];
        if (screenChanges.added.length) {
          details.push(`추가: ${screenChanges.added.join(', ')}`);
        }
        if (screenChanges.removed.length) {
          details.push(`삭제: ${screenChanges.removed.join(', ')}`);
        }
        if (screenChanges.modified.length) {
          details.push(`수정: ${screenChanges.modified.join(', ')}`);
        }
        changeDetails.push(`[${screenDisplayName}] ${details.join(' / ')}`);
      }
    });

    // 요약 생성
    const summaryParts = [];
    if (addedCount > 0) summaryParts.push(`${addedCount}개 추가`);
    if (removedCount > 0) summaryParts.push(`${removedCount}개 삭제`);
    if (modifiedCount > 0) summaryParts.push(`${modifiedCount}개 수정`);

    const totalSummary = summaryParts.length > 0 ? summaryParts.join(', ') : '변경없음';
    const detailText = changeDetails.length > 0 ? '\n' + changeDetails.join('\n') : '';

    return `${totalSummary}${detailText}`;
  }, []);

  // 자동 커밋 메시지 생성
  const autoCommitMessage = React.useMemo(() => {
    if (!hasChanges) return '';
    return generateChangeSummary(lastCommittedSnapshot, featureBadges);
  }, [hasChanges, lastCommittedSnapshot, featureBadges, generateChangeSummary]);

  // 새 버전 커밋
  const commitVersion = (message) => {
    const newVersion = currentVersion + 1;
    const summary = generateChangeSummary(lastCommittedSnapshot, featureBadges);

    const newCommit = {
      id: Date.now(),
      version: newVersion,
      message,
      summary,
      author: userNickname || '익명',
      timestamp: new Date().toISOString(),
      snapshot: JSON.parse(JSON.stringify(featureBadges)) // 깊은 복사
    };

    setVersionHistory(prev => [newCommit, ...prev]);
    setLastCommittedSnapshot(JSON.parse(JSON.stringify(featureBadges)));

    // 공유용 커밋된 데이터 저장 (다른 사용자가 볼 수 있음)
    localStorage.setItem('featureBadges_committed', JSON.stringify(featureBadges));

    alert(`v${newVersion} 커밋 완료!\n${summary}`);
  };

  // 이전 버전으로 롤백
  const rollbackToVersion = (commitId) => {
    const targetCommit = versionHistory.find(v => v.id === commitId);
    if (!targetCommit) return;

    setFeatureBadges(JSON.parse(JSON.stringify(targetCommit.snapshot)));
    setLastCommittedSnapshot(JSON.parse(JSON.stringify(targetCommit.snapshot)));
    alert(`v${targetCommit.version}로 롤백되었습니다.`);
    setShowVersionHistory(false);
  };

  // 다른 사용자의 최신 커밋 로드 (새로고침 시)
  useEffect(() => {
    const loadLatestCommit = () => {
      const committed = localStorage.getItem('featureBadges_committed');
      if (committed && !lastCommittedSnapshot) {
        const data = JSON.parse(committed);
        setFeatureBadges(data);
        setLastCommittedSnapshot(data);
      }
    };
    loadLatestCommit();
  }, []);

  const [isAddingBadge, setIsAddingBadge] = useState(false);
  const [selectedBadge, setSelectedBadge] = useState(null);
  const [badgeEditMode, setBadgeEditMode] = useState(false);

  // 새로운 UX: C키 → 클릭 → 인라인 입력
  const [isPlacingBadge, setIsPlacingBadge] = useState(false); // C키 누른 후 클릭 대기 상태
  const [inlineInputPosition, setInlineInputPosition] = useState(null); // 클릭한 위치에 입력창 표시
  const [nextBadgeNumber, setNextBadgeNumber] = useState(1); // 다음 뱃지 번호
  const contentAreaRef = React.useRef(null); // 콘텐츠 영역 ref
  const [scrollState, setScrollState] = useState({ top: 0, height: 0 }); // 스크롤 상태 추적
  const [contentAreaBounds, setContentAreaBounds] = useState({ top: 0, left: 0, width: 0, height: 0 }); // 콘텐츠 영역 위치

  // 스크롤 및 레이아웃 이벤트 리스너 - 뱃지 오버레이 위치 동기화
  useEffect(() => {
    const contentArea = contentAreaRef.current;
    if (!contentArea || !showFeatureDescription) return;

    const updateState = () => {
      const rect = contentArea.getBoundingClientRect();
      setScrollState({
        top: contentArea.scrollTop,
        height: contentArea.scrollHeight
      });
      setContentAreaBounds({
        top: rect.top,
        left: rect.left,
        width: contentArea.clientWidth,
        height: contentArea.clientHeight
      });
    };

    // 초기 상태 설정
    updateState();

    contentArea.addEventListener('scroll', updateState);
    window.addEventListener('resize', updateState);

    // ResizeObserver로 콘텐츠 영역 크기 변화 감지
    const resizeObserver = new ResizeObserver(updateState);
    resizeObserver.observe(contentArea);

    return () => {
      contentArea.removeEventListener('scroll', updateState);
      window.removeEventListener('resize', updateState);
      resizeObserver.disconnect();
    };
  }, [showFeatureDescription]);

  // 현재 화면의 다음 번호 계산
  const getNextBadgeNumber = React.useCallback(() => {
    const screenKey = `${activeMenu}-${view}`;
    const currentBadges = featureBadges[screenKey] || [];
    if (currentBadges.length === 0) return 1;
    const maxNumber = Math.max(...currentBadges.map(b => b.number || 0));
    return maxNumber + 1;
  }, [activeMenu, view, featureBadges]);

  // 키보드 C 단축키 (기능정의서 활성화 시) - 클릭 대기 모드로 전환
  useEffect(() => {
    if (!showFeatureDescription) return;

    const handleKeyDown = (e) => {
      // 입력 필드에서는 무시
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT') {
        return;
      }

      if (e.key === 'c' || e.key === 'C') {
        e.preventDefault();
        // 편집 모드 자동 활성화
        if (!badgeEditMode) {
          setBadgeEditMode(true);
        }
        // 클릭 대기 모드 활성화
        setIsPlacingBadge(true);
        setNextBadgeNumber(getNextBadgeNumber());
      }

      // ESC로 취소
      if (e.key === 'Escape') {
        setIsPlacingBadge(false);
        setInlineInputPosition(null);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [showFeatureDescription, badgeEditMode, getNextBadgeNumber]);

  // 클릭 대기 모드에서 클릭 시 위치 지정
  const handleContentAreaClick = (e) => {
    if (!isPlacingBadge || !contentAreaRef.current) return;

    const rect = contentAreaRef.current.getBoundingClientRect();
    const scrollTop = contentAreaRef.current.scrollTop;
    const scrollLeft = contentAreaRef.current.scrollLeft;

    // 스크롤 위치를 포함한 절대 픽셀 좌표로 저장
    const absoluteX = e.clientX - rect.left + scrollLeft;
    const absoluteY = e.clientY - rect.top + scrollTop;

    // 클릭한 위치에 인라인 입력창 표시
    setInlineInputPosition({
      x: ((e.clientX - rect.left) / rect.width) * 100, // 팝업 위치용 (화면 비율)
      y: ((e.clientY - rect.top) / rect.height) * 100,
      absoluteX, // 뱃지 저장용 (절대 픽셀)
      absoluteY,
      scrollTop,
      clientX: e.clientX,
      clientY: e.clientY,
    });
    setIsPlacingBadge(false);
  };

  // 현재 화면의 뱃지들 가져오기
  const getCurrentScreenBadges = () => {
    const screenKey = `${activeMenu}-${view}`;
    return featureBadges[screenKey] || [];
  };

  // 기능 추출 함수 - 현재 화면에 대한 자동 기능 분석
  const extractFeatures = React.useCallback(() => {
    const screenKey = `${activeMenu}-${view}`;
    const currentBadges = featureBadges[screenKey] || [];
    const template = getScreenFeatureTemplate(activeMenu);

    if (!template) {
      alert(`'${activeMenu}' 화면에 대한 기능 정의 템플릿이 없습니다.\n수동으로 뱃지를 추가해주세요.`);
      return;
    }

    if (currentBadges.length > 0) {
      const confirmReplace = window.confirm(
        `현재 화면에 ${currentBadges.length}개의 뱃지가 있습니다.\n` +
        `기존 뱃지를 모두 삭제하고 자동 추출된 ${template.features.length}개의 기능으로 교체하시겠습니까?`
      );
      if (!confirmReplace) return;
    }

    const contentArea = contentAreaRef.current;
    if (!contentArea) {
      alert('콘텐츠 영역을 찾을 수 없습니다.');
      return;
    }
    const contentWidth = contentArea.scrollWidth;
    const contentHeight = contentArea.scrollHeight;

    const newBadges = template.features.map((feature, index) => {
      const absoluteX = (feature.position.x / 100) * contentWidth;
      const absoluteY = (feature.position.y / 100) * contentHeight;
      let description = '';

      // 액션 정보 (버튼/요소 클릭 시 어떤 동작이 일어나는지)
      if (feature.action) {
        description += `【액션】\n`;
        if (feature.action.trigger) description += `• 트리거: ${feature.action.trigger}\n`;
        if (feature.action.behavior) description += `• 동작: ${feature.action.behavior}\n`;
        if (feature.action.result) description += `• 결과: ${feature.action.result}\n`;
        if (feature.action.api) description += `• API: ${feature.action.api}\n`;
        if (feature.action.relatedTable) description += `• 테이블: ${feature.action.relatedTable}\n`;
      }

      // 상태 정보 (필드가 가진 상태들과 조건)
      if (feature.states && feature.states.length > 0) {
        if (description) description += '\n';
        description += `【상태】\n`;
        feature.states.forEach(stateInfo => {
          description += `• ${stateInfo.state}: ${stateInfo.condition} → ${stateInfo.display}\n`;
        });
      }

      // 컬럼 정보 (테이블인 경우)
      if (feature.columns) {
        if (description) description += '\n';
        description += `【컬럼】\n`;
        description += `• ${feature.columns}\n`;
      }

      return {
        id: `badge-${Date.now()}-${index}`,
        number: index + 1,
        label: feature.label,
        color: 'red', // 기본 색상 빨간색으로 통일
        x: feature.position.x,
        y: feature.position.y,
        absoluteX,
        absoluteY,
        description: description.trim(),
        action: feature.action || null,
        states: feature.states || [],
        columns: feature.columns || null,
        createdAt: new Date().toISOString(),
        createdBy: userNickname || '시스템',
        autoGenerated: true,
      };
    });

    setFeatureBadges(prev => ({ ...prev, [screenKey]: newBadges }));
    alert(`✅ ${template.screenName}에서 ${newBadges.length}개의 기능이 자동 추출되었습니다.`);
  }, [activeMenu, view, featureBadges, userNickname]);

  // 메뉴 매핑 정보 (공용)
  const menuMapping = {
    // 대시보드/홈
    'dashboard': { group: '홈', label: '대시보드' },
    'home': { group: '홈', label: '홈' },
    // 기준정보
    'item-master': { group: '기준정보', label: '품목기준관리' },
    'process-master': { group: '기준정보', label: '공정기준관리' },
    'quality-master': { group: '기준정보', label: '품질기준관리' },
    'customer-master': { group: '기준정보', label: '거래처기준관리' },
    'site-master': { group: '기준정보', label: '현장기준관리' },
    'order-master': { group: '기준정보', label: '수주기준관리' },
    'process': { group: '기준정보', label: '공정관리' },
    'number-rule': { group: '기준정보', label: '채번관리' },
    'code-rule': { group: '기준정보', label: '공통코드관리' },
    'quote-formula': { group: '기준정보', label: '견적수식관리' },
    'document-template': { group: '기준정보', label: '문서양식관리' },
    // 판매관리
    'customer': { group: '판매관리', label: '거래처관리' },
    'quote': { group: '판매관리', label: '견적관리' },
    'order': { group: '판매관리', label: '수주관리' },
    'shipment': { group: '판매관리', label: '출하관리' },
    'site': { group: '판매관리', label: '현장관리' },
    'price': { group: '판매관리', label: '단가관리' },
    // 물류관리
    'logistics-shipment': { group: '물류관리', label: '출하관리' },
    // 생산관리
    'item': { group: '생산관리', label: '품목관리' },
    'production-dashboard': { group: '생산관리', label: '생산 현황판' },
    'work-order': { group: '생산관리', label: '작업지시 관리' },
    'work-result': { group: '생산관리', label: '작업실적' },
    'worker-task': { group: '생산관리', label: '작업자 화면' },
    'traceability': { group: '생산관리', label: '제품이력추적' },
    // 품질관리
    'inspection': { group: '품질관리', label: '검사관리' },
    'iqc': { group: '품질관리', label: '수입검사(IQC)' },
    'pqc': { group: '품질관리', label: '중간검사(PQC)' },
    'fqc': { group: '품질관리', label: '제품검사(FQC)' },
    'defect': { group: '품질관리', label: '부적합품관리' },
    // 자재관리
    'stock': { group: '자재관리', label: '재고현황' },
    'inbound': { group: '자재관리', label: '입고관리' },
    // 회계관리
    'acc-customer': { group: '회계관리', label: '거래처관리' },
    'sales-account': { group: '회계관리', label: '매출관리' },
    'purchase': { group: '회계관리', label: '매입관리' },
    'cashbook': { group: '회계관리', label: '금전출납부' },
    'collection': { group: '회계관리', label: '수금관리' },
    'cost-analysis': { group: '회계관리', label: '원가관리' },
    // 시스템
    'process-flowchart': { group: '시스템', label: '업무 플로우차트' },
    'detailed-process-flow': { group: '시스템', label: '상세 프로세스 플로우' },
    'users': { group: '시스템', label: '사용자관리' },
    'roles': { group: '시스템', label: '권한관리' },
    'settings': { group: '시스템', label: '시스템설정' },
    'common-ux': { group: '시스템', label: '공통 UX' },
    'integrated-test': { group: '시스템', label: '통합테스트' },
  };

  // 뷰 타입 한글 변환
  const viewLabels = {
    'list': '목록',
    'register': '등록',
    'detail': '상세',
    'edit': '수정',
  };

  // 화면명 생성 함수 (실제 페이지 타이틀)
  const getScreenName = () => {
    // 화면 타이틀 매핑 (view 값 기준 - PageHeader의 title과 동일하게)
    const screenTitleMap = {
      // 기준정보
      'item-master-list': '품목기준 목록',
      'item-master-register': '품목기준 등록',
      'item-master-detail': '품목기준 상세',
      'process-master-list': '공정기준 목록',
      'process-master-register': '공정기준 등록',
      'quality-master-list': '품질기준 목록',
      'customer-master-list': '거래처기준 목록',
      'site-master-list': '현장기준 목록',
      'order-master-list': '수주기준 목록',
      'number-rule-list': '채번규칙 목록',
      'code-rule-list': '공통코드 목록',
      'quote-formula-list': '견적수식 목록',
      'document-template-list': '문서양식 목록',
      'document-template-register': '문서양식 등록',
      'document-template-detail': '문서양식 상세',
      // 판매관리
      'customer-list': '거래처 목록',
      'customer-register': '거래처 등록',
      'customer-detail': '거래처 상세',
      'quote-list': '견적 목록',
      'quote-register': '견적 등록',
      'quote-detail': '견적 상세',
      'order-list': '수주 목록',
      'order-register': '수주 등록',
      'order-detail': '수주 상세',
      'order-edit': '수주 수정',
      'shipment-list': '출하 목록',
      'shipment-register': '출하 등록',
      'shipment-detail': '출하 상세',
      'site-list': '현장 목록',
      'price-list': '단가 목록',
      // 생산관리
      'production-dashboard-list': '생산현황',
      'work-order-list': '작업지시 목록',
      'work-order-register': '작업지시 등록',
      'work-order-detail': '작업지시 상세',
      'work-result-list': '작업실적 목록',
      'worker-task-list': '작업자 태스크',
      // 품질관리
      'inspection-list': '검사 목록',
      'iqc-list': '수입검사 목록',
      'pqc-list': '공정검사 목록',
      'fqc-list': '최종검사 목록',
      'defect-list': '부적합 목록',
      // 자재관리
      'stock-list': '재고 목록',
      'inbound-list': '입고 목록',
      'stock-adjustment-list': '재고 조정',
      // 회계관리
      'acc-customer-list': '거래처 목록',
      'sales-account-list': '매출 목록',
      'purchase-list': '매입 목록',
      'cashbook-list': '금전출납부 목록',
      'collection-list': '수금 목록',
      'cost-analysis-list': '원가분석',
      // 시스템
      'users-list': '사용자 목록',
      'roles-list': '권한 설정',
      'settings-list': '시스템 설정',
      // 대시보드
      'dashboard': '대시보드',
    };

    // view 값이 이미 화면 키 역할을 함 (예: 'order-list', 'customer-register')
    if (screenTitleMap[view]) {
      return screenTitleMap[view];
    }
    // 매핑에 없으면 기본 형식 사용
    const menuInfo = menuMapping[activeMenu] || { group: '', label: activeMenu };
    return `${menuInfo.label} 화면`;
  };

  // 화면ID 코드 체계 설명
  const [showIdCodeHelp, setShowIdCodeHelp] = useState(false);

  const idCodeHelpContent = {
    title: '화면ID 코드 체계',
    sections: [
      {
        category: '기준정보 (M)',
        prefix: 'M',
        description: 'Master Data 관리 화면',
        examples: ['M01: 품목기준', 'M02: 공정기준', 'M03: 검사기준', 'M04: 거래처기준', 'M10: 문서양식']
      },
      {
        category: '판매관리 (S)',
        prefix: 'S',
        description: 'Sales 관련 화면',
        examples: ['S01: 거래처', 'S02: 견적', 'S03: 수주', 'S04: 출하']
      },
      {
        category: '생산관리 (P)',
        prefix: 'P',
        description: 'Production 관련 화면',
        examples: ['P01: 생산현황', 'P02: 작업지시', 'P03: 작업실적', 'P04: 작업자태스크']
      },
      {
        category: '품질관리 (Q)',
        prefix: 'Q',
        description: 'Quality 관련 화면',
        examples: ['Q01: 검사관리', 'Q02: 수입검사', 'Q03: 공정검사', 'Q04: 최종검사', 'Q05: 부적합']
      },
      {
        category: '자재관리 (I)',
        prefix: 'I',
        description: 'Inventory 관련 화면',
        examples: ['I01: 재고', 'I02: 입고']
      },
      {
        category: '회계관리 (A)',
        prefix: 'A',
        description: 'Accounting 관련 화면',
        examples: ['A01: 거래처', 'A02: 매출', 'A03: 매입', 'A04: 금전출납부', 'A05: 수금', 'A06: 원가분석']
      },
      {
        category: '시스템 (SYS)',
        prefix: 'SYS',
        description: 'System 관련 화면',
        examples: ['SYS01: 사용자', 'SYS02: 권한', 'SYS03: 설정']
      },
      {
        category: '대시보드 (D)',
        prefix: 'D',
        description: 'Dashboard 화면',
        examples: ['D01: 대시보드']
      },
    ],
    suffix: '뷰 구분: -01(목록), -02(등록), -03(상세), -04(수정)'
  };

  // 화면 경로 생성 함수 (역할 > 그룹 > 메뉴)
  const getScreenPath = () => {
    const menuInfo = menuMapping[activeMenu] || { group: '', label: activeMenu };
    const roleName = currentUser?.roleName || '대표이사';
    return `${roleName} > ${menuInfo.group} > ${menuInfo.label}`;
  };

  // 화면 ID 생성 함수
  const getScreenId = () => {
    // 모달 ID 매핑 (DLG: Dialog)
    const modalIdMap = {
      // 판매관리 모달
      'quote-convert-modal': 'DLG-S02-01',      // 견적 → 수주 전환
      'order-split-modal': 'DLG-S03-01',        // 수주 분할
      'order-production-modal': 'DLG-S03-02',   // 생산지시 생성
      'order-po-create-modal': 'DLG-S03-03',    // 발주서 생성
      'order-document-modal': 'DLG-S03-04',     // 문서 출력
      'shipment-detail-modal': 'DLG-S04-01',    // 출하 상세
      // 생산관리 모달
      'work-order-create-modal': 'DLG-P02-01',  // 작업지시 생성
      'material-input-modal': 'DLG-P02-02',     // 투입자재 등록
      'work-log-modal': 'DLG-P03-01',           // 작업일지
      'issue-report-modal': 'DLG-P03-02',       // 이슈보고
      // 품질관리 모달
      'defect-action-modal': 'DLG-Q05-01',      // 부적합 처리
      'defect-approval-modal': 'DLG-Q05-02',    // 부적합 승인
      // 자재관리 모달
      'receive-modal': 'DLG-I02-01',            // 입고 등록
      'stock-create-modal': 'DLG-I01-01',       // 재고 조정
      // 기준정보 모달
      'rule-modal': 'DLG-M07-01',               // 채번규칙 편집
      'formula-modal': 'DLG-M09-01',            // 견적공식 편집
      'item-add-modal': 'DLG-M01-01',           // 품목 추가
      // 공통 모달
      'delete-confirm-modal': 'DLG-CMN-01',     // 삭제 확인
      'approval-modal': 'DLG-CMN-02',           // 결재 모달
      'preview-modal': 'DLG-CMN-03',            // 미리보기
    };

    // 모달이 열려있으면 모달 ID 반환
    if (activeModal && modalIdMap[activeModal]) {
      return modalIdMap[activeModal];
    }

    // 화면 ID 매핑 (view 값 기준 - view가 이미 'menu-viewType' 형태)
    const screenIdMap = {
      // 기준정보 (M: Master)
      'item-master-list': 'M01-01',
      'item-master-register': 'M01-02',
      'item-master-detail': 'M01-03',
      'process-master-list': 'M02-01',
      'process-master-register': 'M02-02',
      'quality-master-list': 'M03-01',
      'customer-master-list': 'M04-01',
      'site-master-list': 'M05-01',
      'order-master-list': 'M06-01',
      'number-rule-list': 'M07-01',
      'code-rule-list': 'M08-01',
      'quote-formula-list': 'M09-01',
      'document-template-list': 'M10-01',
      'document-template-register': 'M10-02',
      'document-template-detail': 'M10-03',
      // 판매관리 (S: Sales)
      'customer-list': 'S01-01',
      'customer-register': 'S01-02',
      'customer-detail': 'S01-03',
      'quote-list': 'S02-01',
      'quote-register': 'S02-02',
      'quote-detail': 'S02-03',
      'order-list': 'S03-01',
      'order-register': 'S03-02',
      'order-detail': 'S03-03',
      'order-edit': 'S03-04',
      'shipment-list': 'S04-01',
      'shipment-register': 'S04-02',
      'shipment-detail': 'S04-03',
      'site-list': 'S05-01',
      'price-list': 'S06-01',
      // 생산관리 (P: Production)
      'production-dashboard-list': 'P01-01',
      'work-order-list': 'P02-01',
      'work-order-register': 'P02-02',
      'work-order-detail': 'P02-03',
      'work-result-list': 'P03-01',
      'worker-task-list': 'P04-01',
      // 품질관리 (Q: Quality)
      'inspection-list': 'Q01-01',
      'iqc-list': 'Q02-01',
      'pqc-list': 'Q03-01',
      'fqc-list': 'Q04-01',
      'defect-list': 'Q05-01',
      // 자재관리 (I: Inventory)
      'stock-list': 'I01-01',
      'inbound-list': 'I02-01',
      'stock-adjustment-list': 'I03-01',
      // 회계관리 (A: Accounting)
      'acc-customer-list': 'A01-01',
      'sales-account-list': 'A02-01',
      'purchase-list': 'A03-01',
      'cashbook-list': 'A04-01',
      'collection-list': 'A05-01',
      'cost-analysis-list': 'A06-01',
      // 시스템 (SYS: System)
      'users-list': 'SYS01-01',
      'roles-list': 'SYS02-01',
      'settings-list': 'SYS03-01',
      // 대시보드
      'dashboard': 'D01-01',
    };

    // view 값이 이미 화면 키 역할을 함 (예: 'order-list', 'customer-register')
    return screenIdMap[view] || `SCR-${view.toUpperCase().replace(/-/g, '-').substring(0, 15)}`;
  };

  // 뱃지 추가 (일반 방식)
  const addFeatureBadge = (badge) => {
    const screenKey = `${activeMenu}-${view}`;
    const number = getNextBadgeNumber();
    const newBadge = {
      ...badge,
      number,
      id: Date.now(),
      author: userNickname,
      createdAt: new Date().toISOString(),
    };
    setFeatureBadges(prev => ({
      ...prev,
      [screenKey]: [...(prev[screenKey] || []), newBadge]
    }));
    setIsAddingBadge(false);
  };

  // 현재 화면의 screenKey 가져오기 (모달 포함)
  const getCurrentScreenKey = () => {
    // 모달이 열려있으면 모달 키 반환
    if (activeModal) {
      return `modal-${activeModal}`;
    }
    return `${activeMenu}-${view}`;
  };

  // 현재 화면에 템플릿이 있는지 확인
  const checkHasTemplate = () => {
    const screenKey = getCurrentScreenKey();
    // screenKeyMapping에서 매핑된 키 찾기
    const mappedKey = screenKeyMapping[screenKey] || screenKey;
    return !!getFeatureDefinition(mappedKey);
  };

  // 템플릿에서 뱃지 로드
  const loadTemplateToCurrentScreen = () => {
    const screenKey = getCurrentScreenKey();
    // screenKeyMapping에서 매핑된 키 찾기
    const mappedKey = screenKeyMapping[screenKey] || screenKey;
    const template = getFeatureDefinition(mappedKey);

    if (!template) {
      alert('이 화면에 대한 기능정의 템플릿이 없습니다.');
      return;
    }

    // 템플릿에서 뱃지 생성
    const templateBadges = generateDefaultBadges(mappedKey);

    if (templateBadges.length === 0) {
      alert('템플릿에 정의된 뱃지가 없습니다.');
      return;
    }

    // 기존 뱃지의 마지막 번호 확인
    const existingBadges = featureBadges[screenKey] || [];
    const maxNumber = existingBadges.length > 0
      ? Math.max(...existingBadges.map(b => b.number || 0))
      : 0;

    // 새 뱃지에 번호 재할당 (기존 번호 이후부터)
    const newBadges = templateBadges.map((badge, index) => ({
      ...badge,
      id: `${screenKey}-template-${Date.now()}-${index}`,
      number: maxNumber + index + 1,
      author: userNickname || 'Template',
      createdAt: new Date().toISOString(),
      isFixed: false,
      // 위치를 비율 좌표로 설정 (템플릿에서는 position.x/y를 사용)
      x: badge.position?.x || badge.x || 50,
      y: badge.position?.y || badge.y || 50,
      absoluteX: null, // 렌더링 시 계산됨
      absoluteY: null,
    }));

    // 기존 뱃지에 추가
    setFeatureBadges(prev => ({
      ...prev,
      [screenKey]: [...existingBadges, ...newBadges]
    }));

    alert(`✅ ${newBadges.length}개의 기능정의 뱃지가 로드되었습니다.\n\n화면: ${template.screenName}\n화면ID: ${template.screenId}`);
  };

  // 인라인 뱃지 편집용 상태
  const [editingBadge, setEditingBadge] = useState(null);

  // 인라인 뱃지 추가 (C키 → 클릭 → 입력 방식)
  const addInlineBadge = (badgeData) => {
    if (!inlineInputPosition) return;
    const screenKey = `${activeMenu}-${view}`;
    const newBadge = {
      id: Date.now(),
      number: nextBadgeNumber,
      label: badgeData.label || '', // 기능 제목 추가
      description: badgeData.description,
      uiInfo: badgeData.uiInfo,
      color: badgeData.color || 'red',
      // 절대 픽셀 좌표로 저장 (스크롤과 함께 움직이도록)
      absoluteX: inlineInputPosition.absoluteX,
      absoluteY: inlineInputPosition.absoluteY,
      // 레거시 호환성을 위해 비율도 저장
      x: inlineInputPosition.x,
      y: inlineInputPosition.y,
      author: userNickname,
      createdAt: new Date().toISOString(),
    };
    setFeatureBadges(prev => ({
      ...prev,
      [screenKey]: [...(prev[screenKey] || []), newBadge]
    }));
    setInlineInputPosition(null);
  };

  // 인라인 뱃지 수정 (기존 뱃지 클릭 시)
  const updateInlineBadge = (badgeData) => {
    if (!editingBadge) return;
    const screenKey = `${activeMenu}-${view}`;

    setFeatureBadges(prev => ({
      ...prev,
      [screenKey]: (prev[screenKey] || []).map(b =>
        b.id === editingBadge.id ? {
          ...b,
          label: badgeData.label || b.label || '', // 기능 제목 수정
          description: badgeData.description,
          uiInfo: badgeData.uiInfo,
          color: badgeData.color || b.color
        } : b
      )
    }));
    setEditingBadge(null);
  };

  // 뱃지 업데이트
  const updateFeatureBadge = (badgeId, updates) => {
    const screenKey = `${activeMenu}-${view}`;

    setFeatureBadges(prev => ({
      ...prev,
      [screenKey]: (prev[screenKey] || []).map(b =>
        b.id === badgeId ? { ...b, ...updates } : b
      )
    }));
  };

  // 뱃지 삭제
  const deleteFeatureBadge = (badgeId) => {
    const screenKey = `${activeMenu}-${view}`;

    setFeatureBadges(prev => ({
      ...prev,
      [screenKey]: (prev[screenKey] || []).filter(b => b.id !== badgeId)
    }));
    setSelectedBadge(null);
  };

  // 뱃지에 댓글 추가
  const addBadgeComment = (badgeId, commentText) => {
    const screenKey = `${activeMenu}-${view}`;
    const newComment = {
      id: Date.now(),
      text: commentText,
      author: userNickname || '익명',
      createdAt: new Date().toISOString()
    };

    setFeatureBadges(prev => ({
      ...prev,
      [screenKey]: (prev[screenKey] || []).map(b =>
        b.id === badgeId ? {
          ...b,
          comments: [...(b.comments || []), newComment]
        } : b
      )
    }));

    // selectedBadge도 업데이트
    setSelectedBadge(prev => {
      if (prev && prev.id === badgeId) {
        return {
          ...prev,
          comments: [...(prev.comments || []), newComment]
        };
      }
      return prev;
    });
  };

  // 뱃지 댓글 삭제
  const deleteBadgeComment = (badgeId, commentId) => {
    const screenKey = `${activeMenu}-${view}`;

    setFeatureBadges(prev => ({
      ...prev,
      [screenKey]: (prev[screenKey] || []).map(b =>
        b.id === badgeId ? {
          ...b,
          comments: (b.comments || []).filter(c => c.id !== commentId)
        } : b
      )
    }));

    // selectedBadge도 업데이트
    setSelectedBadge(prev => {
      if (prev && prev.id === badgeId) {
        return {
          ...prev,
          comments: (prev.comments || []).filter(c => c.id !== commentId)
        };
      }
      return prev;
    });
  };

  // 비밀번호 확인 후 삭제 (인라인 팝업용)
  const DELETE_PASSWORD = '1234';
  const deleteWithPassword = (badgeId, onSuccess) => {
    const password = window.prompt('삭제하려면 비밀번호를 입력하세요:');
    if (password === null) return; // 취소
    if (password === DELETE_PASSWORD) {
      deleteFeatureBadge(badgeId);
      if (onSuccess) onSuccess();
    } else {
      alert('비밀번호가 올바르지 않습니다.');
    }
  };

  // 현재 사용자 상태 (역할별 로그인)
  const [currentUser, setCurrentUser] = useState({
    id: 1,
    name: '김대표',
    role: 'ceo',
    roleName: '대표이사',
    avatar: null,
  });

  // 사용자 목록 (테스트용)
  const users = [
    { id: 1, name: '김대표', role: 'ceo', roleName: '대표이사' },
    { id: 2, name: '이판매', role: 'sales', roleName: '판매팀' },
    { id: 3, name: '박생산', role: 'production', roleName: '생산관리' },
    { id: 4, name: '최품질', role: 'quality', roleName: '품질관리' },
    { id: 5, name: '정회계', role: 'accounting', roleName: '회계팀' },
    { id: 6, name: '강구매', role: 'purchase', roleName: '구매팀' },
    { id: 7, name: '김생산', role: 'worker', roleName: '생산담당자' },
  ];

  // 사용자 변경 핸들러
  const handleUserChange = (userId) => {
    const user = users.find(u => u.id === parseInt(userId));
    if (user) {
      setCurrentUser(user);
      // 역할에 따른 기본 대시보드로 이동
      const dashboardMap = {
        ceo: 'dashboard',
        sales: 'sales-dashboard',
        production: 'production-dashboard',
        quality: 'quality-dashboard',
        accounting: 'accounting-dashboard',
        purchase: 'purchase-dashboard',
        worker: 'worker-dashboard',
      };
      setView(dashboardMap[user.role] || 'dashboard');
      setActiveMenu('dashboard');
    }
  };

  // 반응형 훅
  const { isMobile, isTablet, isDesktop } = useResponsive();

  const [orders, setOrders] = useState(initialOrders);
  const [quotes, setQuotes] = useState(sampleQuotesData);
  const [productionOrders, setProductionOrders] = useState(integratedProductionOrderMaster);
  const [workOrders, setWorkOrders] = useState(initialWorkOrders);
  const [workResults, setWorkResults] = useState(initialWorkResults);
  const [shipments, setShipments] = useState(initialShipments);
  const [productInspections, setProductInspections] = useState(initialProductInspections);
  const [purchaseOrders, setPurchaseOrders] = useState([
    { id: 1, poNo: 'KD-SO-250301-001', materialCode: 'RM-COIL-05', materialName: '갈바코일 0.5T', requestQty: 10, unit: '톤', vendor: '철강공업', supplierName: '철강공업', status: '배송중', requestDate: '2025-03-01', requester: '강구매', qty: 10 },
    { id: 2, poNo: 'KD-SO-250302-001', materialCode: 'PP-MOTOR-01', materialName: '튜블러모터', requestQty: 50, unit: 'EA', vendor: '모터공급사', supplierName: '모터공급사', status: '발주완료', requestDate: '2025-03-02', requester: '강구매', qty: 50 },
    // 수입검사(IQC) 대기 항목 - 입고대기/검사대기 상태
    { id: 3, poNo: 'KD-SO-250310-001', materialCode: 'RM-SCREEN-01', materialName: '방충망 원단 1016', requestQty: 100, unit: 'M', vendor: '한국망사', supplierName: '한국망사', status: '검사대기', requestDate: '2025-03-10', requester: '김자재', qty: 100, arrivalDate: '2025-03-12' },
    { id: 4, poNo: 'KD-SO-250311-001', materialCode: 'PP-ENDLOCK-01', materialName: '앤드락 2100', requestQty: 200, unit: 'EA', vendor: '부품산업', supplierName: '부품산업', status: '입고대기', requestDate: '2025-03-11', requester: '김자재', qty: 200, arrivalDate: '2025-03-13' },
    { id: 5, poNo: 'KD-SO-250312-001', materialCode: 'RM-COIL-08', materialName: '갈바코일 0.8T', requestQty: 5, unit: '톤', vendor: '포항철강', supplierName: '포항철강', status: '검사대기', requestDate: '2025-03-12', requester: '강구매', qty: 5, arrivalDate: '2025-03-14' },
  ]);

  // 검사 이력 (수입검사, 중간검사 통합)
  const [allInspections, setAllInspections] = useState([
    // 수입검사(IQC) 이력 - LOT 채번 규칙: YYMMDD-## (예: 250308-01)
    { id: 1, type: 'incoming', inspectionDate: '2025-03-08', targetNo: 'PO-250305-001', lotNo: '250308-01', itemName: '방충망 원단 1270', result: '합격', inspector: '품질팀 박검사', qty: 80, passQty: 80, failQty: 0 },
    { id: 2, type: 'incoming', inspectionDate: '2025-03-07', targetNo: 'PO-250303-001', lotNo: '250307-01', itemName: '튜블러모터 50W', result: '불합격', inspector: '품질팀 박검사', qty: 30, passQty: 25, failQty: 5, ncrNo: 'NCR-250307-001' },
    { id: 3, type: 'incoming', inspectionDate: '2025-03-06', targetNo: 'PO-250302-002', lotNo: '250306-01', itemName: '앤드락 1800', result: '합격', inspector: '품질팀 이검사', qty: 150, passQty: 150, failQty: 0 },
    // 중간검사(PQC) 이력
    { id: 4, type: 'process', inspectionDate: '2025-03-09', targetNo: 'KD-WO-240115-01', lotNo: 'PQC-250309-01', itemName: '스크린 원단절단', result: '합격', inspector: '품질팀 이검사', qty: 10, passQty: 10, failQty: 0 },
    { id: 5, type: 'process', inspectionDate: '2025-03-08', targetNo: 'KD-WO-240115-02', lotNo: 'PQC-250308-01', itemName: '슬랫 코일절단', result: '불합격', inspector: '품질팀 박검사', qty: 5, passQty: 3, failQty: 2, ncrNo: 'NCR-250308-001' },
    // 제품검사(FQC) 이력
    { id: 6, type: 'product', inspectionDate: '2025-03-07', targetNo: 'KD-SA-250307-01', lotNo: 'FQC-250307-01', itemName: '스크린 셔터 (표준형)', result: '합격', inspector: '품질팀 최검사', qty: 3, passQty: 3, failQty: 0 },
    { id: 7, type: 'product', inspectionDate: '2025-03-05', targetNo: 'KD-SA-250305-01', lotNo: 'FQC-250305-01', itemName: '슬랫 셔터', result: '불합격', inspector: '품질팀 최검사', qty: 2, passQty: 1, failQty: 1, ncrNo: 'NCR-250305-002' },
  ]);

  // 부적합품 목록
  const [defects, setDefects] = useState([
    {
      id: 1,
      ncrNo: 'NCR-250307-001',
      registDate: '2025-03-07',
      source: 'IQC',
      sourceNo: 'PO-250303-001',
      itemName: '튜블러모터 50W',
      defectType: '외관불량',
      defectQty: 5,
      totalQty: 30,
      description: '모터 케이스 도장 벗겨짐 및 찍힘 발견',
      vendorName: '모터공급사',
      status: '처리대기',
      registeredBy: '품질팀 박검사',
      images: [],
      approvalLine: {
        type: 'APR-3LINE',
        roles: [
          { id: 'writer', label: '작성', name: '품질팀 박검사', date: '2025-03-07', status: 'approved' },
          { id: 'reviewer', label: '검토', name: '', date: '', status: 'pending' },
          { id: 'approver', label: '승인', name: '', date: '', status: 'pending' },
        ]
      }
    },
    {
      id: 2,
      ncrNo: 'NCR-250308-001',
      registDate: '2025-03-08',
      source: 'PQC',
      sourceNo: 'KD-WO-240115-02',
      itemName: '슬랫 코일절단',
      defectType: '치수불량',
      defectQty: 2,
      totalQty: 5,
      description: '코일 절단 길이 규격 초과 (3010mm, 기준 3000±5mm)',
      vendorName: null,
      status: '처리대기',
      registeredBy: '품질팀 박검사',
      images: [],
      processType: '재작업',
      approvalLine: {
        type: 'APR-3LINE',
        roles: [
          { id: 'writer', label: '작성', name: '품질팀 박검사', date: '2025-03-08', status: 'approved' },
          { id: 'reviewer', label: '검토', name: '생산팀 김팀장', date: '2025-03-08', status: 'approved' },
          { id: 'approver', label: '승인', name: '', date: '', status: 'pending' },
        ]
      }
    },
    {
      id: 3,
      ncrNo: 'NCR-250305-001',
      registDate: '2025-03-05',
      source: 'IQC',
      sourceNo: 'PO-250301-002',
      itemName: '방충망 원단 1524',
      defectType: '이물질혼입',
      defectQty: 10,
      totalQty: 50,
      description: '원단 중간에 금속 이물질 혼입 확인',
      vendorName: '한국망사',
      status: '처리완료',
      processResult: '반품',
      processDate: '2025-03-06',
      processBy: '자재팀 강대리',
      registeredBy: '품질팀 이검사',
      images: [],
      approvalLine: {
        type: 'APR-3LINE',
        roles: [
          { id: 'writer', label: '작성', name: '품질팀 이검사', date: '2025-03-05', status: 'approved' },
          { id: 'reviewer', label: '검토', name: '품질팀 김팀장', date: '2025-03-05', status: 'approved' },
          { id: 'approver', label: '승인', name: '공장장 박상무', date: '2025-03-06', status: 'approved' },
        ]
      }
    },
    {
      id: 4,
      ncrNo: 'NCR-250309-001',
      registDate: '2025-03-09',
      source: 'FQC',
      sourceNo: 'KD-SA-250309-01',
      itemName: '스크린 셔터 (프리미엄)',
      defectType: '기능불량',
      defectQty: 1,
      totalQty: 2,
      description: '모터 작동 시 소음 발생 및 간헐적 정지 현상',
      vendorName: null,
      status: '승인대기',
      registeredBy: '품질팀 최검사',
      images: [],
      processType: '재작업',
      approvalLine: {
        type: 'APR-3LINE',
        roles: [
          { id: 'writer', label: '작성', name: '품질팀 최검사', date: '2025-03-09', status: 'approved' },
          { id: 'reviewer', label: '검토', name: '품질팀 김팀장', date: '2025-03-09', status: 'approved' },
          { id: 'approver', label: '승인', name: '', date: '', status: 'pending' },
        ]
      }
    },
  ]);

  // ═══════════════════════════════════════════════════════════════════
  // LOT 시퀀스 관리 시스템 (자동 번호 생성)
  // ═══════════════════════════════════════════════════════════════════
  const [lotSequences, setLotSequences] = useState({
    // 날짜별 시퀀스 관리 (YYMMDD: seq)
    incoming: {},      // 입고LOT: YYMMDD-##
    production: {},    // 생산LOT: KD-PL-YYMMDD-##
    incomingInsp: {},  // 입고검사LOT: YYMMDD-##
    processInsp: {},   // 중간검사LOT: KD-WE-YYMMDD-##-(step)
    productInsp: {},   // 제품검사LOT: KD-SA-YYMMDD-##
    finished: {},      // 완제품LOT: 수주번호-##
    qc: {},            // 일반검사LOT: KD-QC-YYMMDD-##
  });

  // 다음 시퀀스 번호 가져오기
  const getNextSequence = (type, dateKey) => {
    const currentSeq = lotSequences[type]?.[dateKey] || 0;
    return currentSeq + 1;
  };

  // 시퀀스 번호 업데이트
  const updateSequence = (type, dateKey) => {
    setLotSequences(prev => ({
      ...prev,
      [type]: {
        ...prev[type],
        [dateKey]: (prev[type]?.[dateKey] || 0) + 1
      }
    }));
  };

  // ★ 입고LOT 자동생성: YYMMDD-##
  const autoGenerateIncomingLot = (date = new Date()) => {
    const dateKey = formatDateCode(date);
    const seq = getNextSequence('incoming', dateKey);
    updateSequence('incoming', dateKey);
    return generateIncomingInspectionLot(date, seq);
  };

  // ★ 생산LOT 자동생성: KD-PL-YYMMDD-##
  const autoGenerateProductionLot = (date = new Date()) => {
    const dateKey = formatDateCode(date);
    const seq = getNextSequence('production', dateKey);
    updateSequence('production', dateKey);
    return generateProductionLot(date, seq);
  };

  // ★ 입고검사LOT 자동생성: YYMMDD-## (입고LOT와 동일 체계)
  const autoGenerateIncomingInspLot = (date = new Date()) => {
    const dateKey = formatDateCode(date);
    const seq = getNextSequence('incomingInsp', dateKey);
    updateSequence('incomingInsp', dateKey);
    return generateIncomingInspectionLot(date, seq);
  };

  // ★ 중간검사LOT 자동생성: KD-WE-YYMMDD-##-(step)
  const autoGenerateProcessInspLot = (date = new Date(), step = 1) => {
    const dateKey = formatDateCode(date);
    const seq = getNextSequence('processInsp', dateKey);
    updateSequence('processInsp', dateKey);
    return generateProcessInspectionLot(date, seq, step);
  };

  // ★ 제품검사LOT 자동생성: KD-SA-YYMMDD-##
  const autoGenerateProductInspLot = (date = new Date()) => {
    const dateKey = formatDateCode(date);
    const seq = getNextSequence('productInsp', dateKey);
    updateSequence('productInsp', dateKey);
    return generateProductInspectionLot(date, seq);
  };

  // ★ 완제품LOT 자동생성: 수주번호-## (제품검사 직전)
  const autoGenerateFinishedLot = (orderNo) => {
    const seq = getNextSequence('finished', orderNo);
    updateSequence('finished', orderNo);
    return generateProductLot(orderNo, seq);
  };

  // ★ 일반검사LOT 자동생성: KD-QC-YYMMDD-##
  const autoGenerateQCLot = (date = new Date()) => {
    const dateKey = formatDateCode(date);
    const seq = getNextSequence('qc', dateKey);
    updateSequence('qc', dateKey);
    return generateQCLot(date, seq);
  };

  // ═══════════════════════════════════════════════════════════════════
  // 회계 자동화 시스템
  // ═══════════════════════════════════════════════════════════════════

  // 세금계산서 목록
  const [taxInvoices, setTaxInvoices] = useState([]);

  // 거래명세서 목록
  const [transactionStatements, setTransactionStatements] = useState([]);

  // 미수금 현황
  const [receivables, setReceivables] = useState([]);

  // ★ 세금계산서 자동발행 (출하완료 시 호출)
  const autoGenerateTaxInvoice = (shipment, order) => {
    const invoiceNo = `TI-${formatDateCode(new Date())}-${String(taxInvoices.length + 1).padStart(3, '0')}`;
    const newInvoice = {
      id: taxInvoices.length + 1,
      invoiceNo,
      issueDate: new Date().toISOString().split('T')[0],
      customerId: order.customerId,
      customerName: order.customerName,
      businessNo: order.businessNo || '',
      orderNo: order.orderNo,
      shipmentNo: shipment.shipmentNo,
      items: order.items || [],
      supplyAmount: order.totalAmount || 0,
      taxAmount: Math.round((order.totalAmount || 0) * 0.1),
      totalAmount: Math.round((order.totalAmount || 0) * 1.1),
      status: '발행완료',
      issuedBy: currentUser.name,
      createdAt: new Date().toISOString(),
    };
    setTaxInvoices(prev => [...prev, newInvoice]);

    // 미수금 자동 등록
    autoCreateReceivable(newInvoice, order);

    return newInvoice;
  };

  // ★ 거래명세서 자동생성 (출하완료 시 호출)
  const autoGenerateTransactionStatement = (shipment, order) => {
    const statementNo = `TS-${formatDateCode(new Date())}-${String(transactionStatements.length + 1).padStart(3, '0')}`;
    const newStatement = {
      id: transactionStatements.length + 1,
      statementNo,
      issueDate: new Date().toISOString().split('T')[0],
      customerId: order.customerId,
      customerName: order.customerName,
      orderNo: order.orderNo,
      shipmentNo: shipment.shipmentNo,
      items: order.items || [],
      totalAmount: order.totalAmount || 0,
      status: '발송대기',
      createdAt: new Date().toISOString(),
    };
    setTransactionStatements(prev => [...prev, newStatement]);
    return newStatement;
  };

  // ★ 미수금 자동등록
  const autoCreateReceivable = (invoice, order) => {
    const newReceivable = {
      id: receivables.length + 1,
      invoiceNo: invoice.invoiceNo,
      customerId: order.customerId,
      customerName: order.customerName,
      creditGrade: order.creditGrade || 'B',
      orderNo: order.orderNo,
      invoiceDate: invoice.issueDate,
      dueDate: calculateDueDate(invoice.issueDate, order.paymentTerms || 30),
      amount: invoice.totalAmount,
      paidAmount: 0,
      balance: invoice.totalAmount,
      status: '미수',
      createdAt: new Date().toISOString(),
    };
    setReceivables(prev => [...prev, newReceivable]);
    return newReceivable;
  };

  // ★ 입금 자동반영
  const autoApplyPayment = (customerId, amount, paymentDate = new Date()) => {
    let remainingAmount = amount;
    const updatedReceivables = receivables.map(r => {
      if (r.customerId === customerId && r.balance > 0 && remainingAmount > 0) {
        const payAmount = Math.min(r.balance, remainingAmount);
        remainingAmount -= payAmount;
        return {
          ...r,
          paidAmount: r.paidAmount + payAmount,
          balance: r.balance - payAmount,
          status: r.balance - payAmount <= 0 ? '완납' : '일부입금',
          lastPaymentDate: paymentDate.toISOString().split('T')[0],
        };
      }
      return r;
    });
    setReceivables(updatedReceivables);

    // C등급 고객 출하승인 자동 처리
    const customer = orders.find(o => o.customerId === customerId);
    if (customer?.creditGrade === 'C') {
      autoApproveCGradeShipment(customerId);
    }

    return remainingAmount; // 남은 금액 반환 (0이면 전액 처리)
  };

  // 결제 만기일 계산
  const calculateDueDate = (issueDate, terms) => {
    const date = new Date(issueDate);
    date.setDate(date.getDate() + terms);
    return date.toISOString().split('T')[0];
  };

  // ═══════════════════════════════════════════════════════════════════
  // C등급 출하승인 자동화
  // ═══════════════════════════════════════════════════════════════════

  // ★ C등급 고객 입금확인 후 출하승인 자동처리
  const autoApproveCGradeShipment = (customerId) => {
    setShipments(prev => prev.map(s => {
      if (s.customerId === customerId && s.status === '출하보류') {
        return {
          ...s,
          status: '출하준비',
          approvedAt: new Date().toISOString(),
          approvedBy: '시스템(입금확인)',
          approvalNote: '입금확인으로 자동 출하승인',
        };
      }
      return s;
    }));
  };

  // ★ 출하보류 자동처리 (C등급 또는 미수금 과다 시)
  const autoHoldShipment = (shipmentId, reason) => {
    setShipments(prev => prev.map(s => {
      if (s.id === shipmentId) {
        return {
          ...s,
          status: '출하보류',
          holdReason: reason,
          holdAt: new Date().toISOString(),
        };
      }
      return s;
    }));
  };

  // ═══════════════════════════════════════════════════════════════════
  // 할인정책 자동적용 시스템
  // ═══════════════════════════════════════════════════════════════════

  // 할인 정책 정의
  const discountPolicies = {
    // 거래처 등급별 기본 할인율
    gradeDiscount: {
      'A': 5,  // A등급: 5% 기본 할인
      'B': 3,  // B등급: 3% 기본 할인
      'C': 0,  // C등급: 할인 없음
    },
    // 수량별 추가 할인
    volumeDiscount: [
      { minQty: 100, rate: 2 },   // 100개 이상: 2% 추가
      { minQty: 50, rate: 1 },    // 50개 이상: 1% 추가
      { minQty: 0, rate: 0 },     // 기본
    ],
    // 대량주문 할인 (금액 기준)
    bulkDiscount: [
      { minAmount: 50000000, rate: 5 },  // 5천만원 이상: 5% 추가
      { minAmount: 30000000, rate: 3 },  // 3천만원 이상: 3% 추가
      { minAmount: 10000000, rate: 1 },  // 1천만원 이상: 1% 추가
      { minAmount: 0, rate: 0 },
    ],
    // 결제조건별 할인
    paymentDiscount: {
      '선금결제': 3,     // 선금결제: 3% 추가
      '현금결제': 2,     // 현금결제: 2% 추가
      '30일이내': 1,     // 30일 이내 결제: 1% 추가
    },
  };

  // ★ 할인율 자동 계산
  const autoCalculateDiscount = (customerId, totalAmount, totalQty, paymentTerms) => {
    const customer = sampleCustomersData.find(c => c.id === customerId);
    if (!customer) return { discountRate: 0, discountAmount: 0, breakdown: [] };

    const breakdown = [];
    let totalDiscountRate = 0;

    // 1. 거래처 기본 할인율 (거래처에 설정된 값 우선)
    const customerDiscount = customer.discountRate || 0;
    if (customerDiscount > 0) {
      breakdown.push({ type: '거래처 기본', rate: customerDiscount });
      totalDiscountRate += customerDiscount;
    } else {
      // 등급별 기본 할인
      const gradeRate = discountPolicies.gradeDiscount[customer.creditGrade] || 0;
      if (gradeRate > 0) {
        breakdown.push({ type: `${customer.creditGrade}등급 기본`, rate: gradeRate });
        totalDiscountRate += gradeRate;
      }
    }

    // 2. 수량별 할인
    const volumeRule = discountPolicies.volumeDiscount.find(r => totalQty >= r.minQty);
    if (volumeRule && volumeRule.rate > 0) {
      breakdown.push({ type: `대량주문(${totalQty}개)`, rate: volumeRule.rate });
      totalDiscountRate += volumeRule.rate;
    }

    // 3. 금액별 할인
    const bulkRule = discountPolicies.bulkDiscount.find(r => totalAmount >= r.minAmount);
    if (bulkRule && bulkRule.rate > 0) {
      breakdown.push({ type: `대량금액(${(totalAmount / 10000).toLocaleString()}만원)`, rate: bulkRule.rate });
      totalDiscountRate += bulkRule.rate;
    }

    // 4. 결제조건별 할인
    const paymentRate = discountPolicies.paymentDiscount[paymentTerms] || 0;
    if (paymentRate > 0) {
      breakdown.push({ type: `결제조건(${paymentTerms})`, rate: paymentRate });
      totalDiscountRate += paymentRate;
    }

    // 최대 할인율 제한 (20%)
    totalDiscountRate = Math.min(totalDiscountRate, 20);

    const discountAmount = Math.round(totalAmount * totalDiscountRate / 100);

    return {
      discountRate: totalDiscountRate,
      discountAmount,
      finalAmount: totalAmount - discountAmount,
      breakdown,
    };
  };

  // ═══════════════════════════════════════════════════════════════════
  // 공정별 작업자 할당 시스템
  // ═══════════════════════════════════════════════════════════════════

  // 작업자 목록
  const [workers] = useState([
    { id: 1, name: '김작업', dept: '생산1팀', skills: ['스크린', '슬랫', '조립'], status: '근무중', currentWork: null },
    { id: 2, name: '이생산', dept: '생산1팀', skills: ['스크린', '절곡'], status: '근무중', currentWork: null },
    { id: 3, name: '박공정', dept: '생산2팀', skills: ['슬랫', '조립', '포장'], status: '근무중', currentWork: null },
    { id: 4, name: '최조립', dept: '생산2팀', skills: ['조립', '포장', '검사'], status: '근무중', currentWork: null },
    { id: 5, name: '정설비', dept: '설비팀', skills: ['설비관리', '스크린', '슬랫'], status: '근무중', currentWork: null },
  ]);

  // ★ 작업자 자동 할당 (공정 스킬 기반)
  const autoAssignWorker = (workOrder) => {
    const processType = workOrder.processType;

    // 해당 공정 스킬을 가진 가용 작업자 찾기
    const availableWorkers = workers.filter(w =>
      w.status === '근무중' &&
      !w.currentWork &&
      w.skills.includes(processType)
    );

    if (availableWorkers.length === 0) {
      // 스킬은 있지만 다른 작업 중인 작업자 찾기
      const busyWorkers = workers.filter(w =>
        w.status === '근무중' &&
        w.skills.includes(processType)
      );
      if (busyWorkers.length > 0) {
        return {
          assigned: false,
          message: `${processType} 공정 가능 작업자가 모두 작업 중입니다.`,
          suggestedWorkers: busyWorkers.map(w => w.name),
        };
      }
      return {
        assigned: false,
        message: `${processType} 공정 가능한 작업자가 없습니다.`,
        suggestedWorkers: [],
      };
    }

    // 첫 번째 가용 작업자 할당
    const assignedWorker = availableWorkers[0];
    return {
      assigned: true,
      worker: assignedWorker,
      message: `${assignedWorker.name} 작업자가 자동 할당되었습니다.`,
    };
  };

  // ═══════════════════════════════════════════════════════════════════
  // 설비 가동률 추적 시스템
  // ═══════════════════════════════════════════════════════════════════

  // 설비 목록 및 가동 현황
  const [equipments, setEquipments] = useState([
    { id: 1, code: 'SCR-001', name: '스크린 재단기 1호', type: '스크린', status: '가동중', startTime: null, totalRunTime: 0, totalDownTime: 0 },
    { id: 2, code: 'SCR-002', name: '스크린 재단기 2호', type: '스크린', status: '대기', startTime: null, totalRunTime: 0, totalDownTime: 0 },
    { id: 3, code: 'SLT-001', name: '슬랫 절단기', type: '슬랫', status: '가동중', startTime: null, totalRunTime: 0, totalDownTime: 0 },
    { id: 4, code: 'BND-001', name: '절곡기 1호', type: '절곡', status: '가동중', startTime: null, totalRunTime: 0, totalDownTime: 0 },
    { id: 5, code: 'BND-002', name: '절곡기 2호', type: '절곡', status: '점검중', startTime: null, totalRunTime: 0, totalDownTime: 0 },
    { id: 6, code: 'ASM-001', name: '조립 라인 1', type: '조립', status: '가동중', startTime: null, totalRunTime: 0, totalDownTime: 0 },
  ]);

  // 설비 가동 이력
  const [equipmentLogs, setEquipmentLogs] = useState([]);

  // ★ 설비 가동 시작
  const startEquipment = (equipmentId, workOrderNo) => {
    const now = new Date();
    setEquipments(prev => prev.map(eq => {
      if (eq.id === equipmentId) {
        return {
          ...eq,
          status: '가동중',
          startTime: now.toISOString(),
          currentWorkOrder: workOrderNo,
        };
      }
      return eq;
    }));

    setEquipmentLogs(prev => [...prev, {
      id: Date.now(),
      equipmentId,
      workOrderNo,
      type: '가동시작',
      timestamp: now.toISOString(),
      operator: currentUser.name,
    }]);
  };

  // ★ 설비 가동 종료
  const stopEquipment = (equipmentId, reason = '작업완료') => {
    const now = new Date();
    setEquipments(prev => prev.map(eq => {
      if (eq.id === equipmentId && eq.startTime) {
        const runTime = (now - new Date(eq.startTime)) / 1000 / 60; // 분 단위
        return {
          ...eq,
          status: reason === '작업완료' ? '대기' : '비가동',
          startTime: null,
          totalRunTime: eq.totalRunTime + runTime,
          currentWorkOrder: null,
          lastStopReason: reason,
        };
      }
      return eq;
    }));

    setEquipmentLogs(prev => [...prev, {
      id: Date.now(),
      equipmentId,
      type: '가동종료',
      reason,
      timestamp: now.toISOString(),
      operator: currentUser.name,
    }]);
  };

  // ★ 설비 가동률 계산
  const calculateEquipmentUtilization = (equipmentId, periodDays = 30) => {
    const equipment = equipments.find(eq => eq.id === equipmentId);
    if (!equipment) return 0;

    const totalAvailableMinutes = periodDays * 24 * 60; // 총 가용 시간 (분)
    const utilizationRate = (equipment.totalRunTime / totalAvailableMinutes) * 100;

    return Math.min(Math.round(utilizationRate * 10) / 10, 100); // 소수점 1자리
  };

  // ★ 전체 설비 가동률 요약
  const getEquipmentUtilizationSummary = () => {
    const summary = {
      total: equipments.length,
      running: equipments.filter(eq => eq.status === '가동중').length,
      idle: equipments.filter(eq => eq.status === '대기').length,
      maintenance: equipments.filter(eq => eq.status === '점검중').length,
      down: equipments.filter(eq => eq.status === '비가동').length,
      avgUtilization: 0,
    };

    if (summary.total > 0) {
      const totalUtil = equipments.reduce((sum, eq) => sum + calculateEquipmentUtilization(eq.id), 0);
      summary.avgUtilization = Math.round(totalUtil / summary.total);
    }

    return summary;
  };

  // ═══════════════════════════════════════════════════════════════════
  // 검사성적서 자동생성 시스템
  // ═══════════════════════════════════════════════════════════════════

  // 검사성적서 목록
  const [inspectionCertificates, setInspectionCertificates] = useState([]);

  // ★ 검사성적서 자동생성 (검사 합격 시 호출)
  const autoGenerateInspectionCertificate = (inspection, inspectionType) => {
    const today = new Date();
    const certNo = `CERT-${formatDateCode(today)}-${String(inspectionCertificates.length + 1).padStart(3, '0')}`;

    // 검사 유형별 성적서 템플릿
    const certTypeMap = {
      'incoming': { type: 'IQC', title: '수입검사 성적서' },
      'process': { type: 'PQC', title: '중간검사 성적서' },
      'product': { type: 'FQC', title: '제품검사 성적서' },
    };

    const certConfig = certTypeMap[inspectionType] || certTypeMap['product'];

    const newCertificate = {
      id: inspectionCertificates.length + 1,
      certNo,
      type: certConfig.type,
      title: certConfig.title,
      inspectionLotNo: inspection.lotNo,
      inspectionDate: inspection.inspectionDate || today.toISOString().split('T')[0],
      itemName: inspection.itemName || inspection.productName || inspection.materialName,
      qty: inspection.qty || inspection.passQty,
      passQty: inspection.passQty || inspection.qty,
      failQty: inspection.failQty || 0,
      result: inspection.result || '합격',
      inspector: inspection.inspector || currentUser.name,
      // 검사 항목 상세
      inspectionItems: inspection.inspectionItems || [
        { item: '외관검사', standard: '표면결함없음', result: '합격', value: 'OK' },
        { item: '치수검사', standard: '규격±0.5mm', result: '합격', value: '규격내' },
        { item: '기능검사', standard: '정상작동', result: '합격', value: 'OK' },
      ],
      // 메타 정보
      orderNo: inspection.orderNo,
      workOrderNo: inspection.workOrderNo,
      customerName: inspection.customerName,
      vendorName: inspection.vendorName,
      // 발행 정보
      issuedBy: currentUser.name,
      issuedAt: today.toISOString(),
      status: '발행완료',
      // 승인 정보
      approvalLine: {
        inspector: { name: currentUser.name, date: today.toISOString().split('T')[0], status: 'approved' },
        reviewer: { name: '', date: '', status: 'pending' },
        approver: { name: '', date: '', status: 'pending' },
      },
    };

    setInspectionCertificates(prev => [...prev, newCertificate]);

    console.log(`[검사성적서 자동생성] ${certNo} - ${certConfig.title}`);
    return newCertificate;
  };

  // ★ 검사 합격 시 성적서 자동 발행 (제품검사 완료 핸들러)
  const handleProductInspectionComplete = (inspectionId, result, inspectorName) => {
    const today = new Date().toISOString().split('T')[0];

    setProductInspections(prev => prev.map(insp => {
      if (insp.id === inspectionId) {
        const updatedInsp = {
          ...insp,
          status: result,
          inspectionDate: today,
          inspector: inspectorName || currentUser.name,
          result,
        };

        // ★ 합격 시 검사성적서 자동 생성
        if (result === '합격') {
          const cert = autoGenerateInspectionCertificate(updatedInsp, 'product');
          updatedInsp.certificateNo = cert.certNo;
        }

        // 불합격 시 NCR 자동 생성
        if (result === '불합격') {
          const ncrNo = `NCR-${formatDateCode(new Date())}-${String(defects.length + 1).padStart(3, '0')}`;
          const newDefect = {
            id: defects.length + 1,
            ncrNo,
            registDate: today,
            source: 'FQC',
            sourceType: '제품검사',
            sourceNo: insp.lotNo,
            itemName: insp.productName,
            defectQty: insp.qty,
            totalQty: insp.qty,
            defectType: '제품불량',
            description: `제품검사 불합격`,
            status: '처리대기',
            registeredBy: currentUser.name,
          };
          setDefects(prev => [...prev, newDefect]);
          updatedInsp.ncrNo = ncrNo;
        }

        return updatedInsp;
      }
      return insp;
    }));

    if (result === '합격') {
      alert(`✅ 제품검사가 완료되었습니다.\n\n결과: 합격\n\n📄 검사성적서가 자동 발행되었습니다.\n[품질관리 > 검사성적서]에서 확인하세요.`);
    } else {
      alert(`⚠️ 제품검사가 완료되었습니다.\n\n결과: 불합격\n\n📋 NCR(부적합보고서)가 자동 생성되었습니다.\n[품질관리 > 부적합관리]에서 처리하세요.`);
    }
  };

  // 품목유형 정의 (7개 - 모든 회사 공통)
  const itemTypes = [
    { code: 'FG', name: '제품', nameEn: 'Finished Goods' },
    { code: 'SA', name: '조립부품', nameEn: 'Sub-Assembly' },
    { code: 'BP', name: '절곡부품', nameEn: 'Bending Part' },
    { code: 'PP', name: '구매부품', nameEn: 'Purchased Part' },
    { code: 'SM', name: '부자재', nameEn: 'Sub Material' },
    { code: 'RM', name: '원자재', nameEn: 'Raw Material' },
    { code: 'CS', name: '소모품', nameEn: 'Consumables' },
  ];

  // ═══════════════════════════════════════════════════════════════════
  // LOT NO 코드 체계 (스크린샷 기반)
  // 형식: [제품]-[종류]-[날짜코드]-[모양&길이]
  // 예: G-I-4A05-53 → 가이드레일-일반-2024년5월5일-C형3000
  // ═══════════════════════════════════════════════════════════════════
  const lotCodeConfig = {
    // 제품 코드 (첫 번째 자리)
    productCodes: [
      { code: 'G', name: '가이드레일', description: 'Guide Rail' },
      { code: 'C', name: '케이스', description: 'Case' },
      { code: 'B', name: '하단마감재', description: 'Bottom Finish' },
      { code: 'S', name: '연기차단재', description: 'Smoke Block' },
      { code: 'L', name: 'L-Bar', description: 'L-Bar' },
      { code: 'M', name: '모터', description: 'Motor' },
      { code: 'T', name: '샤프트', description: 'Shaft' },
    ],
    // 종류 코드 (두 번째 자리)
    typeCodes: [
      { code: 'I', name: '일반', description: 'General' },
      { code: 'S', name: 'SUS마감', description: 'SUS Finish' },
      { code: 'E', name: 'EGI', description: 'EGI' },
      { code: 'D', name: 'D형', description: 'D-Type' },
      { code: 'C', name: 'C형', description: 'C-Type' },
      { code: 'F', name: '전면부', description: 'Front' },
      { code: 'B', name: '후면코너부', description: 'Back Corner' },
      { code: 'L', name: '린텔부', description: 'Lintel' },
      { code: 'P', name: '점검구', description: 'Inspection' },
    ],
    // 날짜 코드 (세 번째 자리) - [연도(A-Z)][월(01-12)][일(01-31)]
    // 연도: 2024=4A, 2025=5B, 2026=6C...
    yearCodes: {
      2024: '4A', 2025: '5B', 2026: '6C', 2027: '7D', 2028: '8E', 2029: '9F', 2030: '0G'
    },
    // 모양&길이 코드 (네 번째 자리) - 모양코드(1자리) + 길이코드(1-2자리)
    shapeLengthCodes: {
      shapes: [
        { code: '1', name: '본체', description: 'Body' },
        { code: '2', name: 'D형', description: 'D-Type' },
        { code: '3', name: 'C형', description: 'C-Type' },
        { code: '4', name: 'SUS마감', description: 'SUS' },
        { code: '5', name: 'EGI', description: 'EGI' },
        { code: '6', name: '전면부', description: 'Front' },
        { code: '7', name: '후면코너부', description: 'Back' },
        { code: '8', name: '린텔부', description: 'Lintel' },
        { code: '9', name: '점검구', description: 'Inspect' },
      ],
      lengths: [
        { code: '1', length: 1219, display: '1219' },
        { code: '2', length: 2438, display: '2438' },
        { code: '3', length: 3000, display: '3000' },
        { code: '4', length: 3500, display: '3500' },
        { code: '5', length: 4000, display: '4000' },
        { code: '6', length: 4300, display: '4300' },
        { code: '7', length: 4500, display: '4500' },
      ]
    }
  };

  // Lot No 생성 함수
  const generateLotNo = (productCode, typeCode, date, shapeCode, lengthCode, sequence = 1) => {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const yearCode = lotCodeConfig.yearCodes[year] || `${year % 10}X`;
    const dateCode = `${yearCode}${month}`;
    const shapeLengthCode = `${shapeCode}${lengthCode}`;
    return `${productCode}-${typeCode}-${dateCode}-${shapeLengthCode}`;
  };

  // ═══════════════════════════════════════════════════════════════════
  // 판매 LOT 번호 체계 (스크린샷 기반)
  // 형식: [현장코드]-[수주일자]-[순번]
  // 예: GYS-241105-001 → 광양제철소-2024년11월5일-1번
  // ═══════════════════════════════════════════════════════════════════
  const salesLotConfig = {
    // 현장 코드 예시 (실제 데이터는 sites에서 관리)
    siteCodeExamples: [
      { code: 'GYS', name: '광양제철소' },
      { code: 'POS', name: '포항제철' },
      { code: 'SEC', name: '삼성전자' },
      { code: 'HYN', name: '현대' },
    ],
    // 날짜 형식: YYMMDD
    dateFormat: 'YYMMDD',
    // 순번: 3자리 (001-999)
    sequenceDigits: 3,
  };

  // 판매 LOT No 생성 함수
  const generateSalesLotNo = (siteCode, orderDate, sequence) => {
    const d = new Date(orderDate);
    const yy = String(d.getFullYear()).slice(-2);
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const dd = String(d.getDate()).padStart(2, '0');
    const seq = String(sequence).padStart(3, '0');
    return `${siteCode}-${yy}${mm}${dd}-${seq}`;
  };

  // ═══════════════════════════════════════════════════════════════════
  // 인정제품 코드 체계 (스크린샷 기반)
  // KS, KQ 인정 제품 코드
  // ═══════════════════════════════════════════════════════════════════
  const certifiedProductCodes = [
    // KS 인정 제품 (일반형)
    {
      code: 'KSS01', name: 'KS 스크린방화셔터 일반형', certType: 'KS', productType: '스크린', subType: '일반형',
      description: 'KS F 3109 적합 스크린방화셔터', fireRating: '1시간'
    },
    {
      code: 'KSS02', name: 'KS 스크린방화셔터 대형', certType: 'KS', productType: '스크린', subType: '대형',
      description: 'KS F 3109 적합 대형 스크린방화셔터', fireRating: '1시간'
    },
    {
      code: 'KSL01', name: 'KS 슬랫방화셔터 일반형', certType: 'KS', productType: '슬랫', subType: '일반형',
      description: 'KS F 3109 적합 슬랫방화셔터', fireRating: '1시간'
    },
    {
      code: 'KSL02', name: 'KS 슬랫방화셔터 대형', certType: 'KS', productType: '슬랫', subType: '대형',
      description: 'KS F 3109 적합 대형 슬랫방화셔터', fireRating: '1시간'
    },
    {
      code: 'KSB01', name: 'KS 절곡방화셔터 일반형', certType: 'KS', productType: '절곡', subType: '일반형',
      description: 'KS F 3109 적합 절곡방화셔터', fireRating: '1시간'
    },

    // KQ (품질인정) 제품
    {
      code: 'KQTS01', name: 'KQ 스크린방화셔터 특수형', certType: 'KQ', productType: '스크린', subType: '특수형',
      description: '품질인정 특수 스크린방화셔터', fireRating: '2시간'
    },
    {
      code: 'KQTS02', name: 'KQ 스크린방화셔터 차연형', certType: 'KQ', productType: '스크린', subType: '차연형',
      description: '품질인정 차연 스크린방화셔터', fireRating: '1시간', smokeBlock: true
    },
    {
      code: 'KQTL01', name: 'KQ 슬랫방화셔터 특수형', certType: 'KQ', productType: '슬랫', subType: '특수형',
      description: '품질인정 특수 슬랫방화셔터', fireRating: '2시간'
    },
    {
      code: 'KQTL02', name: 'KQ 슬랫방화셔터 차연형', certType: 'KQ', productType: '슬랫', subType: '차연형',
      description: '품질인정 차연 슬랫방화셔터', fireRating: '1시간', smokeBlock: true
    },
    {
      code: 'KQTB01', name: 'KQ 절곡방화셔터 특수형', certType: 'KQ', productType: '절곡', subType: '특수형',
      description: '품질인정 특수 절곡방화셔터', fireRating: '2시간'
    },
    {
      code: 'KQTB02', name: 'KQ 절곡방화셔터 차연형', certType: 'KQ', productType: '절곡', subType: '차연형',
      description: '품질인정 차연 절곡방화셔터', fireRating: '1시간', smokeBlock: true
    },

    // 기타 인정 제품
    {
      code: 'CERTS01', name: '내화성능 인정 스크린방화셔터', certType: '내화인정', productType: '스크린', subType: '내화형',
      description: '내화성능 인정 스크린방화셔터', fireRating: '3시간'
    },
    {
      code: 'CERTL01', name: '내화성능 인정 슬랫방화셔터', certType: '내화인정', productType: '슬랫', subType: '내화형',
      description: '내화성능 인정 슬랫방화셔터', fireRating: '3시간'
    },
  ];

  // 인정제품 코드로 제품 정보 조회
  const getCertifiedProduct = (code) => certifiedProductCodes.find(p => p.code === code);

  // ═══════════════════════════════════════════════════════════════════
  // 원자재 입고 LOT 관리 (스크린샷 기반)
  // 형식: [자재코드]-[입고일자]-[순번]
  // ═══════════════════════════════════════════════════════════════════
  const [rawMaterialLots, setRawMaterialLots] = useState([
    {
      id: 1, lotNo: 'EGI155-241101-001', materialCode: 'EGI-1.55T', materialName: 'EGI 철판 1.55T',
      inboundDate: '2024-11-01', qty: 100, remainQty: 85, unit: '매', supplier: '포스코', location: 'D-01'
    },
    {
      id: 2, lotNo: 'EGI155-241105-001', materialCode: 'EGI-1.55T', materialName: 'EGI 철판 1.55T',
      inboundDate: '2024-11-05', qty: 150, remainQty: 150, unit: '매', supplier: '포스코', location: 'D-01'
    },
    {
      id: 3, lotNo: 'SUS12-241103-001', materialCode: 'SUS-1.2T', materialName: 'SUS 철판 1.2T',
      inboundDate: '2024-11-03', qty: 50, remainQty: 42, unit: '매', supplier: '포스코', location: 'D-02'
    },
    {
      id: 4, lotNo: 'SLT-COL-241102-001', materialCode: 'SLT-MAT-001', materialName: '슬랫 코일',
      inboundDate: '2024-11-02', qty: 500, remainQty: 320, unit: 'KG', supplier: '동국제강', location: 'C-01'
    },
  ]);

  // ═══════════════════════════════════════════════════════════════════
  // 생산 LOT 관리 (스크린샷 기반)
  // 형식: [제품코드]-[생산일자]-[순번]
  // ═══════════════════════════════════════════════════════════════════
  const [productionLots, setProductionLots] = useState([
    {
      id: 1, lotNo: 'G-I-5B11-33', productCode: 'RC30', productName: '가이드레일(벽면형) C형 3000',
      productionDate: '2025-11-05', qty: 100, rawMaterialLots: ['EGI155-241101-001'], status: '완료'
    },
    {
      id: 2, lotNo: 'G-I-5B11-35', productCode: 'RC35', productName: '가이드레일(벽면형) C형 3500',
      productionDate: '2025-11-05', qty: 80, rawMaterialLots: ['EGI155-241101-001'], status: '완료'
    },
    {
      id: 3, lotNo: 'C-B-5B11-73', productCode: 'CB30', productName: '케이스(후면코너부) 3000',
      productionDate: '2025-11-06', qty: 120, rawMaterialLots: ['EGI155-241105-001'], status: '진행중'
    },
    {
      id: 4, lotNo: 'B-E-5B11-53', productCode: 'BE30', productName: '하단마감재(스크린) EGI 3000',
      productionDate: '2025-11-07', qty: 60, rawMaterialLots: ['EGI155-241105-001'], status: '예정'
    },
  ]);

  // 재고 데이터 (확장: itemType, category 필드 추가)
  // ★ 품목코드는 공통코드관리(codeRuleConfig.js) 규칙 준수: {품목명}-{규격}
  const [inventory, setInventory] = useState([
    // ═══════════════════════════════════════════
    // 원자재 (Raw Material) - 패턴: {품목명}-{규격}
    // ═══════════════════════════════════════════
    {
      id: 1, materialCode: '스크린원단-백색-0.3T', materialName: '스크린 원단 (백색)', unit: '㎡', stock: 500, minStock: 100, location: 'A-01', lastUpdated: '2025-03-01',
      itemType: '원자재', category: '원단', subCategory: '스크린용', lotCount: 3, oldestLotDays: 21
    },
    {
      id: 6, materialCode: '슬랫코일-1.0T', materialName: '슬랫 코일', unit: 'KG', stock: 1500, minStock: 300, location: 'C-01', lastUpdated: '2025-03-01',
      itemType: '원자재', category: '코일', subCategory: '슬랫용', lotCount: 4, oldestLotDays: 35
    },
    {
      id: 8, materialCode: '철판-EGI-1.55T', materialName: 'EGI 철판 1.55T', unit: '매', stock: 200, minStock: 50, location: 'D-01', lastUpdated: '2025-03-01',
      itemType: '원자재', category: '철판', subCategory: 'EGI', lotCount: 2, oldestLotDays: 14
    },
    {
      id: 9, materialCode: '철판-SUS-1.2T', materialName: 'SUS 철판 1.2T', unit: '매', stock: 80, minStock: 20, location: 'D-02', lastUpdated: '2025-03-01',
      itemType: '원자재', category: '철판', subCategory: 'SUS', lotCount: 2, oldestLotDays: 7
    },

    // ═══════════════════════════════════════════
    // 부자재 (Sub Material) - 패턴: {품목명}-{규격}
    // ═══════════════════════════════════════════
    {
      id: 2, materialCode: '앤드락-표준', materialName: '앤드락', unit: 'EA', stock: 800, minStock: 200, location: 'A-02', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '체결류', lotCount: 2, oldestLotDays: 12
    },
    {
      id: 3, materialCode: '하단바-알루미늄', materialName: '하단바', unit: 'EA', stock: 120, minStock: 30, location: 'A-03', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '프레임류', lotCount: 1, oldestLotDays: 5
    },
    {
      id: 4, materialCode: '미싱실-백색', materialName: '미싱실', unit: 'M', stock: 5000, minStock: 1000, location: 'A-04', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '봉제류', lotCount: 3, oldestLotDays: 28
    },
    {
      id: 7, materialCode: '미미자재-표준', materialName: '미미자재', unit: 'EA', stock: 600, minStock: 150, location: 'C-02', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '마감류', lotCount: 2, oldestLotDays: 18
    },
    {
      id: 50, materialCode: '리벳-4.8×12', materialName: '리벳', unit: 'EA', stock: 5000, minStock: 1000, location: 'B-01', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '체결류', lotCount: 5, oldestLotDays: 45
    },
    {
      id: 51, materialCode: '육각볼트-M8×20', materialName: '육각볼트 M8', unit: 'EA', stock: 3000, minStock: 500, location: 'B-02', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '체결류', lotCount: 4, oldestLotDays: 32
    },
    {
      id: 52, materialCode: '실리콘-투명', materialName: '실리콘', unit: 'EA', stock: 200, minStock: 50, location: 'B-03', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '접착류', lotCount: 1, oldestLotDays: 10
    },

    // ═══════════════════════════════════════════
    // 소모품 (Consumables) - 패턴: {품목명}-{규격}
    // ═══════════════════════════════════════════
    {
      id: 5, materialCode: '포장박스-대형', materialName: '포장박스', unit: 'EA', stock: 200, minStock: 50, location: 'B-01', lastUpdated: '2025-03-01',
      itemType: '소모품', category: '포장', lotCount: 2, oldestLotDays: 8
    },
    {
      id: 53, materialCode: '포장테이프-투명', materialName: '포장테이프', unit: 'EA', stock: 100, minStock: 30, location: 'B-04', lastUpdated: '2025-03-01',
      itemType: '소모품', category: '포장', lotCount: 1, oldestLotDays: 3
    },

    // ═══════════════════════════════════════════
    // 절곡부품 - 가이드레일 (Bending Part)
    // ═══════════════════════════════════════════
    {
      id: 101, materialCode: 'RC24', materialName: '가이드레일(벽면형) C형 2438', unit: 'EA', stock: 200, minStock: 50, location: 'E-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: 'C형', length: 2438, producedQty: 200, usedQty: 0
    },
    {
      id: 102, materialCode: 'RC30', materialName: '가이드레일(벽면형) C형 3000', unit: 'EA', stock: 737, minStock: 100, location: 'E-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: 'C형', length: 3000, producedQty: 737, usedQty: 0
    },
    {
      id: 103, materialCode: 'RC35', materialName: '가이드레일(벽면형) C형 3500', unit: 'EA', stock: 608, minStock: 100, location: 'E-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: 'C형', length: 3500, producedQty: 608, usedQty: 0
    },
    {
      id: 104, materialCode: 'RC40', materialName: '가이드레일(벽면형) C형 4000', unit: 'EA', stock: 421, minStock: 80, location: 'E-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: 'C형', length: 4000, producedQty: 421, usedQty: 0
    },
    {
      id: 105, materialCode: 'RC43', materialName: '가이드레일(벽면형) C형 4300', unit: 'EA', stock: 550, minStock: 80, location: 'E-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: 'C형', length: 4300, producedQty: 550, usedQty: 0
    },
    {
      id: 106, materialCode: 'RD24', materialName: '가이드레일(벽면형) D형 2438', unit: 'EA', stock: 200, minStock: 50, location: 'E-02', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: 'D형', length: 2438, producedQty: 200, usedQty: 0
    },
    {
      id: 107, materialCode: 'RD30', materialName: '가이드레일(벽면형) D형 3000', unit: 'EA', stock: 650, minStock: 100, location: 'E-02', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: 'D형', length: 3000, producedQty: 650, usedQty: 0
    },
    {
      id: 108, materialCode: 'RD35', materialName: '가이드레일(벽면형) D형 3500', unit: 'EA', stock: 510, minStock: 80, location: 'E-02', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: 'D형', length: 3500, producedQty: 510, usedQty: 0
    },
    {
      id: 109, materialCode: 'RD40', materialName: '가이드레일(벽면형) D형 4000', unit: 'EA', stock: 352, minStock: 80, location: 'E-02', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: 'D형', length: 4000, producedQty: 352, usedQty: 0
    },
    {
      id: 110, materialCode: 'RM24', materialName: '가이드레일(벽면형) 본체 2438', unit: 'EA', stock: 620, minStock: 100, location: 'E-03', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: '본체', length: 2438, producedQty: 620, usedQty: 0
    },
    {
      id: 111, materialCode: 'RM30', materialName: '가이드레일(벽면형) 본체 3000', unit: 'EA', stock: 604, minStock: 100, location: 'E-03', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: '본체', length: 3000, producedQty: 604, usedQty: 0
    },
    {
      id: 112, materialCode: 'RS24', materialName: '가이드레일(벽면형) SUS마감 2438', unit: 'EA', stock: 396, minStock: 80, location: 'E-04', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: 'SUS마감', length: 2438, producedQty: 396, usedQty: 0
    },
    {
      id: 113, materialCode: 'RS30', materialName: '가이드레일(벽면형) SUS마감 3000', unit: 'EA', stock: 804, minStock: 100, location: 'E-04', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '가이드레일', subCategory: 'SUS마감', length: 3000, producedQty: 804, usedQty: 0
    },

    // ═══════════════════════════════════════════
    // 절곡부품 - 케이스 (Bending Part)
    // ═══════════════════════════════════════════
    {
      id: 201, materialCode: 'CB12', materialName: '케이스(후면코너부) 1219', unit: 'EA', stock: 652, minStock: 100, location: 'F-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '후면코너부', length: 1219, producedQty: 652, usedQty: 0
    },
    {
      id: 202, materialCode: 'CB24', materialName: '케이스(후면코너부) 2438', unit: 'EA', stock: 1117, minStock: 200, location: 'F-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '후면코너부', length: 2438, producedQty: 1117, usedQty: 0
    },
    {
      id: 203, materialCode: 'CB30', materialName: '케이스(후면코너부) 3000', unit: 'EA', stock: 1081, minStock: 200, location: 'F-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '후면코너부', length: 3000, producedQty: 1081, usedQty: 0
    },
    {
      id: 204, materialCode: 'CB35', materialName: '케이스(후면코너부) 3500', unit: 'EA', stock: 495, minStock: 100, location: 'F-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '후면코너부', length: 3500, producedQty: 715, usedQty: 220
    },
    {
      id: 205, materialCode: 'CB40', materialName: '케이스(후면코너부) 4000', unit: 'EA', stock: 1440, minStock: 200, location: 'F-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '후면코너부', length: 4000, producedQty: 1440, usedQty: 0
    },
    {
      id: 206, materialCode: 'CF12', materialName: '케이스(전면부) 1219', unit: 'EA', stock: 191, minStock: 50, location: 'F-02', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '전면부', length: 1219, producedQty: 191, usedQty: 0
    },
    {
      id: 207, materialCode: 'CF24', materialName: '케이스(전면부) 2438', unit: 'EA', stock: 241, minStock: 50, location: 'F-02', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '전면부', length: 2438, producedQty: 241, usedQty: 0
    },
    {
      id: 208, materialCode: 'CF30', materialName: '케이스(전면부) 3000', unit: 'EA', stock: 271, minStock: 50, location: 'F-02', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '���면부', length: 3000, producedQty: 271, usedQty: 0
    },
    {
      id: 209, materialCode: 'CL12', materialName: '케이스(린텔부) 1219', unit: 'EA', stock: 598, minStock: 100, location: 'F-03', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '린텔부', length: 1219, producedQty: 598, usedQty: 0
    },
    {
      id: 210, materialCode: 'CL24', materialName: '케이스(린텔부) 2438', unit: 'EA', stock: 732, minStock: 100, location: 'F-03', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '린텔부', length: 2438, producedQty: 732, usedQty: 0
    },
    {
      id: 211, materialCode: 'CL30', materialName: '케이스(린텔부) 3000', unit: 'EA', stock: 576, minStock: 100, location: 'F-03', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '린텔부', length: 3000, producedQty: 576, usedQty: 0
    },
    {
      id: 212, materialCode: 'CP12', materialName: '케이스(점검구) 1219', unit: 'EA', stock: 300, minStock: 50, location: 'F-04', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '점검구', length: 1219, producedQty: 300, usedQty: 0
    },
    {
      id: 213, materialCode: 'CP24', materialName: '케이스(점검구) 2438', unit: 'EA', stock: 840, minStock: 100, location: 'F-04', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '점검구', length: 2438, producedQty: 840, usedQty: 0
    },
    {
      id: 214, materialCode: 'CP30', materialName: '케이스(점검구) 3000', unit: 'EA', stock: 766, minStock: 100, location: 'F-04', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '케이스', subCategory: '점검구', length: 3000, producedQty: 766, usedQty: 0
    },

    // ═══════════════════════════════════════════
    // 절곡부품 - 하단마감재 (Bending Part)
    // ═══════════════════════════════════════════
    {
      id: 301, materialCode: 'BE30', materialName: '하단마감재(스크린) EGI 3000', unit: 'EA', stock: 396, minStock: 80, location: 'G-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '하단마감재', subCategory: 'EGI', length: 3000, producedQty: 396, usedQty: 0
    },
    {
      id: 302, materialCode: 'BE40', materialName: '하단마감재(스크린) EGI 4000', unit: 'EA', stock: 265, minStock: 50, location: 'G-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '하단마감재', subCategory: 'EGI', length: 4000, producedQty: 265, usedQty: 0
    },
    {
      id: 303, materialCode: 'BS24', materialName: '하단마감재(스크린) SUS 2438', unit: 'EA', stock: 99, minStock: 30, location: 'G-02', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '하단마감재', subCategory: 'SUS', length: 2438, producedQty: 99, usedQty: 0
    },
    {
      id: 304, materialCode: 'BS30', materialName: '하단마감재(스크린) SUS 3000', unit: 'EA', stock: 1144, minStock: 200, location: 'G-02', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '하단마감재', subCategory: 'SUS', length: 3000, producedQty: 1144, usedQty: 0
    },
    {
      id: 305, materialCode: 'BS40', materialName: '하단마감재(스크린) SUS 4000', unit: 'EA', stock: 1150, minStock: 200, location: 'G-02', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '하단마감재', subCategory: 'SUS', length: 4000, producedQty: 1150, usedQty: 0
    },
    {
      id: 306, materialCode: 'TS40', materialName: '하단마감재(철재) SUS 4000', unit: 'EA', stock: 1, minStock: 10, location: 'G-03', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '하단마감재', subCategory: '철재SUS', length: 4000, producedQty: 1, usedQty: 0
    },

    // ═══════════════════════════════════════════
    // 절곡부품 - 연기차단재/L-Bar (Bending Part)
    // ═══════════════════════════════════════════
    {
      id: 401, materialCode: 'GI24', materialName: '연기차단재 화이바원단 2438', unit: 'EA', stock: 1412, minStock: 200, location: 'H-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '연기차단재', subCategory: '화이바원단', length: 2438, producedQty: 1412, usedQty: 0
    },
    {
      id: 402, materialCode: 'GI30', materialName: '연기차단재 화이바원단 3000', unit: 'EA', stock: 1984, minStock: 300, location: 'H-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '연기차단재', subCategory: '화이바원단', length: 3000, producedQty: 1984, usedQty: 0
    },
    {
      id: 403, materialCode: 'GI35', materialName: '연기차단재 화이바원단 3500', unit: 'EA', stock: 1165, minStock: 200, location: 'H-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '연기차단재', subCategory: '화이바원단', length: 3500, producedQty: 1165, usedQty: 0
    },
    {
      id: 404, materialCode: 'GI40', materialName: '연기차단재 화이바원단 4000', unit: 'EA', stock: 1171, minStock: 200, location: 'H-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '연기차단재', subCategory: '화이바원단', length: 4000, producedQty: 1171, usedQty: 0
    },
    {
      id: 405, materialCode: 'GI43', materialName: '연기차단재 화이바원단 4300', unit: 'EA', stock: 1000, minStock: 200, location: 'H-01', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '연기차단재', subCategory: '화이바원단', length: 4300, producedQty: 1000, usedQty: 0
    },
    {
      id: 406, materialCode: 'GI83', materialName: '연기차단재 화이바원단 W80×3000', unit: 'EA', stock: 3561, minStock: 500, location: 'H-02', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: '연기차단재', subCategory: '화이바원단(W80)', length: 3000, producedQty: 3561, usedQty: 0
    },
    {
      id: 407, materialCode: 'LA30', materialName: 'L-Bar 스크린용 3000', unit: 'EA', stock: 1443, minStock: 200, location: 'H-03', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: 'L-Bar', subCategory: '스크린용', length: 3000, producedQty: 1443, usedQty: 0
    },
    {
      id: 408, materialCode: 'LA40', materialName: 'L-Bar 스크린용 4000', unit: 'EA', stock: 676, minStock: 100, location: 'H-03', lastUpdated: '2025-03-01',
      itemType: '절곡부품', category: 'L-Bar', subCategory: '스크린용', length: 4000, producedQty: 676, usedQty: 0
    },

    // ═══════════════════════════════════════════
    // 구매부품 (Purchased Part) - 코드규칙: {품목명}-{규격} (규격 = 전원+용량+유무선)
    // ═══════════════════════════════════════════
    {
      id: 501, materialCode: '전동개폐기-220V150KG유선', materialName: '전동개폐기 150KG 220V 유선', unit: 'EA', stock: 300, minStock: 50, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '150KG/220V/유선', supplier: '대한', lotCount: 4, oldestLotDays: 25
    },
    {
      id: 502, materialCode: '전동개폐기-220V300KG유선', materialName: '전동개폐기 300KG 220V 유선', unit: 'EA', stock: 508, minStock: 80, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '300KG/220V/유선', supplier: '대한', lotCount: 6, oldestLotDays: 42
    },
    {
      id: 503, materialCode: '전동개폐기-220V400KG유선', materialName: '전동개폐기 400KG 220V 유선', unit: 'EA', stock: 136, minStock: 30, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '400KG/220V/유선', supplier: '대한', lotCount: 2, oldestLotDays: 18
    },
    {
      id: 504, materialCode: '연동제어기-매립형유선', materialName: '연동제어기 매립형 유선', unit: 'EA', stock: 500, minStock: 80, location: 'I-02', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '연동제어기', spec: '매립/유선', supplier: '대한', lotCount: 5, oldestLotDays: 35
    },
    {
      id: 505, materialCode: '연동제어기-노출형유선', materialName: '연동제어기 노출형 유선', unit: 'EA', stock: 500, minStock: 80, location: 'I-02', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '연동제어기', spec: '노출/유선', supplier: '대한', lotCount: 5, oldestLotDays: 28
    },
    {
      id: 506, materialCode: '감기샤프트-114.3×2TL4500', materialName: '감기샤프트 114.3×2T L:4500', unit: 'EA', stock: 41, minStock: 10, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '114.3×2T', length: 4500, lotCount: 2, oldestLotDays: 65
    },
    {
      id: 507, materialCode: '감기샤프트-139.8×2.9TL4500', materialName: '감기샤프트 139.8×2.9T L:4500', unit: 'EA', stock: 35, minStock: 10, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '139.8×2.9T', length: 4500, lotCount: 2, oldestLotDays: 52
    },

    // ═══════════════════════════════════════════
    // 구매부품 - 전동개폐기(모터) 확장 - 코드규칙: {품목명}-{전원}{용량}{유무선}
    // ═══════════════════════════════════════════
    // 150KG
    {
      id: 508, materialCode: '전동개폐기-380V150KG유선', materialName: '전동개폐기 150KG 380V 유선', unit: 'EA', stock: 50, minStock: 10, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '150KG/380V/유선', kg: 150, voltage: 380, wireType: '유선', supplier: '대한'
    },
    {
      id: 509, materialCode: '전동개폐기-220V150KG무선', materialName: '전동개폐기 150KG 220V 무선', unit: 'EA', stock: 80, minStock: 15, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '150KG/220V/무선', kg: 150, voltage: 220, wireType: '무선', supplier: '대한'
    },
    {
      id: 510, materialCode: '전동개폐기-380V150KG무선', materialName: '전동개폐기 150KG 380V 무선', unit: 'EA', stock: 30, minStock: 10, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '150KG/380V/무선', kg: 150, voltage: 380, wireType: '무선', supplier: '대한'
    },
    // 300KG
    {
      id: 511, materialCode: '전동개폐기-380V300KG유선', materialName: '전동개폐기 300KG 380V 유선', unit: 'EA', stock: 120, minStock: 20, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '300KG/380V/유선', kg: 300, voltage: 380, wireType: '유선', supplier: '대한'
    },
    {
      id: 512, materialCode: '전동개폐기-220V300KG무선', materialName: '전동개폐기 300KG 220V 무선', unit: 'EA', stock: 150, minStock: 25, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '300KG/220V/무선', kg: 300, voltage: 220, wireType: '무선', supplier: '대한'
    },
    {
      id: 513, materialCode: '전동개폐기-380V300KG무선', materialName: '전동개폐기 300KG 380V 무선', unit: 'EA', stock: 60, minStock: 15, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '300KG/380V/무선', kg: 300, voltage: 380, wireType: '무선', supplier: '대한'
    },
    // 400KG
    {
      id: 514, materialCode: '전동개폐기-380V400KG유선', materialName: '전동개폐기 400KG 380V 유선', unit: 'EA', stock: 80, minStock: 15, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '400KG/380V/유선', kg: 400, voltage: 380, wireType: '유선', supplier: '대한'
    },
    {
      id: 515, materialCode: '전동개폐기-220V400KG무선', materialName: '전동개폐기 400KG 220V 무선', unit: 'EA', stock: 45, minStock: 10, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '400KG/220V/무선', kg: 400, voltage: 220, wireType: '무선', supplier: '대한'
    },
    {
      id: 516, materialCode: '전동개폐기-380V400KG무선', materialName: '전동개폐기 400KG 380V 무선', unit: 'EA', stock: 35, minStock: 10, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '400KG/380V/무선', kg: 400, voltage: 380, wireType: '무선', supplier: '대한'
    },
    // 500KG
    {
      id: 517, materialCode: '전동개폐기-220V500KG유선', materialName: '전동개폐기 500KG 220V 유선', unit: 'EA', stock: 60, minStock: 15, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '500KG/220V/유선', kg: 500, voltage: 220, wireType: '유선', supplier: '대한'
    },
    {
      id: 518, materialCode: '전동개폐기-380V500KG유선', materialName: '전동개폐기 500KG 380V 유선', unit: 'EA', stock: 40, minStock: 10, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '500KG/380V/유선', kg: 500, voltage: 380, wireType: '유선', supplier: '대한'
    },
    {
      id: 519, materialCode: '전동개폐기-220V500KG무선', materialName: '전동개폐기 500KG 220V 무선', unit: 'EA', stock: 25, minStock: 8, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '500KG/220V/무선', kg: 500, voltage: 220, wireType: '무선', supplier: '대한'
    },
    {
      id: 520, materialCode: '전동개폐기-380V500KG무선', materialName: '전동개폐기 500KG 380V 무선', unit: 'EA', stock: 20, minStock: 5, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '500KG/380V/무선', kg: 500, voltage: 380, wireType: '무선', supplier: '대한'
    },
    // 600KG
    {
      id: 521, materialCode: '전동개폐기-220V600KG유선', materialName: '전동개폐기 600KG 220V 유선', unit: 'EA', stock: 35, minStock: 10, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '600KG/220V/유선', kg: 600, voltage: 220, wireType: '유선', supplier: '대한'
    },
    {
      id: 522, materialCode: '전동개폐기-380V600KG유선', materialName: '전동개폐기 600KG 380V 유선', unit: 'EA', stock: 30, minStock: 8, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '600KG/380V/유선', kg: 600, voltage: 380, wireType: '유선', supplier: '대한'
    },
    {
      id: 523, materialCode: '전동개폐기-220V600KG무선', materialName: '전동개폐기 600KG 220V 무선', unit: 'EA', stock: 15, minStock: 5, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '600KG/220V/무선', kg: 600, voltage: 220, wireType: '무선', supplier: '대한'
    },
    {
      id: 524, materialCode: '전동개폐기-380V600KG무선', materialName: '전동개폐기 600KG 380V 무선', unit: 'EA', stock: 12, minStock: 5, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '600KG/380V/무선', kg: 600, voltage: 380, wireType: '무선', supplier: '대한'
    },
    // 800KG
    {
      id: 525, materialCode: '전동개폐기-220V800KG유선', materialName: '전동개폐기 800KG 220V 유선', unit: 'EA', stock: 20, minStock: 5, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '800KG/220V/유선', kg: 800, voltage: 220, wireType: '유선', supplier: '대한'
    },
    {
      id: 526, materialCode: '전동개폐기-380V800KG유선', materialName: '전동개폐기 800KG 380V 유선', unit: 'EA', stock: 18, minStock: 5, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '800KG/380V/유선', kg: 800, voltage: 380, wireType: '유선', supplier: '대한'
    },
    {
      id: 527, materialCode: '전동개폐기-220V800KG무선', materialName: '전동개폐기 800KG 220V 무선', unit: 'EA', stock: 10, minStock: 3, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '800KG/220V/무선', kg: 800, voltage: 220, wireType: '무선', supplier: '대한'
    },
    {
      id: 528, materialCode: '전동개폐기-380V800KG무선', materialName: '전동개폐기 800KG 380V 무선', unit: 'EA', stock: 8, minStock: 3, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '800KG/380V/무선', kg: 800, voltage: 380, wireType: '무선', supplier: '대한'
    },
    // 1000KG
    {
      id: 529, materialCode: '전동개폐기-220V1000KG유선', materialName: '전동개폐기 1000KG 220V 유선', unit: 'EA', stock: 12, minStock: 3, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '1000KG/220V/유선', kg: 1000, voltage: 220, wireType: '유선', supplier: '대한'
    },
    {
      id: 530, materialCode: '전동개폐기-380V1000KG유선', materialName: '전동개폐기 1000KG 380V 유선', unit: 'EA', stock: 10, minStock: 3, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '1000KG/380V/유선', kg: 1000, voltage: 380, wireType: '유선', supplier: '대한'
    },
    {
      id: 531, materialCode: '전동개폐기-220V1000KG무선', materialName: '전동개폐기 1000KG 220V 무선', unit: 'EA', stock: 5, minStock: 2, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '1000KG/220V/무선', kg: 1000, voltage: 220, wireType: '무선', supplier: '대한'
    },
    {
      id: 532, materialCode: '전동개폐기-380V1000KG무선', materialName: '전동개폐기 1000KG 380V 무선', unit: 'EA', stock: 5, minStock: 2, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '1000KG/380V/무선', kg: 1000, voltage: 380, wireType: '무선', supplier: '대한'
    },

    // ═══════════════════════════════════════════
    // 구매부품 - 연동제어기 확장 - 코드규칙: {품목명}-{설치형태}{유무선}
    // ═══════════════════════════════════════════
    {
      id: 533, materialCode: '연동제어기-매립형무선', materialName: '연동제어기 매립형 무선', unit: 'EA', stock: 200, minStock: 50, location: 'I-02', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '연동제어기', spec: '매립/무선', installType: '매립', wireType: '무선', supplier: '대한'
    },
    {
      id: 534, materialCode: '연동제어기-노출형무선', materialName: '연동제어기 노출형 무선', unit: 'EA', stock: 200, minStock: 50, location: 'I-02', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '연동제어기', spec: '노출/무선', installType: '노출', wireType: '무선', supplier: '대한'
    },

    // ═══════════════════════════════════════════
    // 구매부품 - 감기샤프트 확장 - 코드규칙: {품목명}-{규격}L{길이}
    // 예: 감기샤프트-60.5*2.9TL3000
    // ═══════════════════════════════════════════
    // 60.5*2.9T
    {
      id: 535, materialCode: '감기샤프트-60.5*2.9TL3000', materialName: '감기샤프트 60.5*2.9T L:3000', unit: 'EA', stock: 100, minStock: 20, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '60.5*2.9T', diameter: 60.5, thickness: 2.9, length: 3000
    },
    {
      id: 536, materialCode: '감기샤프트-60.5*2.9TL3500', materialName: '감기샤프트 60.5*2.9T L:3500', unit: 'EA', stock: 80, minStock: 15, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '60.5*2.9T', diameter: 60.5, thickness: 2.9, length: 3500
    },
    {
      id: 537, materialCode: '감기샤프트-60.5*2.9TL4000', materialName: '감기샤프트 60.5*2.9T L:4000', unit: 'EA', stock: 60, minStock: 15, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '60.5*2.9T', diameter: 60.5, thickness: 2.9, length: 4000
    },
    {
      id: 538, materialCode: '감기샤프트-60.5*2.9TL4500', materialName: '감기샤프트 60.5*2.9T L:4500', unit: 'EA', stock: 50, minStock: 10, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '60.5*2.9T', diameter: 60.5, thickness: 2.9, length: 4500
    },
    // 76.3*2.8T
    {
      id: 539, materialCode: '감기샤프트-76.3*2.8TL3000', materialName: '감기샤프트 76.3*2.8T L:3000', unit: 'EA', stock: 90, minStock: 18, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '76.3*2.8T', diameter: 76.3, thickness: 2.8, length: 3000
    },
    {
      id: 540, materialCode: '감기샤프트-76.3*2.8TL3500', materialName: '감기샤프트 76.3*2.8T L:3500', unit: 'EA', stock: 70, minStock: 15, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '76.3*2.8T', diameter: 76.3, thickness: 2.8, length: 3500
    },
    {
      id: 541, materialCode: '감기샤프트-76.3*2.8TL4000', materialName: '감기샤프트 76.3*2.8T L:4000', unit: 'EA', stock: 55, minStock: 12, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '76.3*2.8T', diameter: 76.3, thickness: 2.8, length: 4000
    },
    {
      id: 542, materialCode: '감기샤프트-76.3*2.8TL4500', materialName: '감기샤프트 76.3*2.8T L:4500', unit: 'EA', stock: 45, minStock: 10, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '76.3*2.8T', diameter: 76.3, thickness: 2.8, length: 4500
    },
    // 89.1*2.8T
    {
      id: 543, materialCode: '감기샤프트-89.1*2.8TL3000', materialName: '감기샤프트 89.1*2.8T L:3000', unit: 'EA', stock: 80, minStock: 15, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '89.1*2.8T', diameter: 89.1, thickness: 2.8, length: 3000
    },
    {
      id: 544, materialCode: '감기샤프트-89.1*2.8TL3500', materialName: '감기샤프트 89.1*2.8T L:3500', unit: 'EA', stock: 65, minStock: 12, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '89.1*2.8T', diameter: 89.1, thickness: 2.8, length: 3500
    },
    {
      id: 545, materialCode: '감기샤프트-89.1*2.8TL4000', materialName: '감기샤프트 89.1*2.8T L:4000', unit: 'EA', stock: 50, minStock: 10, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '89.1*2.8T', diameter: 89.1, thickness: 2.8, length: 4000
    },
    {
      id: 546, materialCode: '감기샤프트-89.1*2.8TL4500', materialName: '감기샤프트 89.1*2.8T L:4500', unit: 'EA', stock: 40, minStock: 8, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '89.1*2.8T', diameter: 89.1, thickness: 2.8, length: 4500
    },
    // 101.6*2.8T
    {
      id: 547, materialCode: '감기샤프트-101.6*2.8TL3000', materialName: '감기샤프트 101.6*2.8T L:3000', unit: 'EA', stock: 70, minStock: 15, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '101.6*2.8T', diameter: 101.6, thickness: 2.8, length: 3000
    },
    {
      id: 548, materialCode: '감기샤프트-101.6*2.8TL3500', materialName: '감기샤프트 101.6*2.8T L:3500', unit: 'EA', stock: 55, minStock: 12, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '101.6*2.8T', diameter: 101.6, thickness: 2.8, length: 3500
    },
    {
      id: 549, materialCode: '감기샤프트-101.6*2.8TL4000', materialName: '감기샤프트 101.6*2.8T L:4000', unit: 'EA', stock: 45, minStock: 10, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '101.6*2.8T', diameter: 101.6, thickness: 2.8, length: 4000
    },
    {
      id: 550, materialCode: '감기샤프트-101.6*2.8TL4500', materialName: '감기샤프트 101.6*2.8T L:4500', unit: 'EA', stock: 38, minStock: 8, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '101.6*2.8T', diameter: 101.6, thickness: 2.8, length: 4500
    },
    // 114.3*2T
    {
      id: 551, materialCode: '감기샤프트-114.3*2TL3000', materialName: '감기샤프트 114.3*2T L:3000', unit: 'EA', stock: 60, minStock: 12, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '114.3*2T', diameter: 114.3, thickness: 2.0, length: 3000
    },
    {
      id: 552, materialCode: '감기샤프트-114.3*2TL3500', materialName: '감기샤프트 114.3*2T L:3500', unit: 'EA', stock: 50, minStock: 10, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '114.3*2T', diameter: 114.3, thickness: 2.0, length: 3500
    },
    {
      id: 553, materialCode: '감기샤프트-114.3*2TL4000', materialName: '감기샤프트 114.3*2T L:4000', unit: 'EA', stock: 42, minStock: 8, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '114.3*2T', diameter: 114.3, thickness: 2.0, length: 4000
    },
    // 139.8*2.9T
    {
      id: 554, materialCode: '감기샤프트-139.8*2.9TL3000', materialName: '감기샤프트 139.8*2.9T L:3000', unit: 'EA', stock: 50, minStock: 10, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '139.8*2.9T', diameter: 139.8, thickness: 2.9, length: 3000
    },
    {
      id: 555, materialCode: '감기샤프트-139.8*2.9TL3500', materialName: '감기샤프트 139.8*2.9T L:3500', unit: 'EA', stock: 40, minStock: 8, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '139.8*2.9T', diameter: 139.8, thickness: 2.9, length: 3500
    },
    {
      id: 556, materialCode: '감기샤프트-139.8*2.9TL4000', materialName: '감기샤프트 139.8*2.9T L:4000', unit: 'EA', stock: 35, minStock: 8, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '139.8*2.9T', diameter: 139.8, thickness: 2.9, length: 4000
    },
    // 165.2*3.3T
    {
      id: 557, materialCode: '감기샤프트-165.2*3.3TL3000', materialName: '감기샤프트 165.2*3.3T L:3000', unit: 'EA', stock: 30, minStock: 8, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '165.2*3.3T', diameter: 165.2, thickness: 3.3, length: 3000
    },
    {
      id: 558, materialCode: '감기샤프트-165.2*3.3TL3500', materialName: '감기샤프트 165.2*3.3T L:3500', unit: 'EA', stock: 25, minStock: 6, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '165.2*3.3T', diameter: 165.2, thickness: 3.3, length: 3500
    },
    {
      id: 559, materialCode: '감기샤프트-165.2*3.3TL4000', materialName: '감기샤프트 165.2*3.3T L:4000', unit: 'EA', stock: 20, minStock: 5, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '165.2*3.3T', diameter: 165.2, thickness: 3.3, length: 4000
    },
    {
      id: 560, materialCode: '감기샤프트-165.2*3.3TL4500', materialName: '감기샤프트 165.2*3.3T L:4500', unit: 'EA', stock: 18, minStock: 5, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '165.2*3.3T', diameter: 165.2, thickness: 3.3, length: 4500
    },
    // 190.7*4.0T
    {
      id: 561, materialCode: '감기샤프트-190.7*4.0TL3000', materialName: '감기샤프트 190.7*4.0T L:3000', unit: 'EA', stock: 20, minStock: 5, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '190.7*4.0T', diameter: 190.7, thickness: 4.0, length: 3000
    },
    {
      id: 562, materialCode: '감기샤프트-190.7*4.0TL3500', materialName: '감기샤프트 190.7*4.0T L:3500', unit: 'EA', stock: 18, minStock: 5, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '190.7*4.0T', diameter: 190.7, thickness: 4.0, length: 3500
    },
    {
      id: 563, materialCode: '감기샤프트-190.7*4.0TL4000', materialName: '감기샤프트 190.7*4.0T L:4000', unit: 'EA', stock: 15, minStock: 4, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '190.7*4.0T', diameter: 190.7, thickness: 4.0, length: 4000
    },
    {
      id: 564, materialCode: '감기샤프트-190.7*4.0TL4500', materialName: '감기샤프트 190.7*4.0T L:4500', unit: 'EA', stock: 12, minStock: 3, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '190.7*4.0T', diameter: 190.7, thickness: 4.0, length: 4500
    },
    // 216.3*4.2T
    {
      id: 565, materialCode: '감기샤프트-216.3*4.2TL3000', materialName: '감기샤프트 216.3*4.2T L:3000', unit: 'EA', stock: 15, minStock: 4, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '216.3*4.2T', diameter: 216.3, thickness: 4.2, length: 3000
    },
    {
      id: 566, materialCode: '감기샤프트-216.3*4.2TL3500', materialName: '감기샤프트 216.3*4.2T L:3500', unit: 'EA', stock: 12, minStock: 3, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '216.3*4.2T', diameter: 216.3, thickness: 4.2, length: 3500
    },
    {
      id: 567, materialCode: '감기샤프트-216.3*4.2TL4000', materialName: '감기샤프트 216.3*4.2T L:4000', unit: 'EA', stock: 10, minStock: 3, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '216.3*4.2T', diameter: 216.3, thickness: 4.2, length: 4000
    },
    {
      id: 568, materialCode: '감기샤프트-216.3*4.2TL4500', materialName: '감기샤프트 216.3*4.2T L:4500', unit: 'EA', stock: 8, minStock: 2, location: 'I-03', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '감기샤프트', spec: '216.3*4.2T', diameter: 216.3, thickness: 4.2, length: 4500
    },

    // ═══════════════════════════════════════════
    // 구매부품 - 앵글 (스크린샷 기반)
    // ═══════════════════════════════════════════
    {
      id: 569, materialCode: 'ANG-50-30', materialName: '앵글 50×50 L:3000', unit: 'EA', stock: 200, minStock: 50, location: 'I-04', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '앵글', spec: '50×50', length: 3000
    },
    {
      id: 570, materialCode: 'ANG-50-40', materialName: '앵글 50×50 L:4000', unit: 'EA', stock: 150, minStock: 40, location: 'I-04', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '앵글', spec: '50×50', length: 4000
    },
    {
      id: 571, materialCode: 'ANG-65-30', materialName: '앵글 65×65 L:3000', unit: 'EA', stock: 180, minStock: 45, location: 'I-04', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '앵글', spec: '65×65', length: 3000
    },
    {
      id: 572, materialCode: 'ANG-65-40', materialName: '앵글 65×65 L:4000', unit: 'EA', stock: 120, minStock: 30, location: 'I-04', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '앵글', spec: '65×65', length: 4000
    },
    {
      id: 573, materialCode: 'ANG-75-30', materialName: '앵글 75×75 L:3000', unit: 'EA', stock: 100, minStock: 25, location: 'I-04', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '앵글', spec: '75×75', length: 3000
    },
    {
      id: 574, materialCode: 'ANG-75-40', materialName: '앵글 75×75 L:4000', unit: 'EA', stock: 80, minStock: 20, location: 'I-04', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '앵글', spec: '75×75', length: 4000
    },

    // ═══════════════════════════════════════════
    // 구매부품 - 각파이프 (스크린샷 기반)
    // ═══════════════════════════════════════════
    {
      id: 575, materialCode: 'SQP-30-30', materialName: '각파이프 30×30 L:3000', unit: 'EA', stock: 250, minStock: 60, location: 'I-05', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '각파이프', spec: '30×30', length: 3000
    },
    {
      id: 576, materialCode: 'SQP-30-40', materialName: '각파이프 30×30 L:4000', unit: 'EA', stock: 180, minStock: 45, location: 'I-05', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '각파이프', spec: '30×30', length: 4000
    },
    {
      id: 577, materialCode: 'SQP-40-30', materialName: '각파이프 40×40 L:3000', unit: 'EA', stock: 200, minStock: 50, location: 'I-05', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '각파이프', spec: '40×40', length: 3000
    },
    {
      id: 578, materialCode: 'SQP-40-40', materialName: '각파이프 40×40 L:4000', unit: 'EA', stock: 150, minStock: 40, location: 'I-05', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '각파이프', spec: '40×40', length: 4000
    },
    {
      id: 579, materialCode: 'SQP-50-30', materialName: '각파이프 50×50 L:3000', unit: 'EA', stock: 150, minStock: 40, location: 'I-05', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '각파이프', spec: '50×50', length: 3000
    },
    {
      id: 580, materialCode: 'SQP-50-40', materialName: '각파이프 50×50 L:4000', unit: 'EA', stock: 120, minStock: 30, location: 'I-05', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '각파이프', spec: '50×50', length: 4000
    },
  ]);

  // 자재 투입 이력
  const [materialUsage, setMaterialUsage] = useState([]);

  // ═══════════════════════════════════════════
  // 자재 LOT 데이터 (입고 LOT별 재고 관리)
  // ═══════════════════════════════════════════
  const [materialLots, setMaterialLots] = useState([
    // ============================================================
    // 원자재 LOT (YYMMDD-## 형식)
    // ============================================================
    // EGI 철판 LOT (절곡용)
    {
      id: 1, lotNo: '240910-01', materialCode: 'EGI-1.55T', materialName: 'EGI 철판 1.55T',
      itemType: '원자재', category: '철판', unit: '매', supplier: '현대제철', poNo: 'KD-SO-240908-01',
      inboundDate: '2024-09-10', expiryDate: null, initialQty: 50, remainingQty: 12, usedQty: 38,
      location: 'D-01-01', status: 'AVAILABLE', spec: '1.55T', lotType: 'RAW'
    },
    {
      id: 2, lotNo: '240920-02', materialCode: 'EGI-1.55T', materialName: 'EGI 철판 1.55T',
      itemType: '원자재', category: '철판', unit: '매', supplier: '현대제철', poNo: 'KD-SO-240918-01',
      inboundDate: '2024-09-20', expiryDate: null, initialQty: 80, remainingQty: 45, usedQty: 35,
      location: 'D-01-02', status: 'AVAILABLE', spec: '1.55T', lotType: 'RAW'
    },
    {
      id: 3, lotNo: '240927-06', materialCode: 'EGI-1.55T', materialName: 'EGI 철판 1.55T',
      itemType: '원자재', category: '철판', unit: '매', supplier: '현대제철', poNo: 'KD-SO-240925-01',
      inboundDate: '2024-09-27', expiryDate: null, initialQty: 100, remainingQty: 100, usedQty: 0,
      location: 'D-01-03', status: 'AVAILABLE', spec: '1.55T', lotType: 'RAW'
    },
    {
      id: 4, lotNo: '241115-01', materialCode: 'EGI-1.15T', materialName: 'EGI 철판 1.15T',
      itemType: '원자재', category: '철판', unit: '매', supplier: '현대제철', poNo: 'KD-SO-241113-01',
      inboundDate: '2024-11-15', expiryDate: null, initialQty: 60, remainingQty: 35, usedQty: 25,
      location: 'D-02-01', status: 'AVAILABLE', spec: '1.15T', lotType: 'RAW'
    },
    // SUS 철판 LOT (가이드레일용)
    {
      id: 5, lotNo: '241120-01', materialCode: 'SUS-1.2T', materialName: 'SUS 철판 1.2T',
      itemType: '원자재', category: '철판', unit: '매', supplier: '스테인리스코리아', poNo: 'KD-SO-241118-01',
      inboundDate: '2024-11-20', expiryDate: null, initialQty: 30, remainingQty: 8, usedQty: 22,
      location: 'D-03-01', status: 'AVAILABLE', spec: '1.2T', lotType: 'RAW'
    },
    {
      id: 6, lotNo: '250102-01', materialCode: 'SUS-1.2T', materialName: 'SUS 철판 1.2T',
      itemType: '원자재', category: '철판', unit: '매', supplier: '스테인리스코리아', poNo: 'KD-SO-241228-01',
      inboundDate: '2025-01-02', expiryDate: null, initialQty: 50, remainingQty: 50, usedQty: 0,
      location: 'D-03-02', status: 'AVAILABLE', spec: '1.2T', lotType: 'RAW'
    },
    // 슬랫 코일 LOT
    {
      id: 7, lotNo: '241201-01', materialCode: 'SLT-MAT-001', materialName: '슬랫 코일',
      itemType: '원자재', category: '코일', unit: 'KG', supplier: '포스코', poNo: 'KD-SO-241128-01',
      inboundDate: '2024-12-01', expiryDate: null, initialQty: 500, remainingQty: 320, usedQty: 180,
      location: 'C-01-01', status: 'AVAILABLE', lotType: 'RAW'
    },
    {
      id: 8, lotNo: '250105-01', materialCode: 'SLT-MAT-001', materialName: '슬랫 코일',
      itemType: '원자재', category: '코일', unit: 'KG', supplier: '포스코', poNo: 'KD-SO-250102-01',
      inboundDate: '2025-01-05', expiryDate: null, initialQty: 800, remainingQty: 800, usedQty: 0,
      location: 'C-01-02', status: 'AVAILABLE', lotType: 'RAW'
    },

    // ============================================================
    // 원단 LOT (YYMMDD-## 형식)
    // ============================================================
    // 스크린 원단 LOT
    {
      id: 9, lotNo: '240829-01', materialCode: 'SCR-MAT-001', materialName: '스크린 원단 (백색)',
      itemType: '원자재', category: '원단', unit: '㎡', supplier: '대한섬유', poNo: 'KD-SO-240825-01',
      inboundDate: '2024-08-29', expiryDate: '2025-02-28', initialQty: 100, remainingQty: 35, usedQty: 65,
      location: 'A-01-01', status: 'AVAILABLE', lotType: 'FABRIC'
    },
    {
      id: 10, lotNo: '241015-01', materialCode: 'SCR-MAT-001', materialName: '스크린 원단 (백색)',
      itemType: '원자재', category: '원단', unit: '㎡', supplier: '대한섬유', poNo: 'KD-SO-241010-01',
      inboundDate: '2024-10-15', expiryDate: '2025-04-15', initialQty: 150, remainingQty: 80, usedQty: 70,
      location: 'A-01-02', status: 'AVAILABLE', lotType: 'FABRIC'
    },
    {
      id: 11, lotNo: '250110-01', materialCode: 'SCR-MAT-001', materialName: '스크린 원단 (백색)',
      itemType: '원자재', category: '원단', unit: '㎡', supplier: '한국섬유', poNo: 'KD-SO-250105-01',
      inboundDate: '2025-01-10', expiryDate: '2025-07-10', initialQty: 200, remainingQty: 200, usedQty: 0,
      location: 'A-01-03', status: 'AVAILABLE', lotType: 'FABRIC'
    },
    // 연기차단재 원단 LOT (화이바원단)
    {
      id: 12, lotNo: '241201-01', materialCode: 'SMK-FB-001', materialName: '연기차단재 원단 (W50)',
      itemType: '원자재', category: '원단', unit: 'M', supplier: '방재소재', poNo: 'KD-SO-241125-02',
      inboundDate: '2024-12-01', expiryDate: '2025-06-01', initialQty: 200, remainingQty: 145, usedQty: 55,
      location: 'A-05-01', status: 'AVAILABLE', spec: 'W50', lotType: 'FABRIC'
    },
    {
      id: 13, lotNo: '250110-02', materialCode: 'SMK-FB-001', materialName: '연기차단재 원단 (W50)',
      itemType: '원자재', category: '원단', unit: 'M', supplier: '방재소재', poNo: 'KD-SO-250105-02',
      inboundDate: '2025-01-10', expiryDate: '2025-07-10', initialQty: 300, remainingQty: 300, usedQty: 0,
      location: 'A-05-02', status: 'AVAILABLE', spec: 'W50', lotType: 'FABRIC'
    },

    // ============================================================
    // 생산 LOT ({품목}{종류}{Y}{M}{DD}-{규격} 형식)
    // 예: TS4B19-40 = T(하단마감재)+S(SUS마감)+4(2024)+B(11월)+19(일)-40(4000mm)
    // ============================================================
    // 하단마감재(철재) 생산 LOT
    {
      id: 14, lotNo: 'TS4B19-40', materialCode: 'T-SUS-4000', materialName: '하단마감재(철재) SUS마감 4000',
      itemType: '반제품', category: '절곡부품', unit: 'EA', supplier: '자체생산', poNo: null,
      inboundDate: '2024-11-19', expiryDate: null, initialQty: 20, remainingQty: 12, usedQty: 8,
      location: 'E-01-01', status: 'AVAILABLE', spec: '4000mm', lotType: 'PROD',
      itemCode: 'T', typeCode: 'S', specCode: '40'
    },
    {
      id: 15, lotNo: 'TT4C05-43', materialCode: 'T-IRON-4300', materialName: '하단마감재(철재) 본체철재 4300',
      itemType: '반제품', category: '절곡부품', unit: 'EA', supplier: '자체생산', poNo: null,
      inboundDate: '2024-12-05', expiryDate: null, initialQty: 15, remainingQty: 15, usedQty: 0,
      location: 'E-01-02', status: 'AVAILABLE', spec: '4300mm', lotType: 'PROD',
      itemCode: 'T', typeCode: 'T', specCode: '43'
    },
    // 케이스 생산 LOT
    {
      id: 16, lotNo: 'CL4B08-24', materialCode: 'C-LINTEL-2438', materialName: '케이스 린텔부 2438',
      itemType: '반제품', category: '절곡부품', unit: 'EA', supplier: '자체생산', poNo: null,
      inboundDate: '2024-11-08', expiryDate: null, initialQty: 25, remainingQty: 18, usedQty: 7,
      location: 'E-02-01', status: 'AVAILABLE', spec: '2438mm', lotType: 'PROD',
      itemCode: 'C', typeCode: 'L', specCode: '24'
    },
    {
      id: 17, lotNo: 'CP4A24-40', materialCode: 'C-INSP-4000', materialName: '케이스 점검구 4000',
      itemType: '반제품', category: '절곡부품', unit: 'EA', supplier: '자체생산', poNo: null,
      inboundDate: '2024-10-24', expiryDate: null, initialQty: 30, remainingQty: 22, usedQty: 8,
      location: 'E-02-02', status: 'AVAILABLE', spec: '4000mm', lotType: 'PROD',
      itemCode: 'C', typeCode: 'P', specCode: '40'
    },
    {
      id: 18, lotNo: 'CF4A15-40', materialCode: 'C-FRONT-4000', materialName: '케이스 전면부 4000',
      itemType: '반제품', category: '절곡부품', unit: 'EA', supplier: '자체생산', poNo: null,
      inboundDate: '2024-10-15', expiryDate: null, initialQty: 28, remainingQty: 20, usedQty: 8,
      location: 'E-02-03', status: 'AVAILABLE', spec: '4000mm', lotType: 'PROD',
      itemCode: 'C', typeCode: 'F', specCode: '40'
    },
    // 가이드레일 생산 LOT
    {
      id: 19, lotNo: 'RT4A15-43', materialCode: 'R-BODY-4300', materialName: '가이드레일(벽면형) 본체 4300',
      itemType: '반제품', category: '절곡부품', unit: 'EA', supplier: '자체생산', poNo: null,
      inboundDate: '2024-10-15', expiryDate: null, initialQty: 40, remainingQty: 28, usedQty: 12,
      location: 'E-03-01', status: 'AVAILABLE', spec: '4300mm', lotType: 'PROD',
      itemCode: 'R', typeCode: 'T', specCode: '43'
    },
    {
      id: 20, lotNo: 'RS4B10-40', materialCode: 'R-SUS-4000', materialName: '가이드레일(벽면형) SUS마감 4000',
      itemType: '반제품', category: '절곡부품', unit: 'EA', supplier: '자체생산', poNo: null,
      inboundDate: '2024-11-10', expiryDate: null, initialQty: 35, remainingQty: 35, usedQty: 0,
      location: 'E-03-02', status: 'AVAILABLE', spec: '4000mm', lotType: 'PROD',
      itemCode: 'R', typeCode: 'S', specCode: '40'
    },
    // 연기차단재 생산 LOT
    {
      id: 21, lotNo: 'GI4A05-53', materialCode: 'G-FIBER-5000', materialName: '연기차단재 화이바원단 W50×3000',
      itemType: '반제품', category: '연기차단재', unit: 'EA', supplier: '자체생산', poNo: null,
      inboundDate: '2024-10-05', expiryDate: null, initialQty: 50, remainingQty: 32, usedQty: 18,
      location: 'E-04-01', status: 'AVAILABLE', spec: 'W50×3000', lotType: 'PROD',
      itemCode: 'G', typeCode: 'I', specCode: '53'
    },
    {
      id: 22, lotNo: 'GW4B12-53', materialCode: 'G-SHEET-5000', materialName: '연기차단재 화이바시트 W50×3000',
      itemType: '반제품', category: '연기차단재', unit: 'EA', supplier: '자체생산', poNo: null,
      inboundDate: '2024-11-12', expiryDate: null, initialQty: 45, remainingQty: 45, usedQty: 0,
      location: 'E-04-02', status: 'AVAILABLE', spec: 'W50×3000', lotType: 'PROD',
      itemCode: 'G', typeCode: 'W', specCode: '53'
    },

    // ============================================================
    // 부자재 LOT (YYMMDD-## 형식)
    // ============================================================
    // 앤드락 LOT
    {
      id: 23, lotNo: '241210-01', materialCode: 'SCR-MAT-002', materialName: '앤드락',
      itemType: '부자재', category: '체결류', unit: 'EA', supplier: '부자재상사', poNo: 'KD-SO-241205-01',
      inboundDate: '2024-12-10', expiryDate: null, initialQty: 500, remainingQty: 380, usedQty: 120,
      location: 'A-02-01', status: 'AVAILABLE', lotType: 'RAW'
    },
    {
      id: 24, lotNo: '250108-01', materialCode: 'SCR-MAT-002', materialName: '앤드락',
      itemType: '부자재', category: '체결류', unit: 'EA', supplier: '부자재상사', poNo: 'KD-SO-250103-01',
      inboundDate: '2025-01-08', expiryDate: null, initialQty: 300, remainingQty: 300, usedQty: 0,
      location: 'A-02-02', status: 'AVAILABLE', lotType: 'RAW'
    },
    // 미싱실 LOT
    {
      id: 25, lotNo: '241201-02', materialCode: 'SCR-MAT-004', materialName: '미싱실',
      itemType: '부자재', category: '봉제류', unit: 'M', supplier: '봉제자재', poNo: 'KD-SO-241128-04',
      inboundDate: '2024-12-01', expiryDate: null, initialQty: 3000, remainingQty: 1800, usedQty: 1200,
      location: 'A-04-01', status: 'AVAILABLE', lotType: 'RAW'
    },
    // 미미자재 LOT (슬랫용)
    {
      id: 26, lotNo: '241215-01', materialCode: 'SLT-MAT-002', materialName: '미미자재',
      itemType: '부자재', category: '마감류', unit: 'EA', supplier: '마감자재', poNo: 'KD-SO-241210-02',
      inboundDate: '2024-12-15', expiryDate: null, initialQty: 400, remainingQty: 280, usedQty: 120,
      location: 'C-02-01', status: 'AVAILABLE', lotType: 'RAW'
    },
  ]);

  // 메뉴 설정 (기본값: 관리자 - 전체 메뉴)
  const [menuConfig, setMenuConfig] = useState({
    master: { enabled: true, subMenus: { process: true, item: true, 'inspection-standard': true, 'number-rule': true, 'code-rule': true } },
    sales: { enabled: true, subMenus: { customer: true, quote: true, order: true, site: true, price: true } },
    outbound: { enabled: true, subMenus: { shipment: true } },
    production: { enabled: true, subMenus: { 'production-dashboard': true, 'work-order': true, 'work-result': true, 'worker-task': true, item: true } },
    quality: { enabled: true, subMenus: { inspection: true, defect: true } },
    inventory: { enabled: true, subMenus: { stock: true, inbound: true, outbound: true } },
    accounting: { enabled: true, subMenus: { 'acc-customer': true, 'sales-account': true, purchase: true, cashbook: true, collection: true, 'cost-analysis': true } },
  });

  const navigate = (viewName, item = null) => {
    setView(viewName);
    setSelectedItem(item);
    setSelectedData(item);
  };

  const handleMenuChange = (menuId) => {
    setActiveMenu(menuId);
    // 메뉴에 따라 기본 뷰 설정
    switch (menuId) {
      case 'dashboard':
        setView('dashboard');
        break;
      case 'item-master':
        setView('item-master-list');
        break;
      case 'process-master':
        setView('process-master-list');
        break;
      case 'quality-master':
        setView('quality-master-list');
        break;
      case 'customer-master':
        setView('customer-master-list');
        break;
      case 'site-master':
        setView('site-master-list');
        break;
      case 'order-master':
        setView('order-master-list');
        break;
      case 'production-master':
        setView('production-master-list');
        break;
      case 'outbound-master':
        setView('outbound-master-list');
        break;
      case 'process':
        setView('process-list');
        break;
      case 'inspection-standard':
        setView('inspection-standard-list');
        break;
      case 'number-rule':
        setView('number-rule-list');
        break;
      case 'code-rule':
        setView('code-rule-list');
        break;
      case 'quote-formula':
        setView('quote-formula-list');
        break;
      case 'document-template':
        setView('document-template-list');
        break;
      case 'quote':
        setView('quote-list');
        break;
      case 'order':
        setView('order-list');
        break;
      case 'price':
        setView('price-list');
        break;
      case 'item':
        setView('item-list');
        break;
      case 'production-dashboard':
        setView('production-status-board');
        break;
      case 'work-order':
        setView('work-order-list');
        break;
      case 'work-result':
        setView('work-result-list');
        break;
      case 'worker-task':
        setView('worker-task-view');
        break;
      case 'traceability':
        setView('traceability-list');
        break;
      case 'shipment':
        setView('shipment-list');
        break;
      // 판매관리 - 거래처관리 (sales 메뉴 그룹)
      case 'customer':
        setView('customer-list');
        break;
      // 판매관리 - 현장관리
      case 'site':
        setView('site-list');
        break;
      case 'inspection':
        setView('inspection-list');
        break;
      case 'defect':
        setView('defect-list');
        break;
      // 품질관리 - IQC, PQC, FQC
      case 'iqc':
        setView('iqc-list');
        break;
      case 'pqc':
        setView('pqc-list');
        break;
      case 'fqc':
        setView('fqc-list');
        break;
      case 'stock':
        setView('stock-list');
        break;
      case 'inbound':
        setView('inbound-list');
        break;
      case 'stock-adjustment':
        setView('stock-adjustment-list');
        break;
      case 'delivery':
        setView('delivery-status-list');
        break;
      case 'integrated-test':
        setView('integrated-test');
        break;
      case 'common-ux':
        setView('common-ux');
        break;
      case 'process-flowchart':
        setView('process-flowchart');
        break;
      case 'detailed-process-flow':
        setView('detailed-process-flow');
        break;
      case 'policy-guide':
        setView('policy-guide');
        break;
      // 회계관리 - 2단계 메뉴 클릭 시 기본 목록 뷰 설정
      case 'acc-customer':
        setView('acc-customer-list');
        break;
      case 'sales-account':
        setView('sales-list');
        break;
      case 'purchase':
        setView('purchase-list');
        break;
      case 'cashbook':
        setView('cashbook-list');
        break;
      case 'collection':
        setView('collection-list');
        break;
      case 'cost-analysis':
        setView('cost-list');
        break;
      // 회계관리 - 거래처관리 (A0)
      case 'acc-customer-list':
        setView('acc-customer-list');
        break;
      case 'acc-customer-register':
        setView('acc-customer-register');
        break;
      case 'acc-customer-detail':
        setSelectedData(data);
        setView('acc-customer-detail');
        break;
      case 'acc-customer-edit':
        setSelectedData(data);
        setView('acc-customer-edit');
        break;
      // 회계관리 - 매출관리 (A1)
      case 'sales-list':
        setView('sales-list');
        break;
      case 'sales-statement':
        setView('sales-statement');
        break;
      case 'sales-tax-invoice':
        setView('sales-tax-invoice');
        break;
      // 회계관리 - 매입관리 (A2)
      case 'purchase-list':
        setView('purchase-list');
        break;
      case 'purchase-register':
        setView('purchase-register');
        break;
      case 'expense-list':
        setView('expense-list');
        break;
      case 'expense-register':
        setView('expense-register');
        break;
      case 'expense-estimate':
        setView('expense-estimate');
        break;
      // 회계관리 - 금전출납부 (A3)
      case 'cashbook-list':
        setView('cashbook-list');
        break;
      case 'cashbook-register':
        setView('cashbook-register');
        break;
      case 'cashbook-edit':
        setView('cashbook-edit');
        break;
      // 회계관리 - 수금관리 (A4)
      case 'collection-list':
        setView('collection-list');
        break;
      case 'collection-register':
        setView('collection-register');
        break;
      case 'receivable-list':
        setView('receivable-list');
        break;
      case 'bill-list':
        setView('bill-list');
        break;
      // 회계관리 - 원가관리 (A5)
      case 'cost-list':
        setView('cost-list');
        break;
      case 'cost-detail':
        setView('cost-detail');
        break;
      // 시스템관리
      case 'users':
        setView('users');
        break;
      case 'roles':
        setView('roles');
        break;
      case 'settings':
        setView('settings');
        break;
      default:
        setView(`${menuId}-list`);
    }
  };

  // 견적 등록
  const handleSaveQuote = (newQuote) => {
    const quote = {
      ...newQuote,
      id: quotes.length + 1,
    };
    setQuotes(prev => [...prev, quote]);
    navigate('quote-list');
  };

  // 수주 등록
  const handleSaveOrder = (newOrder) => {
    const order = {
      ...newOrder,
      id: orders.length + 1,
    };
    setOrders(prev => [...prev, order]);
  };

  // 수주 업데이트
  const handleUpdateOrder = (updatedOrder) => {
    setOrders(prev => prev.map(o =>
      o.id === updatedOrder.id ? updatedOrder : o
    ));
    setSelectedItem(updatedOrder);
  };

  // 수주 취소
  const handleCancelOrder = (orderId, cancelInfo) => {
    setOrders(prev => prev.map(o => {
      if (o.id === orderId) {
        const newHistory = {
          id: Date.now(),
          changedAt: cancelInfo.cancelledAt,
          changeType: '취소',
          description: `수주 취소 - 사유: ${cancelInfo.reason}${cancelInfo.reasonDetail ? ` (${cancelInfo.reasonDetail})` : ''}`,
          changedBy: cancelInfo.cancelledBy,
        };
        return {
          ...o,
          status: '취소',
          cancelReason: cancelInfo.reason,
          cancelReasonDetail: cancelInfo.reasonDetail,
          cancelledAt: cancelInfo.cancelledAt,
          cancelledBy: cancelInfo.cancelledBy,
          changeHistory: [...(o.changeHistory || []), newHistory],
        };
      }
      return o;
    }));
    alert('수주가 취소되었습니다.');
  };

  // 작업지시 등록 - ★ 생산LOT 자동생성
  const handleSaveWorkOrder = (newWorkOrder) => {
    // ★ 생산LOT 자동 생성 (KD-PL-YYMMDD-## 형식)
    const productionLot = newWorkOrder.productionLot || autoGenerateProductionLot(new Date());

    const workOrder = {
      ...newWorkOrder,
      id: workOrders.length + 1,
      productionLot, // ★ 생산LOT 자동 부여
      lotNo: productionLot, // ★ 목록에서 표시하는 필드명과 일치
      productionLotNo: productionLot, // ★ 호환성 유지
      workPriority: newWorkOrder.workPriority || 5, // ★ 이미 숫자로 전달됨
      materialInputs: [], // ★ 자재 투입 이력 초기화 (LOT 추적용)
      createdAt: new Date().toISOString(),
    };
    setWorkOrders(prev => [...prev, workOrder]);

    // 해당 수주의 분할 상태 업데이트
    if (newWorkOrder.splitNo) {
      setOrders(prev => prev.map(o => {
        if (o.orderNo === newWorkOrder.orderNo) {
          return {
            ...o,
            splits: o.splits?.map(s =>
              s.splitNo === newWorkOrder.splitNo
                ? { ...s, productionStatus: '작업대기', productionOrderNo: newWorkOrder.workOrderNo, productionLot }
                : s
            ),
          };
        }
        return o;
      }));
    }

    console.log(`[작업지시 생성] ${workOrder.workOrderNo} - 생산LOT: ${productionLot}`);
  };

  // 작업지시 승인 처리
  const handleApproveWorkOrder = (workOrderId) => {
    const today = new Date().toISOString().split('T')[0];
    setWorkOrders(prev => prev.map(wo => {
      if (wo.id === workOrderId) {
        return {
          ...wo,
          approvalStatus: '승인완료',
          status: '작업대기', // 승인되면 작업대기로 변경
          approval: {
            ...wo.approval,
            approver: { name: '박생산', date: today, dept: '생산관리' },
          },
        };
      }
      return wo;
    }));
    alert('✅ 작업지시가 승인되었습니다.\n\n회계팀에 참조 알림이 발송됩니다.');
  };

  // 작업자: 작업 시작
  const handleStartWork = (workOrderId) => {
    const now = new Date();
    setWorkOrders(prev => prev.map(wo => {
      if (wo.id === workOrderId) {
        return {
          ...wo,
          status: '작업중',
          startTime: now.toISOString(),
          worker: currentUser.name,
        };
      }
      return wo;
    }));
    alert('✅ 작업을 시작합니다.');
  };

  // 작업자: 작업일지(실적) 입력
  const handleInputWorkLog = (workOrderId, workLog) => {
    setWorkOrders(prev => prev.map(wo => {
      if (wo.id === workOrderId) {
        return {
          ...wo,
          completedQty: workLog.completedQty,
          defectQty: workLog.defectQty,
          workNote: workLog.note,
          lastUpdated: new Date().toISOString(),
        };
      }
      return wo;
    }));
    alert('✅ 작업 실적이 저장되었습니다.');
  };

  // 작업자: 작업 완료 (workOrderId 또는 task 객체 모두 지원) - ★ 제품검사LOT 자동생성
  const handleCompleteWork = (taskOrId) => {
    const now = new Date();
    const isObject = typeof taskOrId === 'object';
    const workOrderId = isObject ? taskOrId.id : taskOrId;
    const taskData = isObject ? taskOrId : null;

    // ★ 제품검사LOT 자동 생성 (KD-SA-YYMMDD-## 형식)
    const productInspLot = autoGenerateProductInspLot(now);

    // 현재 작업지시 정보 가져오기
    const currentWO = workOrders.find(wo => wo.id === workOrderId);

    // 작업지시 상태 업데이트
    setWorkOrders(prev => prev.map(wo => {
      if (wo.id === workOrderId) {
        return {
          ...wo,
          status: '작업완료',
          endTime: now.toISOString(),
          completedDate: now.toISOString().split('T')[0],
          completedQty: taskData?.goodQty || wo.completedQty || wo.totalQty,
          productInspLot, // ★ 제품검사LOT 자동 부여
        };
      }
      return wo;
    }));

    // 작업실적 데이터 자동 생성 (task 객체로 전달된 경우)
    if (isObject && taskData) {
      const resultNo = `WR-${now.toISOString().slice(2, 10).replace(/-/g, '')}-${String(workResults.length + 1).padStart(3, '0')}`;
      const newResult = {
        id: Date.now(),
        resultNo,
        workOrderNo: taskData.workOrderNo,
        workDate: now.toISOString().split('T')[0],
        processType: taskData.processType,
        productName: taskData.items?.[0]?.productName || taskData.productName || '방충망',
        goodQty: taskData.goodQty || taskData.totalQty || 0,
        defectQty: taskData.defectQty || 0,
        status: '작업완료',
        worker: taskData.assignee || '작업자',
        completedAt: now.toISOString(),
        note: taskData.note || '',
        customerName: taskData.customerName,
        siteName: taskData.siteName,
        productInspLot, // ★ 제품검사LOT 연결
      };
      setWorkResults(prev => [...prev, newResult]);
    }

    // ★ 제품검사(FQC) 자동 생성
    const newProductInspection = {
      id: productInspections.length + 1,
      lotNo: productInspLot,
      workOrderNo: currentWO?.workOrderNo || taskData?.workOrderNo,
      productName: currentWO?.productName || taskData?.productName || '제품',
      qty: taskData?.goodQty || currentWO?.totalQty || 0,
      status: '검사대기',
      requestDate: now.toISOString().split('T')[0],
      requester: currentUser.name,
      orderNo: currentWO?.orderNo,
      customerName: currentWO?.customerName || taskData?.customerName,
    };
    setProductInspections(prev => [...prev, newProductInspection]);

    console.log(`[작업완료] 제품검사LOT: ${productInspLot} 자동 생성`);
    alert(`✅ 작업이 완료되었습니다.\n\n📋 제품검사LOT: ${productInspLot}\n\n✅ 제품검사(FQC)가 자동 생성되었습니다.\n[품질관리 > 제품검사]에서 검사를 진행하세요.`);
  };

  // 회계팀: C등급 출하 승인
  const handleApproveShipment = (orderId) => {
    const today = new Date().toISOString().split('T')[0];
    setOrders(prev => prev.map(o => {
      if (o.id === orderId) {
        return {
          ...o,
          accountingStatus: '회계확인완료',
          accountingApprovalDate: today,
          accountingApprover: currentUser.name,
        };
      }
      return o;
    }));
    alert('✅ C등급 출하가 승인되었습니다.\n\n출하 진행이 가능합니다.');
  };

  // 회계팀: C등급 출하 반려
  const handleRejectShipment = (orderId, reason) => {
    const today = new Date().toISOString().split('T')[0];
    setOrders(prev => prev.map(o => {
      if (o.id === orderId) {
        return {
          ...o,
          accountingStatus: '출하반려',
          accountingRejectDate: today,
          accountingRejectReason: reason,
          accountingApprover: currentUser.name,
        };
      }
      return o;
    }));
    alert(`❌ 출하가 반려되었습니다.\n\n사유: ${reason}`);
  };

  // 구매팀: 발주요청 생성
  const handleCreatePO = (material) => {
    const poNo = `PO-${new Date().toISOString().slice(2, 10).replace(/-/g, '')}-${String(purchaseOrders.length + 1).padStart(3, '0')}`;
    const newPO = {
      id: purchaseOrders.length + 1,
      poNo,
      materialCode: material.materialCode,
      materialName: material.materialName,
      requestQty: material.minStock * 2, // 안전재고의 2배 발주
      unit: material.unit,
      vendor: '미정',
      status: '발주대기',
      requestDate: new Date().toISOString().split('T')[0],
      requester: currentUser.name,
    };
    setPurchaseOrders(prev => [...prev, newPO]);
    alert(`✅ 발주요청이 생성되었습니다.\n\n발주번호: ${poNo}\n품목: ${material.materialName}\n수량: ${material.minStock * 2}${material.unit}`);
  };

  // 작업지시 업데이트
  const handleUpdateWorkOrder = (updatedWorkOrder) => {
    setWorkOrders(prev => prev.map(wo =>
      wo.id === updatedWorkOrder.id ? updatedWorkOrder : wo
    ));
    setSelectedItem(updatedWorkOrder);
  };

  const handleSaveWorkResult = (newResult) => {
    const result = {
      ...newResult,
      id: workResults.length + 1,
      createdAt: new Date().toISOString(),
    };
    setWorkResults(prev => [...prev, result]);

    // 작업지시 완료수량 업데이트
    setWorkOrders(prev => prev.map(wo => {
      if (wo.workOrderNo === newResult.workOrderNo) {
        const newCompletedQty = wo.completedQty + newResult.goodQty;
        return {
          ...wo,
          completedQty: newCompletedQty,
          status: newCompletedQty >= wo.totalQty ? '작업완료' : wo.status,
        };
      }
      return wo;
    }));
  };

  // 출하 등록
  const handleSaveShipment = (newShipment) => {
    const shipment = {
      ...newShipment,
      id: shipments.length + 1,
    };
    setShipments(prev => [...prev, shipment]);
  };

  // 출하 업데이트 (상태 변경, 상차 체크 등) - ★ 자동화 연동
  const handleUpdateShipment = (shipmentOrNo, updates = null) => {
    // 두 가지 호출 방식 지원:
    // 1. handleUpdateShipment(updatedShipment) - 전체 객체로 업데이트
    // 2. handleUpdateShipment(shipmentNo, { paymentConfirmed: true }) - 부분 업데이트

    if (updates !== null && typeof shipmentOrNo === 'string') {
      // 부분 업데이트 방식 (수금관리, 세금계산서 발행에서 사용)
      setShipments(prev => prev.map(s =>
        s.shipmentNo === shipmentOrNo ? { ...s, ...updates } : s
      ));
      // 현재 선택된 아이템도 업데이트
      if (selectedItem?.shipmentNo === shipmentOrNo) {
        setSelectedItem(prev => ({ ...prev, ...updates }));
      }
    } else {
      // 전체 객체 업데이트 방식 (기존 방식)
      const updatedShipment = shipmentOrNo;
      const prevShipment = shipments.find(s => s.id === updatedShipment.id);

      // ★ 배송완료로 상태 변경 시 세금계산서/거래명세서 자동 발행
      if (prevShipment?.status !== '배송완료' && updatedShipment.status === '배송완료') {
        const relatedOrder = orders.find(o => o.orderNo === updatedShipment.orderNo);
        if (relatedOrder) {
          // A등급: 세금계산서 자동 발행
          if (relatedOrder.creditGrade === 'A' || !relatedOrder.creditGrade) {
            const invoice = autoGenerateTaxInvoice(updatedShipment, relatedOrder);
            const statement = autoGenerateTransactionStatement(updatedShipment, relatedOrder);
            updatedShipment.taxInvoiceNo = invoice.invoiceNo;
            updatedShipment.taxInvoiceIssued = true;
            updatedShipment.transactionStatementNo = statement.statementNo;
            console.log(`[자동발행] 세금계산서: ${invoice.invoiceNo}, 거래명세서: ${statement.statementNo}`);
          }
          // B/C등급: 거래명세서만 자동 발행
          else {
            const statement = autoGenerateTransactionStatement(updatedShipment, relatedOrder);
            updatedShipment.transactionStatementNo = statement.statementNo;
            console.log(`[자동발행] 거래명세서: ${statement.statementNo} (세금계산서는 입금 후 발행)`);
          }
        }
      }

      setShipments(prev => prev.map(s =>
        s.id === updatedShipment.id ? updatedShipment : s
      ));
      setSelectedItem(updatedShipment);
    }
  };

  // ★ 출하 생성 시 C등급 자동 보류 체크
  const handleCreateShipmentWithCheck = (shipmentData) => {
    const relatedOrder = orders.find(o => o.orderNo === shipmentData.orderNo);

    // C등급 고객은 입금 확인 전까지 자동 보류
    if (relatedOrder?.creditGrade === 'C') {
      const customerReceivables = receivables.filter(r =>
        r.customerId === relatedOrder.customerId && r.balance > 0
      );
      const totalBalance = customerReceivables.reduce((sum, r) => sum + r.balance, 0);

      if (totalBalance > 0) {
        shipmentData.status = '출하보류';
        shipmentData.holdReason = `C등급 고객 - 미수금 ${totalBalance.toLocaleString()}원 존재`;
        shipmentData.holdAt = new Date().toISOString();
        console.log(`[출하보류] ${shipmentData.shipmentNo}: C등급 고객 미수금 ${totalBalance.toLocaleString()}원`);
      }
    }

    // B등급 고객도 미수금 과다 시 보류
    if (relatedOrder?.creditGrade === 'B') {
      const customerReceivables = receivables.filter(r =>
        r.customerId === relatedOrder.customerId && r.balance > 0
      );
      const totalBalance = customerReceivables.reduce((sum, r) => sum + r.balance, 0);
      const creditLimit = relatedOrder.creditLimit || 10000000; // 기본 1천만원

      if (totalBalance > creditLimit) {
        shipmentData.status = '출하보류';
        shipmentData.holdReason = `신용한도 초과 - 미수금 ${totalBalance.toLocaleString()}원 / 한도 ${creditLimit.toLocaleString()}원`;
        shipmentData.holdAt = new Date().toISOString();
        console.log(`[출하보류] ${shipmentData.shipmentNo}: 신용한도 초과`);
      }
    }

    handleSaveShipment(shipmentData);
  };

  // 입고 처리 (구매발주 입고) - ★ 입고LOT 자동생성
  const handleReceivePO = (poId, receiveData) => {
    const today = new Date().toISOString().split('T')[0];
    // ★ LOT 자동생성 함수 사용 (YYMMDD-## 형식)
    const lotNo = autoGenerateIncomingLot(new Date());
    // ★ 입고검사LOT도 자동 생성 (IQC 연동)
    const inspectionLotNo = autoGenerateIncomingInspLot(new Date());

    // 발주 상태 업데이트
    const po = purchaseOrders.find(p => p.id === poId);
    setPurchaseOrders(prev => prev.map(p => {
      if (p.id === poId) {
        return {
          ...p,
          status: receiveData.qty >= p.requestQty ? '검사대기' : '부분입고', // ★ 입고완료 → 검사대기로 변경
          receivedQty: (p.receivedQty || 0) + receiveData.qty,
          receivedDate: today,
          lotNo,
          inspectionLotNo, // ★ 검사LOT 자동 연결
        };
      }
      return p;
    }));

    // 재고 추가
    if (po) {
      setInventory(prev => prev.map(item =>
        item.materialCode === po.materialCode
          ? { ...item, stock: item.stock + receiveData.qty, lastUpdated: today }
          : item
      ));

      // ★★★ 입고 LOT를 materialLots에 추가 (작업지시 자재투입 시 FIFO 선택 가능하도록)
      const newMaterialLot = {
        id: Date.now(),
        lotNo: lotNo,
        materialCode: po.materialCode,
        materialName: po.materialName,
        itemType: po.itemType || '원자재',
        category: po.category || '원자재',
        unit: po.unit || 'EA',
        supplier: po.supplierName || po.vendor || '',
        poNo: po.poNo,
        inboundDate: today,
        expiryDate: null, // 유통기한이 있는 품목의 경우 별도 설정
        initialQty: receiveData.qty,
        remainingQty: receiveData.qty,
        usedQty: 0,
        location: receiveData.location || 'A-01-01',
        status: 'AVAILABLE',
        spec: po.spec || '',
        lotType: 'RAW', // 입고 LOT는 원자재 타입
      };
      setMaterialLots(prev => [...prev, newMaterialLot]);

      // ★ 입고검사(IQC) 자동 생성
      const newInspection = {
        id: allInspections.length + 1,
        type: 'incoming',
        lotNo: inspectionLotNo,
        targetNo: po.poNo,
        itemName: po.materialName,
        qty: receiveData.qty,
        status: '검사대기',
        requestDate: today,
        requester: currentUser.name,
        vendorName: po.supplierName,
      };
      setAllInspections(prev => [...prev, newInspection]);
    }

    alert(`✅ 입고가 완료되었습니다.\n\n📦 입고LOT: ${lotNo}\n🔍 검사LOT: ${inspectionLotNo}\n입고수량: ${receiveData.qty}\n\n✅ 수입검사(IQC)가 자동 생성되었습니다.\n✅ 자재투입용 LOT가 자동 등록되었습니다.\n[품질관리 > 수입검사]에서 검사를 진행하세요.`);
  };

  // 수입검사 저장 - ★ LOT 자동생성 및 NCR 연동
  const handleSaveIncomingInspection = (inspection) => {
    const today = new Date().toISOString().split('T')[0];
    // ★ 검사LOT가 없으면 자동 생성
    const inspLotNo = inspection.lotNo || autoGenerateIncomingInspLot(new Date());

    const newInspection = {
      ...inspection,
      id: allInspections.length + 1,
      type: 'incoming',
      inspectionType: '수입검사',
      lotNo: inspLotNo,
      inspectionDate: today,
      inspector: currentUser.name,
      passQty: inspection.result === '합격' ? inspection.qty : (inspection.passQty || 0),
      failQty: inspection.result === '불합격' ? inspection.qty : (inspection.failQty || 0),
    };
    setAllInspections(prev => [...prev, newInspection]);

    // 발주 상태 업데이트
    if (inspection.targetNo) {
      setPurchaseOrders(prev => prev.map(po => {
        if (po.poNo === inspection.targetNo) {
          return {
            ...po,
            status: inspection.result === '합격' ? '입고완료' : '불합격',
            inspectionResult: inspection.result,
            inspectionDate: today,
          };
        }
        return po;
      }));
    }

    // ★ 불합격 시 NCR(부적합보고서) 자동 등록
    if (inspection.result === '불합격') {
      const ncrNo = `NCR-${formatDateCode(new Date())}-${String(defects.length + 1).padStart(3, '0')}`;
      const newDefect = {
        id: defects.length + 1,
        ncrNo,
        registDate: today,
        source: 'IQC',
        sourceType: '수입검사',
        sourceNo: inspection.targetNo || inspLotNo,
        itemName: inspection.materialName || inspection.itemName,
        defectQty: inspection.failQty || inspection.defectQty || inspection.qty,
        totalQty: inspection.qty,
        defectType: inspection.defectType || '품질불량',
        description: inspection.defectDescription || `수입검사 불합격 - ${inspection.defectType || '품질불량'}`,
        vendorName: inspection.vendorName,
        status: '처리대기',
        registeredBy: currentUser.name,
        approvalLine: {
          type: 'APR-3LINE',
          roles: [
            { id: 'writer', label: '작성', name: currentUser.name, date: today, status: 'approved' },
            { id: 'reviewer', label: '검토', name: '', date: '', status: 'pending' },
            { id: 'approver', label: '승인', name: '', date: '', status: 'pending' },
          ]
        }
      };
      setDefects(prev => [...prev, newDefect]);

      alert(`✅ 수입검사가 등록되었습니다.\n\n검사LOT: ${inspLotNo}\n결과: ${inspection.result}\n\n⚠️ NCR(부적합보고서)가 자동 생성되었습니다.\nNCR번호: ${ncrNo}\n\n[품질관리 > 부적합관리]에서 처리하세요.`);
    } else {
      alert(`✅ 수입검사가 등록되었습니다.\n\n검사LOT: ${inspLotNo}\n결과: ${inspection.result}\n합격수량: ${newInspection.passQty}`);
    }
  };

  // 중간검사 저장 - ★ LOT 자동생성 및 NCR 연동
  const handleSaveProcessInspection = (inspection) => {
    const today = new Date().toISOString().split('T')[0];
    // ★ 중간검사LOT 자동 생성 (공정단계 포함)
    const processStep = inspection.processStep || 1;
    const inspLotNo = inspection.lotNo || autoGenerateProcessInspLot(new Date(), processStep);

    const newInspection = {
      ...inspection,
      id: allInspections.length + 1,
      type: 'process',
      inspectionType: '중간검사',
      lotNo: inspLotNo,
      inspectionDate: today,
      inspector: currentUser.name,
      passQty: inspection.result === '합격' ? inspection.qty : (inspection.passQty || 0),
      failQty: inspection.result === '불합격' ? inspection.qty : (inspection.failQty || 0),
    };
    setAllInspections(prev => [...prev, newInspection]);

    // 작업지시 상태 업데이트
    if (inspection.workOrderNo) {
      setWorkOrders(prev => prev.map(wo => {
        if (wo.workOrderNo === inspection.workOrderNo) {
          return {
            ...wo,
            inspectionStatus: inspection.result,
            lastInspectionDate: today,
          };
        }
        return wo;
      }));
    }

    // ★ 불합격 시 NCR(부적합보고서) 자동 등록
    if (inspection.result === '불합격') {
      const ncrNo = `NCR-${formatDateCode(new Date())}-${String(defects.length + 1).padStart(3, '0')}`;
      const newDefect = {
        id: defects.length + 1,
        ncrNo,
        registDate: today,
        source: 'PQC',
        sourceType: '중간검사',
        sourceNo: inspection.workOrderNo,
        itemName: inspection.productName || inspection.itemName,
        defectQty: inspection.failQty || inspection.defectQty,
        totalQty: inspection.qty,
        defectType: inspection.defectType || '공정불량',
        description: inspection.defectDescription || `중간검사 불합격 - ${inspection.defectType || '공정불량'}`,
        vendorName: null,
        status: '처리대기',
        processType: '재작업',
        registeredBy: currentUser.name,
        approvalLine: {
          type: 'APR-3LINE',
          roles: [
            { id: 'writer', label: '작성', name: currentUser.name, date: today, status: 'approved' },
            { id: 'reviewer', label: '검토', name: '', date: '', status: 'pending' },
            { id: 'approver', label: '승인', name: '', date: '', status: 'pending' },
          ]
        }
      };
      setDefects(prev => [...prev, newDefect]);

      alert(`✅ 중간검사가 등록되었습니다.\n\n검사LOT: ${inspLotNo}\n결과: ${inspection.result}\n\n⚠️ NCR(부적합보고서)가 자동 생성되었습니다.\nNCR번호: ${ncrNo}\n\n[품질관리 > 부적합관리]에서 처리하세요.`);
    } else {
      alert(`✅ 중간검사가 등록되었습니다.\n\n검사LOT: ${inspLotNo}\n결과: ${inspection.result}\n\n다음 공정으로 진행 가능합니다.`);
    }
  };

  // 부적합품 처리
  const handleProcessDefect = (defectId, processData) => {
    const today = new Date().toISOString().split('T')[0];

    setDefects(prev => prev.map(d => {
      if (d.id === defectId) {
        return {
          ...d,
          status: '처리완료',
          processType: processData.processType, // 재작업, 폐기, 특채
          processDate: today,
          processBy: currentUser.name,
          processNote: processData.note,
        };
      }
      return d;
    }));

    alert(`✅ 부적합품이 처리되었습니다.\n\n처리유형: ${processData.processType}`);
  };

  // 배송상태 업데이트
  const handleUpdateDeliveryStatus = (shipmentId, statusData) => {
    setShipments(prev => prev.map(s => {
      if (s.id === shipmentId) {
        return {
          ...s,
          deliveryStatus: statusData.status,
          deliveryProgress: statusData.progress,
          currentLocation: statusData.location,
          lastUpdateTime: new Date().toISOString(),
        };
      }
      return s;
    }));
  };

  const renderContent = () => {
    switch (view) {
      // 공통 UX 가이드
      case 'common-ux':
        return <CommonUXGuide />;
      // 통합 테스트 대시보드
      case 'integrated-test':
        return <IntegratedTestDashboard />;
      case 'policy-guide':
        return <PolicyGuide onNavigate={navigate} />;
      case 'process-flowchart':
        // 플로우차트 screenId → 실제 view 매핑
        const screenToViewMap = {
          'customer': 'customer-master-list',
          'quote': 'quote-list',
          'order': 'order-list',
          'site': 'site-master-list',
          'price': 'price-list',
          'shipment': 'shipment-list',
          'item': 'item-list',
          'work-order': 'work-order-list',
          'work-result': 'work-result-list',
          'worker-task': 'worker-task-view',
          'iqc': 'inspection-list',
          'pqc': 'inspection-list',
          'fqc': 'inspection-list',
          'defect': 'defect-list',
          'stock': 'stock-list',
          'inbound': 'inbound-list',
          'stock-adjustment': 'stock-adjustment-list',
          'sales-list': 'sales-list',
          'sales-statement': 'sales-statement',
          'sales-tax-invoice': 'sales-tax-invoice',
          'collection-list': 'collection-list',
          'purchase-list': 'purchase-list',
          'expense-list': 'expense-list',
          'cashbook-list': 'cashbook-list',
          'cost-list': 'cost-list',
        };
        return (
          <div className="space-y-4">
            <div className="flex justify-end gap-2 mb-4">
              <button
                onClick={() => setView('detailed-process-flow')}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2 text-sm font-medium"
              >
                <Activity className="w-4 h-4" />
                견적~출하 상세 플로우
              </button>
              <button
                onClick={() => setShowDetailedFlowDiagram(true)}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2 text-sm font-medium"
              >
                <GitBranch className="w-4 h-4" />
                상세 다이어그램 보기
              </button>
            </div>
            <BusinessFlowChart onNavigate={(screen) => {
              const mappedView = screenToViewMap[screen] || screen;
              setView(mappedView);
            }} />
          </div>
        );
      case 'production-process-flowchart':
        return <ProcessFlowChart />;
      case 'detailed-process-flow':
        return <DetailedProcessFlowChart onNavigate={navigate} />;
      // 대시보드
      case 'dashboard':
      case 'ceo-dashboard':
        return <CEODashboard userRole={currentUser.role} onNavigate={navigate} />;
      case 'sales-dashboard':
        return <SalesDashboard
          onNavigate={navigate}
          quotes={quotes}
          orders={orders}
          shipments={shipments}
        />;
      case 'production-dashboard':
        return <ProductionDashboard
          onNavigate={navigate}
          workOrders={workOrders}
          onApprove={handleApproveWorkOrder}
        />;
      case 'quality-dashboard':
        return <QualityDashboard
          onNavigate={navigate}
          workOrders={workOrders}
        />;
      case 'accounting-dashboard':
        return <AccountingDashboard
          onNavigate={navigate}
          orders={orders}
          shipments={shipments}
          onApproveShipment={handleApproveShipment}
          onRejectShipment={handleRejectShipment}
        />;
      case 'purchase-dashboard':
        return <PurchaseDashboard
          onNavigate={navigate}
          materials={inventory}
          purchaseOrders={purchaseOrders}
          onCreatePO={handleCreatePO}
        />;
      case 'worker-dashboard':
        return <WorkerDashboard
          onNavigate={navigate}
          workOrders={workOrders}
          currentUser={currentUser}
          onStartWork={handleStartWork}
          onInputWorkLog={handleInputWorkLog}
          onCompleteWork={handleCompleteWork}
        />;
      // 품목관리 (생산관리 메뉴) - 공유 상태 연동
      case 'item-list':
        return <ItemList
          onNavigate={navigate}
          items={sharedItems}
          onAddItem={handleAddItem}
          onUpdateItem={handleUpdateItem}
          onDeleteItem={handleDeleteItem}
        />;
      case 'item-create':
        return <ItemForm onNavigate={navigate} onAddItem={handleAddItem} />;
      case 'item-edit':
        return <ItemForm item={selectedItem} onNavigate={navigate} isEdit={true} onUpdateItem={handleUpdateItem} />;
      case 'item-detail':
        return <ItemDetail item={selectedItem} onNavigate={navigate} />;
      // 품목기준관리
      case 'item-master-list':
        return <ItemMasterManagement onNavigate={navigate} />;
      // 자재기준관리
      case 'material-master':
      case 'material-master-list':
        return <MaterialMasterManagement onNavigate={navigate} />;
      // 공정기준관리
      case 'process-master-list':
        return <MasterConfigurationManager configId="process" onNavigate={navigate} />;
      // 품질기준관리 (마스터)
      case 'quality-master-list':
        return <MasterConfigurationManager configId="quality" onNavigate={navigate} />;
      // 거래처기준관리
      case 'customer-master-list':
        return <MasterConfigurationManager configId="customer" onNavigate={navigate} />;
      // 현장기준관리
      case 'site-master-list':
        return <MasterConfigurationManager configId="site" onNavigate={navigate} />;
      // 수주기준관리
      case 'order-master-list':
        return <MasterConfigurationManager configId="order" onNavigate={navigate} />;
      // 생산기준관리
      case 'production-master-list':
        return <ProductionMasterManagement onNavigate={navigate} />;
      // 출고기준관리
      case 'outbound-master-list':
        return <OutboundMasterManagement onNavigate={navigate} />;
      // 공정관리
      case 'process-list':
        return <ProcessList processes={sampleProcesses} onNavigate={navigate} />;
      case 'process-detail':
        return <ProcessDetail
          process={selectedItem}
          workOrders={workOrders}
          onNavigate={navigate}
          onBack={() => navigate('process-list')}
        />;
      case 'process-create':
        return <ProcessForm
          process={null}
          onSave={(formData) => {
            const newCode = `P-${String(sampleProcesses.length + 1).padStart(3, '0')}`;
            const newProcess = {
              id: sampleProcesses.length + 1,
              processCode: newCode,
              ...formData,
              createdAt: new Date().toISOString().split('T')[0],
              updatedAt: new Date().toISOString().split('T')[0],
            };
            sampleProcesses.push(newProcess);
            navigate('process-list');
          }}
          onBack={() => navigate('process-list')}
        />;
      case 'process-edit':
        return <ProcessForm
          process={selectedItem}
          onSave={(formData) => {
            const idx = sampleProcesses.findIndex(p => p.id === selectedItem.id);
            if (idx !== -1) {
              sampleProcesses[idx] = { ...sampleProcesses[idx], ...formData, updatedAt: new Date().toISOString().split('T')[0] };
            }
            navigate('process-list');
          }}
          onBack={() => navigate('process-list')}
        />;
      // 품질기준관리
      case 'quality-standard-list':
        return <InspectionStandardList standards={initialInspectionStandards} onNavigate={navigate} />;
      // 채번관리
      case 'number-rule-list':
        return <NumberRuleManagement onNavigate={navigate} />;
      // 공통코드관리
      case 'code-rule-list':
        return <CodeRuleManagement onNavigate={navigate} />;
      // 견적수식관리
      case 'quote-formula-list':
        return <QuoteFormulaManagement onNavigate={navigate} />;
      // 문서양식관리
      case 'document-template-list':
        return <DocumentTemplateManager onNavigate={navigate} />;
      // 견적관리
      case 'quote-list':
        return <QuoteList
          quotes={quotes}
          onNavigate={navigate}
          onCreateOrder={(newOrder) => {
            // 수주 리스트에 새 수주 추가
            setOrders(prev => [newOrder, ...prev]);
          }}
          onUpdateQuote={(updatedQuote) => {
            // 견적 상태 업데이트
            setQuotes(prev => prev.map(q =>
              q.id === updatedQuote.id ? updatedQuote : q
            ));
          }}
        />;
      case 'quote-create':
        return <QuoteCreate onNavigate={navigate} onBack={() => navigate('quote-list')} onSave={handleSaveQuote} />;
      case 'quote-detail':
        return <QuoteDetailNew
          quote={selectedItem}
          orders={orders}
          onNavigate={navigate}
          onBack={() => navigate('quote-list')}
          onConvertToOrder={(quote, deliveryInfo) => {
            // 수주번호 생성 - 채번관리 규칙 적용
            const productType = quote.productType || quote.productName || '';
            const newOrderNo = generateNumber('수주번호', productType, []);

            // 새 수주 데이터 생성
            const newOrder = {
              id: Date.now(),
              orderNo: newOrderNo,
              quoteNo: quote.quoteNo,
              orderDate: new Date().toISOString().split('T')[0],
              customerName: quote.customerName,
              siteName: quote.siteName,
              siteAddress: quote.siteAddress || deliveryInfo?.deliveryAddress,
              manager: quote.manager,
              contact: quote.contact,
              productName: quote.productName,
              qty: quote.qty,
              totalAmount: quote.finalAmount || quote.totalAmount,
              status: '수주등록',
              dueDate: deliveryInfo?.dueDate || quote.dueDate,
              deliveryMethod: deliveryInfo?.deliveryMethod || '상차',
              freightCost: deliveryInfo?.freightCost || '선불',
              receiverName: deliveryInfo?.receiverName || '',
              receiverPhone: deliveryInfo?.receiverPhone || '',
              deliveryAddress: deliveryInfo?.deliveryAddress || '',
              note: deliveryInfo?.note || '',
              creditGrade: quote.creditGrade,
              items: quote.items || [],
              calculatedItems: quote.calculatedItems || [],
              bomData: quote.bomData || {},
              splits: [],
              history: [{
                id: Date.now(),
                changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
                changeType: '수주등록',
                description: `견적(${quote.quoteNo})에서 수주전환`,
                changedBy: '현재 사용자',
              }],
            };

            // 수주 추가
            setOrders(prev => [newOrder, ...prev]);
            // 견적 상태 업데이트
            setQuotes(prev => prev.map(q => q.id === quote.id ? { ...q, status: '수주전환', convertedOrderNo: newOrderNo } : q));
          }}
          onUpdateQuote={(updatedQuote) => {
            setQuotes(prev => prev.map(q => q.id === updatedQuote.id ? updatedQuote : q));
            setSelectedItem(updatedQuote);
          }}
          onCreateOrder={(newOrder) => {
            setOrders(prev => [newOrder, ...prev]);
          }}
        />;
      // 수주관리
      case 'order-list':
        return <OrderList
          orders={orders}
          shipments={shipments}
          workOrders={workOrders}
          onNavigate={navigate}
          onCreateWorkOrders={(order) => {
            // 수주에서 바로 공정별 작업지시 자동 생성 (구매품/서비스 제외)
            const now = new Date();
            const bomItems = order.items || [];
            const processGroups = {};

            // BOM 품목을 공정별로 그룹화 (구매품/서비스 제외)
            bomItems.forEach(item => {
              const mapping = itemProcessMapping[item.itemCode];
              if (mapping && mapping.processCode && !mapping.isPurchased && !mapping.isService) {
                const key = mapping.processCode;
                if (!processGroups[key]) {
                  processGroups[key] = {
                    processCode: mapping.processCode,
                    processName: mapping.processName,
                    workflowCode: mapping.workflowCode,
                    processSeq: mapping.processSeq,
                    items: []
                  };
                }
                processGroups[key].items.push(item);
              }
            });

            // 공정별 작업지시서 생성
            const newWorkOrders = Object.values(processGroups)
              .sort((a, b) => a.processSeq - b.processSeq)
              .map((group, idx) => {
                const woDate = new Date(now);
                woDate.setDate(woDate.getDate() + idx); // 공정 순서대로 1일씩 추가

                return {
                  id: Date.now() + idx,
                  workOrderNo: `WO-${order.orderNo.replace('SO-', '')}-${String(idx + 1).padStart(2, '0')}`,
                  workOrderDate: woDate.toISOString().split('T')[0],
                  status: '대기',
                  orderId: order.id,
                  orderNo: order.orderNo,
                  quoteNo: order.quoteNo,
                  customerId: order.customerId,
                  customerName: order.customerName,
                  siteId: order.siteId,
                  siteName: order.siteName,
                  productType: order.productType,
                  qty: order.qty,
                  processCode: group.processCode,
                  processName: group.processName,
                  workflowCode: group.workflowCode,
                  processSeq: group.processSeq,
                  items: group.items,
                  dueDate: order.dueDate,
                  plannedStartDate: woDate.toISOString().split('T')[0],
                  plannedEndDate: woDate.toISOString().split('T')[0],
                  createdBy: '판매팀',
                  createdAt: now.toISOString(),
                  note: `${order.siteName} - ${group.processName} 공정`,
                };
              });

            // 작업지시 추가
            setWorkOrders(prev => [...newWorkOrders, ...prev]);

            // 수주 상태 업데이트 (생산지시 생성 완료)
            setOrders(prev => prev.map(o =>
              o.id === order.id ? { ...o, status: '생산지시완료' } : o
            ));

            // 알림 표시 및 작업지시 관리 페이지로 이동
            alert(`✅ ${newWorkOrders.length}개의 작업지시서가 공정별로 자동 생성되었습니다.\n\n생성된 작업지시서:\n${newWorkOrders.map(wo => `- ${wo.workOrderNo} (${wo.processName})`).join('\n')}\n\n작업지시 관리 페이지로 이동합니다.`);
            navigate('work-order-list');
          }}
          onCancelOrder={handleCancelOrder}
        />;
      case 'order-create':
        return <OrderCreate quotes={quotes} onNavigate={navigate} onBack={() => navigate('order-list')} onSave={handleSaveOrder} />;
      case 'order-create-from-quote':
        return <OrderCreate
          quotes={quotes}
          fromQuote={selectedItem}
          onNavigate={navigate}
          onBack={() => navigate('quote-detail', selectedItem)}
          onSave={(order) => {
            handleSaveOrder(order);
            // 견적 상태 업데이트
            if (selectedItem) {
              setQuotes(prev => prev.map(q =>
                q.id === selectedItem.id
                  ? { ...q, status: '수주전환', convertedOrderNo: order.orderNo }
                  : q
              ));
            }
          }}
        />;
      case 'order-create-additional':
        // 추가분 수주 생성
        const additionalData = selectedItem; // { quote, pendingItems, relatedOrders }
        return <OrderCreate
          quotes={quotes}
          fromQuote={additionalData?.quote}
          additionalItems={additionalData?.pendingItems}
          relatedOrders={additionalData?.relatedOrders}
          isAdditional={true}
          onNavigate={navigate}
          onBack={() => navigate('quote-detail', additionalData?.quote)}
          onSave={(order) => {
            // 추가분 수주 저장
            const newOrder = {
              ...order,
              orderType: 'additional',
              parentOrderNo: additionalData?.relatedOrders?.[0]?.orderNo,
            };
            handleSaveOrder(newOrder);
            // 견적 품목 상태 업데이트
            if (additionalData?.quote) {
              setQuotes(prev => prev.map(q =>
                q.id === additionalData.quote.id
                  ? {
                    ...q,
                    relatedOrders: [...(q.relatedOrders || []), newOrder.orderNo],
                    items: q.items.map(item =>
                      additionalData.pendingItems.find(pi => pi.id === item.id)
                        ? { ...item, orderStatus: 'ordered', orderId: newOrder.id }
                        : item
                    )
                  }
                  : q
              ));
            }
            navigate('quote-detail', additionalData?.quote);
          }}
        />;
      case 'order-detail':
        return <OrderDetail
          order={selectedItem}
          productionOrders={productionOrders}
          customers={customers}
          onNavigate={navigate}
          onBack={() => navigate('order-list')}
          onUpdate={(updatedOrder) => {
            setOrders(prev => prev.map(o => o.id === updatedOrder.id ? updatedOrder : o));
            setSelectedItem(updatedOrder);
          }}
          onCreateWorkOrder={(newWorkOrder) => {
            setWorkOrders(prev => [...prev, newWorkOrder]);
          }}
          onCreateProductionOrder={(order) => {
            // 수주에서 생산지시 생성 (구매품/서비스 제외)
            const now = new Date();
            const bomItems = order.items || [];
            const processGroups = {};

            bomItems.forEach(item => {
              const mapping = itemProcessMapping[item.itemCode];
              if (mapping && mapping.processCode && !mapping.isPurchased && !mapping.isService) {
                const key = mapping.processCode;
                if (!processGroups[key]) {
                  processGroups[key] = {
                    processCode: mapping.processCode,
                    processName: mapping.processName,
                    workflowCode: mapping.workflowCode,
                    processSeq: mapping.processSeq,
                    items: []
                  };
                }
                processGroups[key].items.push(item);
              }
            });

            const newPO = {
              id: Date.now(),
              productionOrderNo: `PO-${order.orderNo.replace('SO-', '')}`,
              productionOrderDate: now.toISOString().split('T')[0],
              status: '생산대기',
              orderId: order.id,
              orderNo: order.orderNo,
              quoteNo: order.quoteNo,
              customerId: order.customerId,
              customerName: order.customerName,
              siteId: order.siteId,
              siteName: order.siteName,
              productType: order.productType,
              qty: order.qty,
              dueDate: order.dueDate,
              processGroups: Object.values(processGroups).sort((a, b) => a.processSeq - b.processSeq),
              totalProcesses: Object.keys(processGroups).length,
              completedProcesses: 0,
              workOrdersGenerated: false,
              createdBy: '판매팀',
              createdAt: now.toISOString(),
              note: `${order.siteName} 생산지시`,
            };

            setProductionOrders(prev => [newPO, ...prev]);
            setOrders(prev => prev.map(o =>
              o.id === order.id ? { ...o, productionOrderNo: newPO.productionOrderNo, status: '생산지시완료' } : o
            ));

            alert(`✅ 생산지시가 생성되었습니다.\n\n생산지시번호: ${newPO.productionOrderNo}\n\n생산관리 > 생산지시 관리에서 작업지시서를 생성하세요.`);
            navigate('production-order-detail', newPO);
          }}
          onCancelOrder={handleCancelOrder}
        />;
      case 'order-edit':
        return <OrderEdit order={selectedItem} onNavigate={navigate} onBack={() => navigate('order-detail', selectedItem)} onSave={handleUpdateOrder} />;
      // 생산지시 생성 페이지
      case 'production-order-create':
        return <ProductionOrderCreatePage
          order={selectedItem}
          onBack={() => navigate('order-detail', selectedItem)}
          onNavigate={navigate}
          onConfirm={(order) => {
            // 수주에서 생산지시 생성 (구매품/서비스 제외)
            const now = new Date();
            const bomItems = order.items || [];
            const processGroups = {};

            bomItems.forEach(item => {
              const mapping = itemProcessMapping[item.itemCode];
              if (mapping && mapping.processCode && !mapping.isPurchased && !mapping.isService) {
                const key = mapping.processCode;
                if (!processGroups[key]) {
                  processGroups[key] = {
                    processCode: mapping.processCode,
                    processName: mapping.processName,
                    workflowCode: mapping.workflowCode,
                    processSeq: mapping.processSeq,
                    items: []
                  };
                }
                processGroups[key].items.push(item);
              }
            });

            const newPO = {
              id: Date.now(),
              productionOrderNo: `PO-${order.orderNo.replace('SO-', '')}`,
              productionOrderDate: now.toISOString().split('T')[0],
              status: '생산대기',
              orderId: order.id,
              orderNo: order.orderNo,
              quoteNo: order.quoteNo,
              customerId: order.customerId,
              customerName: order.customerName,
              siteId: order.siteId,
              siteName: order.siteName,
              productType: order.productType,
              qty: order.qty,
              dueDate: order.dueDate,
              processGroups: Object.values(processGroups).sort((a, b) => a.processSeq - b.processSeq),
              totalProcesses: Object.keys(processGroups).length,
              completedProcesses: 0,
              workOrdersGenerated: false,
              createdBy: '판매팀',
              createdAt: now.toISOString(),
              note: `${order.siteName} 생산지시`,
            };

            setProductionOrders(prev => [newPO, ...prev]);
            setOrders(prev => prev.map(o =>
              o.id === order.id ? { ...o, productionOrderNo: newPO.productionOrderNo, status: '생산지시완료' } : o
            ));

            alert(`✅ 생산지시가 생성되었습니다.\n\n생산지시번호: ${newPO.productionOrderNo}\n\n생산관리 > 생산지시 관리에서 작업지시서를 생성하세요.`);
            navigate('production-order-detail', newPO);
          }}
        />;
      // 생산관리 - 현황판
      case 'production-status-board':
        return <ProductionStatusBoard workOrders={workOrders} workResults={workResults} onNavigate={navigate} />;
      // 생산관리 - 작업자 화면
      case 'worker-task-view':
        return <WorkerTaskView
          workOrders={workOrders}
          workResults={workResults}
          onNavigate={navigate}
          onBack={() => navigate('production-dashboard')}
          onStartWork={(task) => {
            setWorkOrders(prev => prev.map(wo =>
              wo.id === task.id ? { ...wo, status: '작업중', startTime: new Date().toISOString() } : wo
            ));
          }}
          onCompleteWork={(task) => {
            // 작업 완료 + 실적 자동 등록
            handleCompleteWork(task);
          }}
          onReportIssue={(task, issue) => {
            console.log('Issue reported:', task.workOrderNo, issue);
            alert(`이슈가 보고되었습니다.\n작업: ${task.workOrderNo}\n유형: ${issue.type}`);
          }}
          onMaterialInput={(task) => {
            // 자재투입: 작업자 화면에서 바로 자재투입 모달 열기
            setWorkerMaterialTask(task);
            setShowWorkerMaterialModal(true);
          }}
        />;
      // 생산관리 - 제품 이력 추적
      case 'traceability-list':
        return <ProductTraceability workOrders={workOrders} workResults={workResults} onNavigate={navigate} />;
      // 생산지시 관리
      case 'production-order-list':
        return <ProductionOrderList
          productionOrders={productionOrders}
          workOrders={workOrders}
          onNavigate={navigate}
          onCreateWorkOrders={(po) => {
            // BOM 기반 공정별 작업지시서 자동 생성
            const newWorkOrders = [];
            const now = new Date();
            const baseId = Date.now();

            po.processGroups?.forEach((pg, idx) => {
              const woNo = `WO-${po.orderNo.replace('SO-', '')}-${String(idx + 1).padStart(2, '0')}`;
              newWorkOrders.push({
                id: baseId + idx,
                workOrderNo: woNo,
                workOrderDate: now.toISOString().split('T')[0],
                status: '대기',
                // 생산지시/수주 연결
                productionOrderNo: po.productionOrderNo,
                orderId: po.orderId,
                orderNo: po.orderNo,
                // 공정 정보
                processCode: pg.processCode,
                processName: pg.processName,
                processSeq: pg.processSeq,
                // 제품 정보
                productType: po.productType,
                siteName: po.siteName,
                customerName: po.customerName,
                qty: po.qty,
                totalQty: po.qty,
                completedQty: 0,
                defectQty: 0,
                // 품목 목록
                items: pg.items,
                // 작업 계획
                plannedStartDate: now.toISOString().split('T')[0],
                plannedEndDate: new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
                plannedQty: po.qty,
                // 메타
                createdBy: '생산관리',
                createdAt: now.toISOString(),
                note: `${po.siteName} ${pg.processName} 공정`,
              });
            });

            setWorkOrders(prev => [...newWorkOrders, ...prev]);

            // 생산지시 상태 업데이트
            setProductionOrders(prev => prev.map(p =>
              p.id === po.id ? { ...p, workOrdersGenerated: true, status: '생산지시완료' } : p
            ));

            // 수주 상태 업데이트 (생산지시 생성 완료)
            setOrders(prev => prev.map(o =>
              o.orderNo === po.orderNo ? { ...o, status: '생산지시완료' } : o
            ));

            alert(`✅ ${newWorkOrders.length}개의 작업지시서가 생성되었습니다.\n\n생성된 작업지시서:\n${newWorkOrders.map(wo => `- ${wo.workOrderNo} (${wo.processName})`).join('\n')}`);
          }}
        />;
      case 'production-order-detail':
        return <ProductionOrderDetail
          productionOrder={selectedItem}
          workOrders={workOrders}
          orders={orders}
          onNavigate={navigate}
          onBack={() => navigate('production-order-list')}
          onCreateWorkOrders={(po) => {
            // BOM 기반 공정별 작업지시서 자동 생성 (상세화면에서도 동일 로직)
            const newWorkOrders = [];
            const now = new Date();
            const baseId = Date.now();

            po.processGroups?.forEach((pg, idx) => {
              const woNo = `WO-${po.orderNo.replace('SO-', '')}-${String(idx + 1).padStart(2, '0')}`;
              newWorkOrders.push({
                id: baseId + idx,
                workOrderNo: woNo,
                workOrderDate: now.toISOString().split('T')[0],
                status: '대기',
                productionOrderNo: po.productionOrderNo,
                orderId: po.orderId,
                orderNo: po.orderNo,
                processCode: pg.processCode,
                processName: pg.processName,
                processSeq: pg.processSeq,
                productType: po.productType,
                siteName: po.siteName,
                customerName: po.customerName,
                qty: po.qty,
                totalQty: po.qty,
                completedQty: 0,
                defectQty: 0,
                items: pg.items,
                plannedStartDate: now.toISOString().split('T')[0],
                plannedEndDate: new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
                plannedQty: po.qty,
                createdBy: '생산관리',
                createdAt: now.toISOString(),
                note: `${po.siteName} ${pg.processName} 공정`,
              });
            });

            setWorkOrders(prev => [...newWorkOrders, ...prev]);
            setProductionOrders(prev => prev.map(p =>
              p.id === po.id ? { ...p, workOrdersGenerated: true, status: '생산지시완료' } : p
            ));
            setOrders(prev => prev.map(o =>
              o.orderNo === po.orderNo ? { ...o, status: '생산지시완료' } : o
            ));

            // 작업지시 생성 완료 후 작업지시 관리 페이지로 이동
            alert(`✅ ${newWorkOrders.length}개의 작업지시서가 공정별로 자동 생성되었습니다.\n\n생성된 작업지시서:\n${newWorkOrders.map(wo => `- ${wo.workOrderNo} (${wo.processName})`).join('\n')}\n\n작업지시 관리 페이지로 이동합니다.`);
            navigate('work-order-list');
          }}
        />;
      case 'work-order-list':
        return <WorkOrderList
          workOrders={workOrders}
          orders={orders}
          onNavigate={navigate}
          onApprove={handleApproveWorkOrder}
          onAssign={(workOrderId, assignees) => {
            // 담당자 배정 처리
            setWorkOrders(prev => prev.map(wo =>
              wo.id === workOrderId
                ? { ...wo, assignee: assignees.join(', '), assignees: assignees }
                : wo
            ));
          }}
          onStartWork={(workOrderId) => {
            // ★ 작업 시작 처리
            const now = new Date();
            setWorkOrders(prev => prev.map(wo =>
              wo.id === workOrderId
                ? {
                  ...wo,
                  status: '작업중',
                  startedAt: now.toISOString(),
                  currentStep: wo.processType === '스크린' ? '원단절단' :
                    wo.processType === '슬랫' ? '코일절단' :
                      wo.processType === '절곡' ? '절단' : '작업준비'
                }
                : wo
            ));
            alert('✅ 작업이 시작되었습니다.');
          }}
          onCompleteWork={(workOrderId) => {
            // ★ 작업 완료 처리
            const wo = workOrders.find(w => w.id === workOrderId);
            if (wo && wo.completedQty < wo.totalQty) {
              if (!confirm(`완료 수량(${wo.completedQty})이 총수량(${wo.totalQty})보다 적습니다.\n그래도 완료 처리하시겠습니까?`)) {
                return;
              }
            }
            handleCompleteWork(workOrderId);
          }}
          onProgressWork={(workOrderId, progressData) => {
            // ★ 공정 진행 저장 처리
            const now = new Date();
            setWorkOrders(prev => prev.map(wo =>
              wo.id === workOrderId
                ? {
                  ...wo,
                  completedQty: progressData.completedQty,
                  defectQty: progressData.defectQty,
                  currentStep: progressData.currentStep,
                  lastProgressAt: now.toISOString(),
                  progressNote: progressData.note,
                  // 완료 수량이 총 수량에 도달하면 자동 완료 처리하지 않고 상태만 유지
                }
                : wo
            ));

            // 불량 발생 시 NCR 자동 생성
            if (progressData.defectQty > 0) {
              const wo = workOrders.find(w => w.id === workOrderId);
              if (wo) {
                const ncrNo = `NCR-${now.toISOString().slice(0, 10).replace(/-/g, '')}-${String(ncrs.length + 1).padStart(3, '0')}`;
                const newNcr = {
                  id: Date.now(),
                  ncrNo,
                  workOrderNo: wo.workOrderNo,
                  productName: wo.siteName,
                  defectQty: progressData.defectQty,
                  defectType: '공정불량',
                  description: progressData.note || `${progressData.currentStep} 공정에서 불량 발생`,
                  reportDate: now.toISOString().split('T')[0],
                  reporter: wo.assignee || '생산팀',
                  status: '접수',
                  approvalLine: [
                    { step: 1, role: '품질담당', approver: '', status: '대기', date: null },
                    { step: 2, role: '품질팀장', approver: '', status: '대기', date: null },
                  ]
                };
                setNcrs(prev => [...prev, newNcr]);
              }
            }

            alert(`✅ 진행상황이 저장되었습니다.\n- 현재 단계: ${progressData.currentStep}\n- 완료: ${progressData.completedQty}개\n- 불량: ${progressData.defectQty}개`);
          }}
        />;
      case 'work-order-detail':
        return <WorkOrderDetail
          workOrder={selectedItem}
          workResults={workResults}
          orders={orders}
          inventory={inventory}
          materialLots={materialLots}
          onNavigate={navigate}
          onBack={() => navigate('work-order-list')}
          onUpdate={(updatedWorkOrder) => {
            setWorkOrders(prev => prev.map(wo => wo.id === updatedWorkOrder.id ? updatedWorkOrder : wo));
            setSelectedItem(updatedWorkOrder);
          }}
          onUpdateOrder={(orderNo, updates) => {
            setOrders(prev => prev.map(o => o.orderNo === orderNo ? { ...o, ...updates } : o));
          }}
          onUseMaterial={(materialCode, qty, usage) => {
            // 재고 감소
            setInventory(prev => prev.map(item =>
              item.materialCode === materialCode
                ? { ...item, stock: Math.max(0, item.stock - qty), lastUpdated: new Date().toISOString().split('T')[0] }
                : item
            ));
            // 사용 이력 추가
            setMaterialUsage(prev => [...prev, {
              id: Date.now(),
              ...usage,
              materialCode,
              qty,
              usedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
            }]);
          }}
          setActiveModal={setActiveModal}
          showFeatureDescription={showFeatureDescription}
          featureBadges={featureBadges}
          selectedBadge={selectedBadge}
          setSelectedBadge={setSelectedBadge}
          updateFeatureBadge={updateFeatureBadge}
          setEditingBadge={setEditingBadge}
        />;
      case 'work-order-register':
        return <WorkOrderCreate orders={orders} customers={customers} sites={integratedSiteMaster} onNavigate={navigate} onBack={() => navigate('work-order-list')} onSave={handleSaveWorkOrder} />;
      case 'work-order-edit':
        return <WorkOrderEdit workOrder={selectedItem} onNavigate={navigate} onBack={() => navigate('work-order-detail', selectedItem)} onSave={handleUpdateWorkOrder} />;
      case 'work-result-list':
        return <WorkResultList workResults={workResults} onNavigate={navigate} />;
      case 'work-result-input':
        return <WorkResultInput workOrder={selectedItem} onNavigate={navigate} onBack={() => navigate('work-order-detail', selectedItem)} onSave={handleSaveWorkResult} />;
      case 'work-result-create':
        return <WorkResultInput workOrder={selectedItem} onNavigate={navigate} onBack={() => navigate('worker-task-view')} onSave={handleSaveWorkResult} />;
      case 'shipment-list':
        return <ShipmentList shipments={shipments} onNavigate={navigate} />;
      case 'shipment-create':
        return <ShipmentCreate orders={orders} onNavigate={navigate} onBack={() => navigate('shipment-list')} onSave={handleSaveShipment} />;
      case 'shipment-detail':
        return <ShipmentDetail shipment={selectedItem} shipments={shipments} onNavigate={navigate} onBack={() => navigate('shipment-list')} onUpdate={handleUpdateShipment} />;
      case 'shipment-edit':
        return <ShipmentEdit shipment={selectedItem} onNavigate={navigate} onBack={() => navigate('shipment-detail', selectedItem)} onSave={handleUpdateShipment} />;
      // 품질관리 - 검사관리 (분리된 컴포넌트)
      case 'inspection-list':
        return <InspectionList onNavigate={navigate} />;
      case 'inspection-register':
        return <InspectionRegister
          onNavigate={navigate}
          onSave={() => {
            alert('검사가 완료되었습니다.');
            navigate('inspection-list');
          }}
        />;
      case 'inspection-detail':
        return <InspectionDetail inspection={selectedItem} onNavigate={navigate} />;
      case 'inspection-edit':
        return <InspectionEdit
          inspection={selectedItem}
          onNavigate={navigate}
          onSave={() => {
            alert('수정이 완료되었습니다.');
            navigate('inspection-detail', selectedItem);
          }}
        />;
      // 품질관리 - 검사템플릿 (분리된 컴포넌트)
      case 'template-list':
        return <TemplateList onNavigate={navigate} />;
      case 'template-register':
        return <TemplateRegister
          onNavigate={navigate}
          onSave={() => {
            alert('템플릿이 저장되었습니다.');
            navigate('template-list');
          }}
        />;
      case 'template-detail':
        return <TemplateDetail template={selectedItem} onNavigate={navigate} />;
      case 'template-edit':
        return <TemplateEdit
          template={selectedItem}
          onNavigate={navigate}
          onSave={() => {
            alert('수정이 완료되었습니다.');
            navigate('template-detail', selectedItem);
          }}
        />;
      // 품질관리 - 수입검사(IQC)
      case 'iqc-list':
        return <IncomingInspectionList
          purchaseOrders={purchaseOrders}
          onNavigate={navigate}
          onInspectionComplete={handleReceivePO}
        />;
      // 품질관리 - 중간검사(PQC)
      case 'pqc-list':
        return <ProcessInspectionList
          workOrders={workOrders}
          onNavigate={navigate}
          onInspectionComplete={(wo, result) => {
            // 검사 완료 시 다음 공정 진행 허용
            setWorkOrders(prev => prev.map(w =>
              w.id === wo.id ? { ...w, inspectionStatus: result.passed ? '검사합격' : '검사불합격', pqcResult: result } : w
            ));
          }}
        />;
      // 품질관리 - 제품검사(FQC)
      case 'fqc-list':
        return <ProductInspectionList inspections={productInspections} onNavigate={navigate} />;
      // 품질관리 - 검사 등록 화면 (개별)
      case 'iqc-register':
        return <IQCRegisterForm
          purchaseOrders={purchaseOrders}
          initialData={selectedItem} // 입고관리에서 전달한 데이터
          onNavigate={navigate}
          onSave={(inspectionData) => {
            // 검사 결과 저장
            setAllInspections(prev => [...prev, { ...inspectionData, id: prev.length + 1, type: 'incoming' }]);

            // 발주 데이터에 검사 결과 반영 및 합격 시 자동 입고 처리
            let updatedInbound = null;
            setPurchaseOrders(prev => prev.map(po => {
              if (po.poNo === inspectionData.targetNo) {
                const isPass = inspectionData.result === '합격';
                updatedInbound = {
                  ...po,
                  status: isPass ? '입고완료' : '검사불합격',
                  receivedQty: isPass ? po.requestQty : po.receivedQty, // 합격 시 입고 수량 자동 반영
                  receivedDate: isPass ? inspectionData.inspectionDate : po.receivedDate,
                  inspectionLot: inspectionData.lotNo, // 검사 LOT 저장
                  inspectionResult: {
                    result: inspectionData.result,
                    inspector: inspectionData.inspector,
                    inspectionDate: inspectionData.inspectionDate,
                    inspectionItems: inspectionData.inspectionItems,
                  }
                };

                // 합격 시 재고에 자동 추가
                if (isPass) {
                  setInventory(prev => [...prev, {
                    id: prev.length + 1,
                    itemCode: po.materialCode,
                    itemName: po.materialName,
                    category: '원자재',
                    lotNo: inspectionData.lotNo,
                    warehouseCode: 'WH-001',
                    warehouseName: '원자재창고',
                    locationCode: 'A-01',
                    locationName: 'A구역-01',
                    quantity: po.requestQty,
                    unit: po.unit,
                    receivedDate: inspectionData.inspectionDate,
                    expiryDate: null,
                    supplier: po.vendor,
                    poNo: po.poNo,
                    status: '정상'
                  }]);
                }

                return updatedInbound;
              }
              return po;
            }));

            alert(`✅ 수입검사가 ${inspectionData.result} 처리되었습니다.\n\nLOT번호: ${inspectionData.lotNo}${inspectionData.result === '합격' ? '\n입고 처리가 완료되었습니다.' : ''}`);
            // 입고 상세로 돌아가기
            navigate('inbound-detail', updatedInbound || selectedItem);
          }}
        />;
      case 'pqc-register':
        return <PQCRegisterForm
          workOrders={workOrders}
          onNavigate={navigate}
          onSave={(inspectionData) => {
            setAllInspections(prev => [...prev, { ...inspectionData, id: prev.length + 1, type: 'process' }]);
            navigate('inspection-list');
          }}
        />;
      case 'fqc-register':
        return <FQCRegisterForm
          workOrders={workOrders}
          shipments={shipments}
          onNavigate={navigate}
          onSave={(inspectionData) => {
            setAllInspections(prev => [...prev, { ...inspectionData, id: prev.length + 1, type: 'final' }]);
            setProductInspections(prev => [...prev, { ...inspectionData, id: prev.length + 1, type: 'final' }]);
            navigate('inspection-list');
          }}
        />;
      // 거래처 관리 (판매관리 - 회계정보 숨김)
      case 'customer-list':
        return <CustomerList customers={initialCustomers} onNavigate={navigate} hideAccountingInfo={true} />;
      case 'customer-detail':
        return <CustomerDetail customer={selectedData} onNavigate={navigate} hideAccountingInfo={true} />;
      case 'customer-register':
        return <CustomerRegister onNavigate={navigate} hideAccountingInfo={true} />;
      case 'customer-edit':
        return <CustomerRegister customer={selectedData} onNavigate={navigate} isEdit={true} hideAccountingInfo={true} />;
      // 현장 관리
      case 'site-list':
        return <SiteList sites={initialSites} onNavigate={navigate} />;
      case 'site':
        return <SiteList sites={initialSites} onNavigate={navigate} />;
      case 'site-detail':
        return <SiteDetail site={selectedData} onNavigate={navigate} />;
      case 'site-register':
        return <SiteRegister onNavigate={navigate} />;
      case 'site-edit':
        return <SiteRegister site={selectedData} onNavigate={navigate} isEdit={true} />;
      // 단가 관리 (단일 목록 + 이력관리 + 거래처그룹 할인) - 품목마스터 연동
      case 'price-list':
        return <PriceListSimple onNavigate={navigate} items={sharedItems} onUpdatePrice={handleUpdatePrice} />;
      // 자재관리 - 재고현황
      case 'stock-list':
        return <StockList inventory={inventory} onNavigate={navigate} />;
      case 'stock-detail':
        return <StockDetail stock={selectedItem} inventory={inventory} onNavigate={navigate} />;
      // 자재관리 - 입고관리
      case 'inbound-list':
        return <InboundManagement
          purchaseOrders={purchaseOrders}
          onNavigate={navigate}
          onReceive={handleReceivePO}
        />;
      case 'inbound-detail':
        return <InboundDetail
          inbound={selectedItem}
          onNavigate={navigate}
          onReceive={handleReceivePO}
        />;
      // 자재관리 - 재고조정
      case 'stock-adjustment-list':
        return <StockAdjustment inventory={inventory} onNavigate={navigate} />;
      // 품질관리 - 부적합품관리
      case 'defect-list':
        return <DefectManagement
          defects={defects}
          onNavigate={navigate}
          onProcess={handleProcessDefect}
        />;
      // 물류관리 - 배송현황
      case 'delivery-status-list':
        return <DeliveryStatusList
          shipments={shipments.filter(s => s.status === '출하확정' || s.status === '배송중' || s.status === '배송완료')}
          onNavigate={navigate}
          onUpdateStatus={handleUpdateDeliveryStatus}
        />;
      // 회계관리 - 거래처관리
      case 'acc-customer-list':
        return <AccCustomerList onNavigate={navigate} />;
      case 'acc-customer-register':
        return <AccCustomerRegister onNavigate={navigate} />;
      case 'acc-customer-detail':
        return <AccCustomerDetail customer={selectedData} onNavigate={navigate} />;
      case 'acc-customer-edit':
        return <AccCustomerRegister customer={selectedData} onNavigate={navigate} isEdit={true} />;
      case 'acc-customer-statement':
        return <TransactionStatementIssue shipments={shipments} onUpdateShipment={handleUpdateShipment} onNavigate={navigate} />;
      case 'acc-customer-tax':
        return <TaxInvoiceIssue shipments={shipments} onUpdateShipment={handleUpdateShipment} />;
      // 회계관리 - 매출관리
      case 'sales-list':
      case 'sales-account':
        return <SalesAccountManagement shipments={shipments} onNavigate={navigate} />;
      case 'sales-statement':
        return <TransactionStatementIssue shipments={shipments} onUpdateShipment={handleUpdateShipment} onNavigate={navigate} />;
      case 'sales-tax-invoice':
        return <TaxInvoiceIssue shipments={shipments} onUpdateShipment={handleUpdateShipment} />;
      // 회계관리 - 매입관리
      case 'purchase':
      case 'purchase-list':
        return <PurchaseRequestManagement />;
      case 'purchase-register':
        return <PurchaseRequestManagement mode="register" />;
      case 'expense-list':
        return <ExpenseApprovalManagement />;
      case 'expense-register':
        return <ExpenseApprovalManagement mode="register" />;
      case 'expense-estimate':
        return <ExpenseApprovalManagement mode="estimate" />;
      // 회계관리 - 금전출납부
      case 'cashbook':
      case 'cashbook-list':
        return <CashbookManagement />;
      case 'cashbook-register':
        return <CashbookManagement mode="register" />;
      case 'cashbook-edit':
        return <CashbookManagement mode="edit" />;
      // 회계관리 - 수금관리
      case 'collection-list':
        return <CollectionRegister shipments={shipments} onUpdateShipment={handleUpdateShipment} onNavigate={navigate} />;
      case 'collection-register':
        return <CollectionRegister shipments={shipments} onUpdateShipment={handleUpdateShipment} onNavigate={navigate} mode="register" />;
      case 'receivable-list':
      case 'outstanding':
      case 'receivable':
        return <OutstandingManagement />;
      case 'bill-list':
        return <BillManagement />;
      // 회계관리 - 원가관리
      case 'cost-analysis':
      case 'cost-list':
        return <CostAnalysisManagement orders={orders} workOrders={workOrders} />;
      case 'cost-detail':
        return <CostAnalysisManagement orders={orders} workOrders={workOrders} mode="detail" selectedOrder={selectedItem} />;
      // 회계관리 - 기존 호환
      case 'invoice':
        return <InvoiceManagement />;
      case 'collection':
        return <CollectionManagement />;
      // 시스템관리
      case 'users':
        return <UserManagement />;
      case 'roles':
        return <RoleManagement />;
      case 'settings':
        return <SystemSettings />;
      default:
        return (
          <div className="text-center py-20">
            <Settings className="w-16 h-16 mx-auto mb-4 text-gray-300" />
            <h2 className="text-xl font-bold text-gray-700 mb-2">준비 중인 기능입니다</h2>
            <p className="text-gray-500">해당 메뉴는 곧 구현될 예정입니다.</p>
          </div>
        );
    }
  };

  // 그레이스케일 와이어프레임 스타일
  const grayscaleStyle = wireframeMode ? {
    filter: 'grayscale(100%)',
    WebkitFilter: 'grayscale(100%)',
  } : {};

  return (
    <>
      {/* C키 누른 후 클릭 대기 상태 표시 - 컬러 유지 */}
      {isPlacingBadge && (
        <div className="fixed top-20 left-1/2 -translate-x-1/2 z-[101] bg-blue-600 text-white px-4 py-2 rounded-full shadow-lg flex items-center gap-2 animate-pulse">
          <span className="w-6 h-6 bg-white text-blue-600 rounded-full flex items-center justify-center font-bold text-sm">
            {nextBadgeNumber}
          </span>
          <span className="text-sm font-medium">클릭하여 #{nextBadgeNumber} 뱃지 배치</span>
          <span className="text-xs opacity-75">(ESC 취소)</span>
        </div>
      )}

      {/* 인라인 입력창 - 컬러 유지, 최상단 z-index */}
      {inlineInputPosition && (
        <div className="fixed inset-0 z-[9999]" style={{ pointerEvents: 'none' }}>
          <div style={{ pointerEvents: 'auto' }}>
            <InlineBadgeInput
              position={inlineInputPosition}
              number={nextBadgeNumber}
              onSave={addInlineBadge}
              onCancel={() => setInlineInputPosition(null)}
            />
          </div>
        </div>
      )}

      {/* 인라인 뱃지 수정 팝업 - 컬러 유지, 최상단 z-index */}
      {editingBadge && (
        <div className="fixed inset-0 z-[9999]" style={{ pointerEvents: 'none' }}>
          <div style={{ pointerEvents: 'auto' }}>
            <InlineBadgeInput
              position={{ x: editingBadge.x, y: editingBadge.y }}
              number={editingBadge.number}
              existingBadge={editingBadge}
              onSave={updateInlineBadge}
              onCancel={() => setEditingBadge(null)}
              onDelete={(badgeId) => {
                deleteWithPassword(badgeId, () => setEditingBadge(null));
              }}
            />
          </div>
        </div>
      )}

      {/* 기능정의서 활성화 시: 화면 정보 헤더 - 그레이스케일 외부, fixed로 다이얼로그 위에 표시 */}
      {!isMobile && showFeatureDescription && (
        <div className="fixed top-0 left-0 right-0 bg-white border-b border-gray-300 z-[10001]" style={{ filter: 'grayscale(100%)' }}>
          <table className="text-sm border-collapse">
            <tbody>
              <tr className="border-b border-gray-200">
                <td className="py-1.5 px-3 font-semibold bg-gray-100 border-r border-gray-200 whitespace-nowrap">화면명</td>
                <td className="py-1.5 px-3 border-r border-gray-200 whitespace-nowrap">{getScreenName()}</td>
                <td className="py-1.5 px-3 font-semibold bg-gray-100 border-r border-gray-200 whitespace-nowrap">화면ID</td>
                <td className="py-1.5 px-3 font-mono relative">
                  <span>{getScreenId()}</span>
                  <button
                    onClick={() => setShowIdCodeHelp(!showIdCodeHelp)}
                    className="ml-2 w-5 h-5 rounded-full border border-gray-400 text-gray-500 hover:bg-gray-200 text-xs inline-flex items-center justify-center"
                    title="화면ID 코드 체계 설명"
                  >
                    ?
                  </button>
                  {/* 화면ID 코드 체계 설명 팝업 */}
                  {showIdCodeHelp && (
                    <div className="absolute top-full left-0 mt-1 w-80 bg-white border border-gray-300 rounded shadow-lg z-[10002] text-left">
                      <div className="px-3 py-2 bg-gray-100 border-b border-gray-300 flex items-center justify-between">
                        <span className="font-semibold text-sm">{idCodeHelpContent.title}</span>
                        <button
                          onClick={() => setShowIdCodeHelp(false)}
                          className="text-gray-500 hover:text-gray-700"
                        >
                          ×
                        </button>
                      </div>
                      <div className="p-3 max-h-64 overflow-y-auto">
                        {idCodeHelpContent.sections.map((section, idx) => (
                          <div key={idx} className="mb-2">
                            <div className="font-medium text-xs text-gray-800">{section.category}</div>
                            <div className="text-xs text-gray-500 ml-2">{section.description}</div>
                            <div className="text-xs text-gray-600 ml-2">
                              {section.examples.map((ex, i) => (
                                <span key={i} className="mr-2">{ex}</span>
                              ))}
                            </div>
                          </div>
                        ))}
                        <div className="mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600">
                          {idCodeHelpContent.suffix}
                        </div>
                      </div>
                    </div>
                  )}
                </td>
              </tr>
              <tr>
                <td className="py-1.5 px-3 font-semibold bg-gray-100 border-r border-gray-200">화면경로</td>
                <td className="py-1.5 px-3 truncate" colSpan="3" title={getScreenPath()}>{getScreenPath()}</td>
              </tr>
            </tbody>
          </table>
        </div>
      )}

      <div className={`flex h-screen bg-gray-50 ${!isMobile && showFeatureDescription ? 'pt-[52px]' : ''}`}>
        {/* 좌측: 그레이스케일 적용 영역 (사이드바 + 메인 컨텐츠) */}
        <div className="flex flex-col flex-1 overflow-hidden" style={grayscaleStyle}>
          {/* 사이드바 + 메인 컨텐츠 영역 */}
          <div className="flex flex-1 overflow-hidden">
            {/* 데스크탑/태블릿: 사이드바 */}
            {!isMobile && (
              <Sidebar
                activeMenu={activeMenu}
                onMenuChange={handleMenuChange}
                menuConfig={menuConfig}
                onOpenSettings={() => setShowSettings(true)}
              />
            )}

            {/* 기능정의문서 패널 - 좌측에서 슬라이드 */}
            {!isMobile && showFeatureDocPanel && (
              <FeatureDocPanel
                isOpen={showFeatureDocPanel}
                onClose={() => setShowFeatureDocPanel(false)}
                screenFeatures={getFeaturesByCurrentScreen(activeMenu, view)}
                currentScreenName={activeMenu}
                currentView={view}
                onBadgeHover={setHoveredBadgeNumber}
              />
            )}

            {/* 메인 컨텐츠 */}
            <div className="flex-1 flex flex-col overflow-hidden">
              {/* 모바일: 상단 헤더 */}
              {isMobile && (
                <MobileHeader
                  onMenuToggle={() => setShowMobileMenu(true)}
                  showBack={view !== 'order-list'}
                  onBack={() => navigate('order-list')}
                />
              )}

              {/* 데스크탑/태블릿: 상단 헤더 */}
              {!isMobile && (
                <DesktopHeader
                  user={currentUser}
                  users={users}
                  onUserChange={handleUserChange}
                  showFeatureDescription={showFeatureDescription}
                  onToggleFeatureDescription={handleToggleFeatureDescription}
                  currentVersion={currentVersion}
                  hasChanges={hasChanges}
                  onOpenHistory={() => setShowVersionHistory(true)}
                  showFlowPanel={showFlowPanel}
                  onToggleFlowPanel={() => setShowFlowPanel(!showFlowPanel)}
                  userNickname={userNickname}
                  showFeatureDocPanel={showFeatureDocPanel}
                  onToggleFeatureDocPanel={() => setShowFeatureDocPanel(!showFeatureDocPanel)}
                  showComprehensiveFlowPanel={showComprehensiveFlowPanel}
                  onToggleComprehensiveFlowPanel={() => setShowComprehensiveFlowPanel(!showComprehensiveFlowPanel)}
                  showAllMenuFeatureDocPanel={showAllMenuFeatureDocPanel}
                  onToggleAllMenuFeatureDocPanel={() => setShowAllMenuFeatureDocPanel(!showAllMenuFeatureDocPanel)}
                  isFeatureAdmin={isFeatureAdmin}
                />
              )}

              {/* 메인 컨텐츠 영역 */}
              <main
                ref={contentAreaRef}
                className={`flex-1 overflow-y-auto relative ${isPlacingBadge ? 'cursor-crosshair' : ''}`}
                onClick={handleContentAreaClick}
              >
                <div className={`${isMobile ? 'p-4' : 'p-6'} relative`}>
                  {renderContent()}
                </div>

                {/* 기능정의문서 자동 번호 뱃지 오버레이 */}
                {!isMobile && showFeatureDocPanel && (
                  <FeatureDocBadgeOverlay
                    screenFeatures={getFeaturesByCurrentScreen(activeMenu, view)}
                    isVisible={showFeatureDocPanel}
                    hoveredNumber={hoveredBadgeNumber}
                    onBadgeClick={(badge) => {
                      console.log('Badge clicked:', badge);
                    }}
                  />
                )}
              </main>
            </div>
          </div>
        </div>

        {/* 뱃지 오버레이 - 그레이스케일 밖에서 컬러 유지, 메인 영역 위에 고정 */}
        {/* 모든 UI 요소 위에 표시되도록 z-[9999] 설정 */}
        {!isMobile && showFeatureDescription && contentAreaBounds.width > 0 && (
          <div
            className="fixed pointer-events-none"
            style={{
              top: contentAreaBounds.top,
              left: contentAreaBounds.left,
              width: contentAreaBounds.width,
              height: contentAreaBounds.height,
              overflow: 'hidden',
              zIndex: 9999
            }}
          >
            <div
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: scrollState.height,
                transform: `translateY(-${scrollState.top}px)`
              }}
            >
              <FeatureBadgeOverlay
                badges={getCurrentScreenBadges()}
                selectedBadge={selectedBadge}
                onSelectBadge={setSelectedBadge}
                badgeEditMode={badgeEditMode}
                onUpdatePosition={(badgeId, pos) => updateFeatureBadge(badgeId, pos)}
                onAnalyzeAndUpdate={(badgeId, analysis) => {
                  updateFeatureBadge(badgeId, {
                    ...(analysis.label && !getCurrentScreenBadges().find(b => b.id === badgeId)?.label ? { label: analysis.label } : {}),
                    uiInfo: analysis.uiInfo,
                    funcInfo: analysis.funcInfo,
                    dataInfo: analysis.dataInfo,
                  });
                }}
                onEditBadge={(badge) => setEditingBadge(badge)}
              />
            </div>
          </div>
        )}

        {/* 기능정의서 + 플로우 우측 패널 영역 - 반응형 레이아웃 */}
        {!isMobile && (showFeatureDescription || showFlowPanel || showComprehensiveFlowPanel) && (
          <div className={`flex flex-shrink-0 z-[10010] ${showFeatureDescription ? '-mt-[52px] h-screen' : 'h-full'}`} data-feature-panel="true">
            {/* 기능정의서 패널 */}
            {showFeatureDescription && (
              <div
                className={`${(showFlowPanel || showComprehensiveFlowPanel) ? 'w-72 min-w-[288px]' : 'w-80 min-w-[320px]'} flex-shrink-0 border-l bg-white overflow-hidden feature-description-panel transition-all duration-200 h-full`}
              >
                <FeatureDescriptionPanel
                  isOpen={showFeatureDescription}
                  onClose={() => setShowFeatureDescription(false)}
                  badges={getCurrentScreenBadges()}
                  selectedBadge={selectedBadge}
                  onSelectBadge={setSelectedBadge}
                  onUpdateBadge={updateFeatureBadge}
                  onDeleteBadge={deleteFeatureBadge}
                  onAddBadge={addFeatureBadge}
                  isAddingBadge={isAddingBadge}
                  setIsAddingBadge={setIsAddingBadge}
                  badgeEditMode={badgeEditMode}
                  setBadgeEditMode={setBadgeEditMode}
                  screenName={getScreenName()}
                  screenPath={getScreenPath()}
                  screenId={getScreenId()}
                  allBadges={featureBadges}
                  onImportBadges={setFeatureBadges}
                  userNickname={userNickname}
                  onChangeNickname={() => setShowNicknameModal(true)}
                  onLoadTemplate={loadTemplateToCurrentScreen}
                  currentScreenKey={getCurrentScreenKey()}
                  hasTemplate={checkHasTemplate()}
                  onExtractFeatures={extractFeatures}
                  onAddComment={addBadgeComment}
                  onDeleteComment={deleteBadgeComment}
                  isAdmin={isFeatureAdmin}
                />
              </div>
            )}

            {/* 유저플로우 패널 - 기능정의서 우측에 표시 */}
            {showFlowPanel && (
              <div
                className={`${showFeatureDescription ? 'w-72 min-w-[288px]' : 'w-80 min-w-[320px]'} flex-shrink-0 border-l bg-white overflow-hidden transition-all duration-200`}
              >
                <UserFlowPanel
                  isOpen={showFlowPanel}
                  onClose={() => setShowFlowPanel(false)}
                  onNavigate={(menu, viewName) => {
                    setActiveMenu(menu);
                    setView(viewName);
                  }}
                />
              </div>
            )}

            {/* 종합 플로우 패널 - 드래그로 너비 조절 가능 */}
            {showComprehensiveFlowPanel && (
              <ComprehensiveFlowPanel
                isOpen={showComprehensiveFlowPanel}
                onClose={() => setShowComprehensiveFlowPanel(false)}
                width={comprehensiveFlowPanelWidth}
                onWidthChange={setComprehensiveFlowPanelWidth}
                isInline={true}
              />
            )}
          </div>
        )}
      </div>

      {/* 모바일 메뉴 */}
      {isMobile && (
        <MobileMenu
          isOpen={showMobileMenu}
          onClose={() => setShowMobileMenu(false)}
          activeMenu={activeMenu}
          onMenuChange={handleMenuChange}
          menuConfig={menuConfig}
        />
      )}

      {/* 메뉴 설정 모달 */}
      {showSettings && (
        <MenuSettings
          menuConfig={menuConfig}
          onSave={setMenuConfig}
          onClose={() => setShowSettings(false)}
        />
      )}

      {/* 닉네임 입력 모달 */}
      {showNicknameModal && (
        <NicknameModal onSave={saveNickname} currentNickname={userNickname} />
      )}

      {/* 기능정의서 어드민 비밀번호 모달 */}
      {showAdminPasswordModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[9999]">
          <div className="bg-white rounded-xl shadow-2xl p-6 w-96">
            <h3 className="text-lg font-bold mb-4">기능정의서 접근</h3>
            <p className="text-sm text-gray-600 mb-4">
              어드민 비밀번호를 입력하면 모든 사용자의 글을 볼 수 있습니다.<br />
              빈칸으로 입력하면 일반 사용자로 접근합니다.
            </p>
            <input
              type="password"
              placeholder="어드민 비밀번호 (선택)"
              value={adminPassword}
              onChange={(e) => {
                setAdminPassword(e.target.value);
                setAdminPasswordError('');
              }}
              onKeyDown={(e) => e.key === 'Enter' && handleAdminPasswordSubmit()}
              className="w-full border rounded-lg px-4 py-3 mb-2 text-sm"
              autoFocus
            />
            {adminPasswordError && (
              <p className="text-red-500 text-xs mb-3">{adminPasswordError}</p>
            )}
            <div className="flex gap-2 mt-4">
              <button
                onClick={() => {
                  setShowAdminPasswordModal(false);
                  setAdminPassword('');
                  setAdminPasswordError('');
                }}
                className="flex-1 px-4 py-2 border rounded-lg text-gray-600 hover:bg-gray-50"
              >
                취소
              </button>
              <button
                onClick={handleAdminPasswordSubmit}
                className="flex-1 px-4 py-2 bg-purple-600 rounded-lg hover:bg-purple-700"
                style={{ color: '#ffffff' }}
              >
                {adminPassword ? '어드민 진입' : '일반 진입'}
              </button>
            </div>
            {isFeatureAdmin && (
              <p className="text-xs text-green-600 mt-3 text-center">
                현재 어드민 모드가 활성화되어 있습니다.
              </p>
            )}
          </div>
        </div>
      )}

      {/* 작업자 화면 자재투입 모달 */}
      {showWorkerMaterialModal && workerMaterialTask && (
        <MaterialInputModal
          workOrder={workerMaterialTask}
          inventory={inventory}
          materialLots={materialLots}
          onClose={() => {
            setShowWorkerMaterialModal(false);
            setWorkerMaterialTask(null);
          }}
          onSubmit={(materialCode, qty, lotNo, inputBy, note) => {
            // 재고 감소 처리
            handleUseMaterial?.(materialCode, qty, {
              workOrderNo: workerMaterialTask.workOrderNo,
              lotNo,
              inputBy,
              note,
            });

            // 작업지시에 투입 이력 추가
            const material = inventory.find(m => m.materialCode === materialCode);
            const newInput = {
              id: Date.now(),
              materialCode,
              materialName: material?.materialName || '',
              lotNo,
              qty,
              unit: material?.unit || '',
              inputBy,
              inputAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
              note,
            };

            // 작업지시 업데이트
            setWorkOrders(prev => prev.map(wo =>
              wo.id === workerMaterialTask.id
                ? { ...wo, materialInputs: [...(wo.materialInputs || []), newInput] }
                : wo
            ));

            alert(`✅ 자재 투입이 등록되었습니다.\n\n자재: ${material?.materialName}\n투입량: ${qty} ${material?.unit}\nLOT: ${lotNo}`);
            setShowWorkerMaterialModal(false);
            setWorkerMaterialTask(null);
          }}
        />
      )}

      {/* 버전 히스토리 모달 */}
      <VersionHistoryModal
        isOpen={showVersionHistory}
        onClose={() => setShowVersionHistory(false)}
        history={versionHistory}
        onCommit={commitVersion}
        onRollback={rollbackToVersion}
        currentVersion={currentVersion}
        hasChanges={hasChanges}
        autoMessage={autoCommitMessage}
      />

      {/* 유저플로우 네비게이터 (레거시 모달 - 패널 방식으로 대체됨) */}
      {/* 패널 방식: 헤더의 플로우 버튼 클릭 시 우측 패널로 표시됨 (showFlowPanel) */}
      {/* 아래 모달은 다른 곳에서 showUserFlow를 사용하는 경우를 위해 유지 */}
      {showUserFlow && (
        <UserFlowNavigator
          onClose={() => setShowUserFlow(false)}
          onNavigate={(menu, viewName) => {
            setActiveMenu(menu);
            setView(viewName);
          }}
        />
      )}

      {/* 상세 플로우 다이어그램 (ReactFlow 기반) */}
      {showDetailedFlowDiagram && (
        <DetailedFlowDiagram
          flowType={detailedFlowType}
          onClose={() => setShowDetailedFlowDiagram(false)}
        />
      )}

      {/* 종합 플로우차트 패널은 이제 메인 레이아웃에 인라인으로 통합됨 (우측 푸시 패널 방식) */}

      {/* 전체 메뉴 기능정의서 패널 - 모든 메뉴/페이지/섹션/항목 순차 정의 */}
      <AllMenuFeatureDocPanel
        isOpen={showAllMenuFeatureDocPanel}
        onClose={() => setShowAllMenuFeatureDocPanel(false)}
      />

      {/* 전체 기능정의서 조회 모달 - 모든 화면의 뱃지 통합 조회/관리 */}
      {showAllFeatureBadgesViewer && (
        <AllFeatureBadgesViewer
          allBadges={featureBadges}
          isAdmin={isFeatureAdmin}
          onClose={() => setShowAllFeatureBadgesViewer(false)}
        />
      )}
    </>
  );
}
