import React, { useState, useEffect } from 'react';
import { 
  Search, Plus, FileText, Package, Truck, Factory, Users, DollarSign,
  ChevronDown, ChevronRight, ChevronLeft, MoreHorizontal, Edit, Edit3, Trash2, Eye, Printer,
  CheckCircle, Clock, AlertCircle, X, Calendar, Building, Phone, MapPin,
  ArrowLeft, Copy, Send, Download, Check, XCircle, Settings, BarChart3,
  ClipboardList, Box, Warehouse, ShieldCheck, Clipboard, CreditCard, GitBranch,
  Play, Bell, User, ShoppingCart, Zap, Layers, Home, Menu, Sun
} from 'lucide-react';

/*
 * ============================================================
 * 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/번호 체계 정의 ============
/*
  [번호 체계 규칙]
  
  1. 견적번호: KD-PR-YYMMDD-순번
     예) KD-PR-250717-02
  
  2. 수주번호: KD-SO-YYMMDD-순번
     예) KD-SO-250805-03
  
  3. 생산 LOT: KD-PL-YYMMDD-순번
     예) KD-PL-250810-01
  
  4. 완제품 LOT: KD-공장코드-YYMMDD-순번-분할순번
     예) KD-TS-250717-02-01
     공장코드: TS(스크린), SL(슬랫), BN(절곡)
  
  5. 부품 LOT: 완제품 LOT와 동일 형식
     예) KD-TS-250717-02-01
  
  6. 재고생산 LOT: 품목코드 기반
     예) TS4B19-40
  
  7. 검사 LOT:
     - 입고검사: YYMMDD-순번 (예: 250715-02)
     - 중간검사: KD-공정코드-YYMMDD-순번-(공정단계) (예: KD-SC-250209-01-(3))
       공정코드: SC(스크린), SL(슬랫), BD(절곡)
     - 제품검사: KD-SA-YYMMDD-순번 (예: KD-SA-250604-01)
  
  8. 설치 LOT: 제품검사 LOT와 동일
  
  9. 출하번호: 별도 체계 없음 (내부 관리용)
*/

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

const processCodes = {
  '스크린': 'SC',
  '슬랫': 'SL',
  '절곡': 'BD',
};

// 날짜를 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 generateQuoteNo = (date, seq) => `KD-PR-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
const generateOrderNo = (date, seq) => `KD-SO-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
const generateProductionLot = (date, seq) => `KD-PL-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
const generateProductLot = (processType, date, seq, splitSeq = 1) => 
  `KD-${factoryCodes[processType] || 'XX'}-${formatDateCode(date)}-${String(seq).padStart(2, '0')}-${String(splitSeq).padStart(2, '0')}`;
const generateIncomingInspectionLot = (date, seq) => `${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;
const generateProcessInspectionLot = (processType, date, seq, step) => 
  `KD-${processCodes[processType] || 'XX'}-${formatDateCode(date)}-${String(seq).padStart(2, '0')}-(${step})`;
const generateProductInspectionLot = (date, seq) => `KD-SA-${formatDateCode(date)}-${String(seq).padStart(2, '0')}`;

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

// 상태 배지
const StatusBadge = ({ status }) => {
  const color = statusColors[status] || { bg: 'bg-gray-100', text: 'text-gray-700' };
  return (
    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${color.bg} ${color.text}`}>
      {status}
    </span>
  );
};

// 대시보드 카드
const DashboardCard = ({ icon: Icon, title, value, subtitle, color = 'blue', onClick }) => {
  const bgColors = {
    blue: 'bg-blue-50',
    green: 'bg-green-50',
    yellow: 'bg-yellow-50',
    purple: 'bg-purple-50',
    red: 'bg-red-50',
  };
  const iconColors = {
    blue: 'text-blue-500',
    green: 'text-green-500',
    yellow: 'text-yellow-500',
    purple: 'text-purple-500',
    red: 'text-red-500',
  };
  return (
    <div 
      className={`${bgColors[color]} rounded-xl p-5 flex items-center justify-between ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
      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>
      <div className={`w-12 h-12 rounded-lg bg-white/60 flex items-center justify-center`}>
        <Icon className={`w-6 h-6 ${iconColors[color]}`} />
      </div>
    </div>
  );
};

// ============================================================
// 역할별 권한 시스템
// ============================================================
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: '✓' },
  'incoming-inspection': { ceo: '✓', sales: '-', production: '-', quality: '✓', accounting: '-', purchase: '△', worker: '-' },
  'process-inspection': { ceo: '✓', sales: '-', production: '△', quality: '✓', accounting: '-', purchase: '-', worker: '△' },
  'final-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: 'approval-status', name: '결재 현황', desc: '대기중인 결재 건', width: 'half', enabled: true, order: 13 },
    { id: 'calendar', name: '일정 캘린더', desc: '주요 일정 및 회의', width: 'half', enabled: true, order: 14 },
  ]);
  
  // 샘플 데이터
  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 오후' },
      ],
    },
    
    // 결재 현황
    approvalStatus: {
      total: 12,
      items: [
        { type: '지출결의서', urgent: 2, count: 5 },
        { type: '휴가신청서', urgent: 0, count: 3 },
        { type: '구매요청서', urgent: 1, count: 4 },
      ],
    },
    
    // 오늘 일정
    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 'approval-status':
        return <ApprovalStatusWidget data={dashboardData.approvalStatus} />;
      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-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.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.toLocaleString()}만원</p>
          <p className="text-xs text-red-600 mt-2">연체: {data.overdueReceivable.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.toLocaleString()}만원</p>
          <p className="text-xs text-gray-500 mt-2">매출-매입-경비: {data.dailyProfit.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>}
                    {item.progress !== undefined && (
                      <div className="mt-1">
                        <div className="w-full bg-gray-200 rounded-full h-1.5">
                          <div className={`h-1.5 rounded-full ${item.progress > 50 ? 'bg-green-500' : 'bg-yellow-500'}`} style={{ width: `${item.progress}%` }} />
                        </div>
                        <p className="text-xs text-right mt-0.5">{item.progress}%</p>
                      </div>
                    )}
                  </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>}
                    {item.progress !== undefined && item.progress > 0 && (
                      <div className="mt-1">
                        <div className="w-full bg-gray-200 rounded-full h-1.5">
                          <div className="bg-purple-500 h-1.5 rounded-full" style={{ width: `${item.progress}%` }} />
                        </div>
                        <p className="text-xs text-right mt-0.5">{item.progress}%</p>
                      </div>
                    )}
                  </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 ApprovalStatusWidget = ({ data }) => (
  <div className="bg-white rounded-xl border p-5">
    <div className="flex items-center gap-2 mb-4">
      <FileText className="w-4 h-4 text-gray-600" />
      <span className="font-medium text-gray-900">결재 현황</span>
      <span className="ml-auto px-2 py-0.5 bg-red-500 text-white text-xs rounded-full">{data.total}</span>
    </div>
    <div className="space-y-2">
      {data.items.map((item, i) => (
        <div key={i} className="flex justify-between items-center py-2 border-b last:border-0">
          <div className="flex items-center gap-2">
            {item.urgent > 0 && <AlertCircle className="w-4 h-4 text-red-500" />}
            <span className="text-sm text-gray-900">{item.type}</span>
          </div>
          <div className="flex items-center gap-2">
            {item.urgent > 0 && (
              <span className="px-2 py-0.5 bg-red-100 text-red-700 text-xs rounded">긴급 {item.urgent}</span>
            )}
            <span className="text-sm text-gray-600">{item.count}건</span>
          </div>
        </div>
      ))}
    </div>
  </div>
);

// 15. 캘린더 위젯
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">
              <X className="w-5 h-5" />
            </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 = ({ onNavigate }) => {
  const data = {
    monthlyQuotes: 45,
    conversionRate: 32,
    pendingShipments: 12,
    deliveryRate: 94.5,
    todayQuotes: [
      { no: 'KD-PR-251205-01', customer: '삼성전자', amount: 4500, status: '검토중' },
      { no: 'KD-PR-251205-02', customer: 'LG전자', amount: 3200, status: '대기' },
    ],
    weeklyShipments: [
      { date: '12/05', customer: '삼성전자', count: 3 },
      { date: '12/06', customer: 'LG전자', count: 2 },
      { date: '12/07', customer: '현대건설', count: 5 },
    ],
  };
  
  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-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.monthlyQuotes}건</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-blue-600 mt-1">{data.conversionRate}%</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.pendingShipments}건</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.deliveryRate}%</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.todayQuotes.map((q, i) => (
              <div key={i} className="flex justify-between items-center p-2 bg-gray-50 rounded">
                <div>
                  <p className="font-mono text-sm">{q.no}</p>
                  <p className="text-sm text-gray-600">{q.customer} {q.amount.toLocaleString()}만원</p>
                </div>
                <span className={`px-2 py-1 rounded text-xs ${
                  q.status === '검토중' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'
                }`}>
                  {q.status}
                </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.weeklyShipments.map((s, i) => (
              <div key={i} className="flex justify-between items-center p-2 bg-gray-50 rounded">
                <span className="text-sm font-medium">{s.date}</span>
                <span className="text-sm text-gray-600">{s.customer}</span>
                <span className="text-sm font-bold">{s.count}건</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// 생산관리 대시보드
const ProductionDashboard = ({ onNavigate }) => {
  const data = {
    todayProduction: { completed: 24, target: 30 },
    achievementRate: 80,
    inProgress: 5,
    defectRate: 0.8,
    processes: [
      { name: '절곡', progress: 80 },
      { name: '용접', progress: 60 },
      { name: '조립', progress: 40 },
    ],
    urgentOrders: [
      { no: 'MO-001', customer: '삼성전자', dDay: 1 },
      { no: 'MO-002', customer: 'LG전자', dDay: 2 },
      { no: 'MO-003', customer: '현대건설', dDay: 3 },
    ],
  };
  
  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-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.todayProduction.completed}/{data.todayProduction.target} SET</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-blue-600 mt-1">{data.achievementRate}%</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.inProgress}건</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.defectRate}%</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-3">
            {data.processes.map((p, i) => (
              <div key={i}>
                <div className="flex justify-between text-sm mb-1">
                  <span>{p.name}</span>
                  <span>{p.progress}%</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-3">
                  <div 
                    className={`h-3 rounded-full ${p.progress >= 70 ? 'bg-green-500' : p.progress >= 50 ? 'bg-yellow-500' : 'bg-red-500'}`}
                    style={{ width: `${p.progress}%` }}
                  />
                </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="space-y-2">
            {data.urgentOrders.map((o, i) => (
              <div key={i} className="flex justify-between items-center p-2 bg-red-50 rounded">
                <div>
                  <p className="font-mono text-sm">{o.no}</p>
                  <p className="text-sm text-gray-600">{o.customer}</p>
                </div>
                <span className="px-2 py-1 bg-red-100 text-red-700 rounded text-sm font-bold">
                  D-{o.dDay}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// 품질관리 대시보드
const QualityDashboard = ({ onNavigate }) => {
  const data = {
    incomingInspection: 3,
    processInspection: 5,
    finalInspection: 2,
    monthlyDefectRate: 0.5,
    pendingInspections: [
      { lot: 'L-251205-001', type: '수입검사', item: '알루미늄 프레임' },
      { lot: 'MO-001', type: '공정검사', item: '스크린셔터' },
      { lot: 'MO-002', 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-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 = ({ onNavigate }) => {
  const data = {
    monthlySales: 32000,
    totalReceivable: 8200,
    monthlyPurchase: 18000,
    totalPayable: 4500,
    collectSchedule: [
      { date: '12/10', customer: '삼성전자', amount: 2400 },
      { date: '12/15', customer: 'LG전자', amount: 1800 },
    ],
    paymentSchedule: [
      { date: '12/15', vendor: '철강공업', amount: 800 },
      { date: '12/20', vendor: '모터공급사', amount: 500 },
    ],
  };
  
  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-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.monthlySales / 10000).toFixed(1)}억</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-red-600 mt-1">{data.totalReceivable.toLocaleString()}만원</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.monthlyPurchase / 10000).toFixed(1)}억</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-orange-600 mt-1">{data.totalPayable.toLocaleString()}만원</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.collectSchedule.map((c, i) => (
              <div key={i} className="flex justify-between items-center p-2 bg-blue-50 rounded">
                <span className="text-sm">{c.date}</span>
                <span className="text-sm text-gray-600">{c.customer}</span>
                <span className="font-bold text-blue-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">
            {data.paymentSchedule.map((p, i) => (
              <div key={i} className="flex justify-between items-center p-2 bg-orange-50 rounded">
                <span className="text-sm">{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>
    </div>
  );
};

// 작업자 대시보드 (모바일 최적화)
const WorkerDashboard = ({ onNavigate }) => {
  const data = {
    userName: '김작업',
    todayCompleted: 5,
    inProgress: 1,
    defects: 0,
    tasks: [
      { no: 'MO-251205-01', name: '스크린셔터', qty: 3, unit: 'SET', status: '진행중' },
      { no: 'MO-251205-02', name: '철재셔터', qty: 2, unit: 'SET', status: '대기' },
    ],
  };
  
  return (
    <div className="space-y-4 max-w-md mx-auto">
      <div className="bg-blue-600 text-white rounded-xl p-4">
        <p className="text-lg font-bold">👷 {data.userName} 님</p>
        <p className="text-sm opacity-80">오늘 작업 현황</p>
      </div>
      
      {/* 내 작업 목록 */}
      <div className="bg-white rounded-xl border p-4">
        <h3 className="font-medium text-gray-900 mb-3">📋 내 작업 목록</h3>
        <div className="space-y-3">
          {data.tasks.map((task, i) => (
            <div key={i} className={`p-3 rounded-lg border-2 ${
              task.status === '진행중' ? 'border-blue-500 bg-blue-50' : 'border-gray-200'
            }`}>
              <div className="flex justify-between items-start mb-2">
                <div>
                  <p className="font-mono text-sm">{task.no}</p>
                  <p className="font-medium">{task.name} {task.qty}{task.unit}</p>
                </div>
                <span className={`px-2 py-1 rounded text-xs ${
                  task.status === '진행중' ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600'
                }`}>
                  {task.status === '진행중' ? '▶ 진행중' : '○ 대기'}
                </span>
              </div>
              <button className={`w-full py-2 rounded-lg text-sm font-medium ${
                task.status === '진행중' 
                  ? 'bg-blue-600 text-white' 
                  : 'bg-gray-100 text-gray-700'
              }`}>
                {task.status === '진행중' ? '작업일지 입력' : '작업 시작'}
              </button>
            </div>
          ))}
        </div>
      </div>
      
      {/* 오늘 내 실적 */}
      <div className="bg-white rounded-xl border p-4">
        <h3 className="font-medium text-gray-900 mb-3">📊 오늘 내 실적</h3>
        <div className="grid grid-cols-3 gap-2">
          <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">{data.todayCompleted} SET</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">{data.inProgress} SET</p>
          </div>
          <div className="bg-gray-50 rounded-lg p-3 text-center">
            <p className="text-xs text-gray-500">불량</p>
            <p className="text-xl font-bold text-gray-600">{data.defects} SET</p>
          </div>
        </div>
      </div>
    </div>
  );
};

// 탭 필터
const TabFilter = ({ tabs, activeTab, onTabChange }) => (
  <div className="flex gap-1 border-b">
    {tabs.map(tab => (
      <button
        key={tab.id}
        onClick={() => onTabChange(tab.id)}
        className={`px-4 py-2.5 text-sm font-medium rounded-t-lg transition-colors
          ${activeTab === tab.id 
            ? 'bg-blue-500 text-white' 
            : 'text-gray-500 hover:bg-gray-100'}`}
      >
        {tab.label} {tab.count !== undefined && <span className="ml-1">{tab.count}</span>}
      </button>
    ))}
  </div>
);

// 검색 입력
const SearchInput = ({ placeholder, value, onChange }) => (
  <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={placeholder}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
    />
  </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',
  };
};

// 모바일 헤더 컴포넌트
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 }) => {
  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 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: 'process', label: '공정관리', icon: GitBranch },
      { id: 'item', label: '품목관리', icon: Package },
      { id: 'inspection-standard', label: '검사기준관리', icon: ShieldCheck },
      { id: 'number-rule', label: '번호기준관리', icon: ClipboardList },
      { id: 'code-rule', label: '코드기준관리', icon: Layers },
      { id: 'quote-formula', label: '견적수식관리', icon: Calculator },
    ]},
    { id: 'sales', label: '판매관리', icon: DollarSign, subMenus: [
      { id: 'customer', label: '거래처관리', icon: Users },
      { id: 'quote', label: '견적관리', icon: FileText },
      { id: 'order', label: '수주관리', icon: Package },
      { id: 'shipment', label: '출하관리', icon: Truck },
      { id: 'site', label: '현장관리', icon: Building },
      { id: 'price', label: '단가관리', icon: DollarSign },
    ]},
    { id: 'production', label: '생산관리', icon: Factory, subMenus: [
      { 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: 'incoming-inspection', label: '수입검사', icon: Clipboard },
      { id: 'process-inspection', label: '중간검사', icon: Clipboard },
      { id: 'product-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: Send },
    ]},
    { id: 'accounting', label: '회계관리', icon: CreditCard, subMenus: [
      { id: 'receivable', label: '거래처별채권', icon: Users },
      { id: 'collection', label: '수금관리', icon: DollarSign },
      { id: 'outstanding', label: '미수금관리', icon: AlertCircle },
    ]},
  ];

  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">
            <X className="w-5 h-5" />
          </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 => (
                    <button
                      key={sub.id}
                      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 className="w-4 h-4" />
                      {sub.label}
                    </button>
                  ))}
                </div>
              )}
            </div>
          ))}
        </nav>
      </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="grid grid-cols-2 gap-4 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>
          <p className="text-gray-500 mb-1">출고진행</p>
          <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: `${order.shipmentProgress || 0}%` }}
              />
            </div>
            <span className="text-xs text-gray-600">{order.shipmentProgress || 0}%</span>
          </div>
        </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 }) => (
  <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>
    {children}
    {hint && <p className="text-xs text-gray-500">{hint}</p>}
  </div>
);

// 텍스트 입력
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 }) => (
  <div className="flex items-center justify-between mb-6">
    <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 && <div className="flex items-center gap-2">{actions}</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 },
];

// 수식 카테고리 정의
const formulaCategories = [
  { id: 'basic-info', name: '기본정보', order: 1 },
  { id: 'production-size', name: '제작사이즈', order: 2 },
  { id: 'area', name: '면적', order: 3 },
  { id: 'motor-calc', name: '모터용량산출', order: 4 },
  { id: 'shaft', name: '감기샤프트', order: 5 },
  { id: 'bracket', name: '브라켓&받침용엥글', order: 6 },
  { id: 'guide-rail', name: '가이드레일', order: 7 },
  { id: 'guide-rail-type', name: '가이드레일설치유형', order: 8 },
  { id: 'shutter-box', name: '셔터박스', order: 9 },
  { id: 'bottom-finish', name: '하단마감재', order: 10 },
];

// 품목 수식 데이터
const initialQuoteFormulas = [
  // 기본정보 (10개)
  { id: 1, productId: 'common', categoryId: 'basic-info', order: 1, name: '제품 카테고리', variable: 'PC', type: 'input', formula: 'PC', resultType: 'item', description: 'Product Category', process: null },
  { id: 2, productId: 'common', categoryId: 'basic-info', order: 2, name: '오픈사이즈 가로', variable: 'W0', type: 'input', formula: 'W0', resultType: 'item', description: '고객 주문 가로 사이즈', process: null },
  { id: 3, productId: 'common', categoryId: 'basic-info', order: 3, name: '오픈사이즈 세로', variable: 'H0', type: 'input', formula: 'H0', resultType: 'item', description: '고객 주문 세로 사이즈', process: null },
  { id: 4, productId: 'common', categoryId: 'basic-info', order: 4, name: '가이드레일 유형', variable: 'GT', type: 'input', formula: 'GT', resultType: 'item', description: '가이드레일 설치 유형', process: null },
  { id: 5, productId: 'common', categoryId: 'basic-info', order: 5, name: '모터 전원', variable: 'MP', type: 'input', formula: 'MP', resultType: 'item', description: '모터 전원 타입', process: null },
  { id: 6, productId: 'common', categoryId: 'basic-info', order: 6, name: '연동제어기', variable: 'CT', type: 'input', formula: 'CT', resultType: 'item', description: '제어기 타입', process: null },
  { id: 7, productId: 'common', categoryId: 'basic-info', order: 7, name: '수량', variable: 'QTY', type: 'input', formula: 'QTY', resultType: 'item', description: '주문 수량', process: null },
  { id: 8, productId: 'common', categoryId: 'basic-info', order: 8, name: '마구리 날개치수', variable: 'WS', type: 'input', formula: 'WS', resultType: 'item', description: '', process: null },
  { id: 9, productId: 'common', categoryId: 'basic-info', order: 9, name: '검사비', variable: 'INSP', type: 'input', formula: 'INSP', resultType: 'item', description: '', process: null },
  { id: 10, productId: 'common', categoryId: 'basic-info', order: 10, name: '제품명', variable: '-', type: 'input', formula: '-', resultType: 'item', description: '제품 선택용 (변수 아님)', process: null },
  
  // 제작사이즈 (4개)
  { id: 11, productId: 'common', categoryId: 'production-size', order: 1, name: '스크린 가로', variable: 'W1_스크린', type: 'formula', formula: 'W0 + 140', resultType: 'item', description: '스크린 제작 가로 사이즈', process: '스크린' },
  { id: 12, productId: 'common', categoryId: 'production-size', order: 2, name: '스크린 세로', variable: 'H1_스크린', type: 'formula', formula: 'H0 + 350', resultType: 'item', description: '스크린 제작 세로 사이즈', process: '스크린' },
  { id: 13, productId: 'common', categoryId: 'production-size', order: 3, name: '철재 가로', variable: 'W1_철재', type: 'formula', formula: 'W0 + 110', resultType: 'item', description: '철재 제작 가로 사이즈', process: '절곡' },
  { id: 14, productId: 'common', categoryId: 'production-size', order: 4, name: '철재 세로', variable: 'H1_철재', type: 'formula', formula: 'H0 + 350', resultType: 'item', description: '철재 제작 세로 사이즈', process: '절곡' },
  
  // 면적 (1개)
  { id: 15, productId: 'common', categoryId: 'area', order: 1, name: '스크린 면적', variable: 'AREA', type: 'formula', formula: '(W1_스크린 * H1_스크린) / 1000000', resultType: 'item', description: '스크린 면적 (㎡)', process: '스크린' },
  
  // 모터용량산출 (2개)
  { id: 16, productId: 'common', categoryId: 'motor-calc', order: 1, name: '모터용량', variable: 'MOTOR_CAP', type: 'formula', formula: 'CEIL(AREA * 0.15)', resultType: 'item', description: '모터 용량 산출 (kW)', process: null },
  { id: 17, productId: 'common', categoryId: 'motor-calc', order: 2, name: '모터형번', variable: 'MOTOR_MODEL', type: 'lookup', formula: 'VLOOKUP(MOTOR_CAP, MOTOR_TABLE)', resultType: 'item', description: '모터 형번 선택', process: null },
  
  // 감기샤프트 (2개)
  { id: 18, productId: 'common', categoryId: 'shaft', order: 1, name: '샤프트 직경', variable: 'SHAFT_D', type: 'formula', formula: 'IF(W0 > 3000, 60, IF(W0 > 2000, 50, 40))', resultType: 'item', description: '샤프트 직경 (mm)', process: '절곡' },
  { id: 19, productId: 'common', categoryId: 'shaft', order: 2, name: '샤프트 길이', variable: 'SHAFT_L', type: 'formula', formula: 'W0 + 200', resultType: 'item', description: '샤프트 길이 (mm)', process: '절곡' },
  
  // 가이드레일 (2개)
  { id: 20, productId: 'common', categoryId: 'guide-rail', order: 1, name: '가이드레일 길이', variable: 'GR_L', type: 'formula', formula: 'H0 + 100', resultType: 'output', description: '가이드레일 길이', process: '절곡', itemCode: 'BP-GR-001', itemName: '가이드레일', unit: 'EA', qtyFormula: 'QTY * 2' },
  { id: 21, productId: 'common', categoryId: 'guide-rail', order: 2, name: '가이드레일 하부', variable: 'GR_BASE', type: 'formula', formula: 'W0 + 60', resultType: 'output', description: '가이드레일 하부 베이스', process: '절곡', itemCode: 'BP-GB-001', itemName: '하부베이스', unit: 'EA', qtyFormula: 'QTY * 2' },
  
  // 셔터박스 (3개)
  { id: 22, productId: 'common', categoryId: 'shutter-box', order: 1, name: '케이스 길이', variable: 'CASE_L', type: 'formula', formula: 'W0 + 100', resultType: 'output', description: '케이스 길이', process: '절곡', itemCode: 'BP-CS-001', itemName: '케이스', unit: 'EA', qtyFormula: 'QTY' },
  { id: 23, productId: 'common', categoryId: 'shutter-box', order: 2, name: '측면덮개', variable: 'SIDE_COVER', type: 'formula', formula: 'IF(GT == "백면", 2, 4)', resultType: 'output', description: '측면덮개 수량', process: '절곡', itemCode: 'BP-SC-001', itemName: '측면덮개', unit: 'EA', qtyFormula: 'SIDE_COVER * QTY' },
  { id: 24, productId: 'common', categoryId: 'shutter-box', order: 3, name: '상부덮개', variable: 'TOP_COVER', type: 'formula', formula: '1', resultType: 'output', description: '상부덮개', process: '절곡', itemCode: 'BP-TC-001', itemName: '상부덮개', unit: 'EA', qtyFormula: 'QTY' },
  
  // 하단마감재 (수식 추가)
  { id: 25, productId: 'common', categoryId: 'bottom-finish', order: 1, name: '하단마감재 길이', variable: 'BF_L', type: 'formula', formula: 'W0', resultType: 'output', description: '하단마감재', process: '절곡', itemCode: 'BP-BF-001', itemName: '하단마감재', unit: 'EA', qtyFormula: 'QTY' },
  { id: 26, productId: 'common', categoryId: 'bottom-finish', order: 2, name: '하단보강빔바', variable: 'BF_BEAM', type: 'formula', formula: 'W0', resultType: 'output', description: '하단보강빔바', process: '절곡', itemCode: 'BP-BB-001', itemName: '하단보강빔바', unit: 'EA', qtyFormula: 'QTY * 2' },
];

// 단가 계산 분류 (카테고리 그룹)
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' },
];

// 수식 계산 엔진
const formulaEngine = {
  // 변수 저장소
  variables: {},
  
  // 변수 설정
  setVariable(name, value) {
    this.variables[name] = value;
  },
  
  // 변수 가져오기
  getVariable(name) {
    return this.variables[name] || 0;
  },
  
  // 수식 평가
  evaluate(formula) {
    if (!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, 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;
    }
  },
  
  // 견적 품목 산출
  calculateQuoteItems(inputs, formulas, priceList) {
    // 입력값 설정
    this.variables = { ...inputs };
    
    // 수식 순서대로 실행
    const sortedFormulas = [...formulas].sort((a, b) => {
      const catA = formulaCategories.find(c => c.id === a.categoryId)?.order || 99;
      const catB = formulaCategories.find(c => c.id === b.categoryId)?.order || 99;
      if (catA !== catB) return catA - catB;
      return a.order - b.order;
    });
    
    const outputItems = [];
    
    for (const formula of sortedFormulas) {
      if (formula.type === 'formula' || formula.type === 'lookup') {
        const result = this.evaluate(formula.formula);
        this.setVariable(formula.variable, result);
        
        // 품목 출력인 경우
        if (formula.resultType === 'output' && formula.itemCode) {
          const qty = formula.qtyFormula ? this.evaluate(formula.qtyFormula) : 1;
          const price = priceList.find(p => p.itemCode === formula.itemCode)?.sellingPrice || 0;
          
          outputItems.push({
            id: Date.now() + outputItems.length,
            formulaId: formula.id,
            itemCode: formula.itemCode,
            itemName: formula.itemName,
            spec: `${result}mm`,
            length: result,
            qty: Math.ceil(qty),
            unit: formula.unit || 'EA',
            unitPrice: price,
            amount: Math.ceil(qty) * price,
            process: formula.process,
            category: formula.categoryId,
          });
        }
      }
    }
    
    return {
      variables: { ...this.variables },
      items: outputItems,
      totalAmount: outputItems.reduce((sum, item) => sum + item.amount, 0),
    };
  },
};

// ============ 공정 마스터 데이터 ============
const sampleProcesses = [
  {
    id: 1,
    processCode: 'P-001',
    processName: '스크린',
    processType: '생산',
    department: '스크린생산부서',
    standardTime: 120,
    processCost: 50000,
    equipment: '미싱기 3대, 절단기 1대',
    personnel: 3,
    workSheetType: '스크린형',
    sortOrder: 1,
    isActive: true,
    description: '방화스크린 원단 가공 및 조립',
    workSteps: ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'],
    createdAt: '2025-01-01',
    updatedAt: '2025-01-15',
  },
  {
    id: 2,
    processCode: 'P-002',
    processName: '절곡',
    processType: '생산',
    department: '절곡생산부서',
    standardTime: 180,
    processCost: 80000,
    equipment: '절곡기 2대, 용접기 1대',
    personnel: 4,
    workSheetType: '절곡형',
    sortOrder: 2,
    isActive: true,
    description: '가이드레일, 케이스, 하단마감재 제작',
    workSteps: ['가이드레일 제작', '케이스 제작', '하단마감재 제작', '검사'],
    createdAt: '2025-01-01',
    updatedAt: '2025-01-15',
  },
  {
    id: 3,
    processCode: 'P-003',
    processName: '슬랫',
    processType: '생산',
    department: '슬랫생산부서',
    standardTime: 150,
    processCost: 60000,
    equipment: '코일절단기 1대, 성형기 2대',
    personnel: 3,
    workSheetType: '슬랫형',
    sortOrder: 3,
    isActive: true,
    description: '슬랫 코일 절단 및 성형',
    workSteps: ['코일절단', '성형', '미미작업', '검사', '포장'],
    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 },
        ]},
      ],
    },
  },
};

// 수주 (로트번호 = 수주번호 = 모든 추적의 기준)
const initialOrders = [
  /*
   * ============================================================
   * 📋 수주 데이터 - 7개 테스트 시나리오
   * ============================================================
   * [1] KD-SO-250205-01 ← KD-PR-250201-01 (삼성건설 A등급) → 출하완료
   * [2] KD-SO-250208-01 ← KD-PR-250203-01 (현대개발 B등급) → 입금대기, 출고보류
   * [3] KD-SO-250210-01 ← KD-PR-250205-01 (한화시공 C등급) → 경리승인 대기
   * [4] KD-SO-250205-01-A ← KD-PR-250220-01 (삼성건설 추가분) → 생산중
   * [5] KD-SO-250212-01 ← KD-PR-250207-01 (부산건설 분할출하) → 분할 진행중
   * [6] KD-SO-250215-01 ← KD-PR-250210-01 (삼성건설 품질불량) → 재작업중
   * [7] KD-SO-250218-01 ← KD-PR-250215-01 (현대개발 할인적용) → 생산중
   * ============================================================
   */
  
  // ========== 시나리오 1: A등급 정상 플로우 (삼성건설) ==========
  {
    id: 1,
    orderNo: 'KD-SO-250205-01',
    lotNo: 'KD-SO-250205-01',
    orderDate: '2025-02-05',
    quoteId: 1,
    quoteNo: 'KD-PR-250201-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 1,
    customerName: '삼성건설(주)',
    creditGrade: 'A',
    siteName: '강남 타워 신축현장',
    siteCode: 'PJ-202502-001',
    manager: '이건설',
    contact: '010-1111-1111',
    dueDate: '2025-03-15',
    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-SO-250205-01-01',
        lotNo: 'KD-SO-250205-01',
        splitOrder: 1, 
        splitType: '일괄',
        itemIds: [1, 2], 
        dueDate: '2025-03-01', 
        productionStatus: '작업완료', 
        shipmentStatus: '출하완료',
        productionOrderNo: 'KD-PL-250207-01',
        totalQty: 2,
        completedQty: 2,
        remainingQty: 0,
      },
    ],
    documentHistory: [
      { id: 1, docType: '거래명세서', sentAt: '2025-02-05 15:00', sentBy: '영업팀', sentMethod: '이메일', recipient: 'samsung@samsung-const.co.kr', status: '발송완료' },
      { id: 2, docType: '세금계산서', sentAt: '2025-02-05 15:30', sentBy: '회계팀', sentMethod: '전자발행', recipient: '123-45-67890', status: '발행완료' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-02-05 14:00', changeType: '수주등록', description: 'A등급 거래처 - 자동 진행', changedBy: '영업팀 김영업' },
      { id: 2, changedAt: '2025-02-06 10:00', changeType: '회계확인', description: '전액 입금 확인', changedBy: '회계팀 박회계' },
      { id: 3, changedAt: '2025-03-01 16:00', changeType: '출하완료', description: '배송 완료', changedBy: '물류팀 박배송' },
    ],
    createdAt: '2025-02-05',
    createdBy: '영업팀 김영업',
    note: '[시나리오1] A등급 정상 플로우 - 자동 진행 완료',
  },
  
  // ========== 시나리오 2: B등급 입금 후 출고 (현대개발) ==========
  {
    id: 2,
    orderNo: 'KD-SO-250208-01',
    lotNo: 'KD-SO-250208-01',
    orderDate: '2025-02-08',
    quoteId: 2,
    quoteNo: 'KD-PR-250203-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 2,
    customerName: '현대개발(주)',
    creditGrade: 'B',
    siteName: '송도 오피스빌딩',
    siteCode: 'PJ-202502-002',
    manager: '최개발',
    contact: '010-2222-2222',
    dueDate: '2025-03-20',
    status: '생산완료',
    paymentStatus: '미입금',
    // 회계 상태 (B등급: 입금확인 후 출고)
    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: '인천시 연수구 송도동 200',
    receiverName: '최개발',
    receiverPhone: '010-2222-2222',
    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-SO-250208-01-01',
        lotNo: 'KD-SO-250208-01',
        splitOrder: 1, 
        splitType: '층별',
        itemIds: [1], 
        dueDate: '2025-03-15', 
        productionStatus: '작업완료', 
        shipmentStatus: '출고보류',  // ⚠️ 입금대기
        productionOrderNo: 'KD-PL-250210-01',
        totalQty: 2,
        completedQty: 2,
        remainingQty: 0,
      },
      { 
        id: 2, 
        splitNo: 'KD-SO-250208-01-02',
        lotNo: 'KD-SO-250208-01',
        splitOrder: 2, 
        splitType: '층별',
        itemIds: [2], 
        dueDate: '2025-03-20', 
        productionStatus: '작업완료', 
        shipmentStatus: '출고보류',  // ⚠️ 입금대기
        productionOrderNo: 'KD-PL-250212-01',
        totalQty: 2,
        completedQty: 2,
        remainingQty: 0,
      },
    ],
    documentHistory: [
      { id: 1, docType: '거래명세서', sentAt: '2025-02-08 14:00', sentBy: '영업팀', sentMethod: '이메일', status: '발송완료' },
      { id: 2, docType: '세금계산서', sentAt: '2025-02-08 14:30', sentBy: '회계팀', sentMethod: '전자발행', status: '발행완료' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-02-08 13:00', changeType: '수주등록', description: 'B등급 거래처 - 입금확인 후 출고 조건', changedBy: '영업팀 이영업' },
      { id: 2, changedAt: '2025-03-15 09:00', changeType: '생산완료', description: '전량 생산 완료, 출고 대기', changedBy: '생산팀 박생산' },
      { id: 3, changedAt: '2025-03-15 10:00', changeType: '출고보류', description: '입금 미확인으로 출고 보류', changedBy: '물류팀 김물류' },
    ],
    createdAt: '2025-02-08',
    createdBy: '영업팀 이영업',
    note: '[시나리오2] B등급 - 생산완료, 입금확인 대기 중 (출고보류)',
  },
  
  // ========== 시나리오 3: C등급 경리승인 후 생산 (한화시공) ==========
  {
    id: 3,
    orderNo: 'KD-SO-250210-01',
    lotNo: 'KD-SO-250210-01',
    orderDate: '2025-02-10',
    quoteId: 3,
    quoteNo: 'KD-PR-250205-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 3,
    customerName: '한화시공(주)',
    creditGrade: 'C',
    siteName: '둔산 상가 리모델링',
    siteCode: 'PJ-202502-003',
    manager: '강시공',
    contact: '010-3333-3333',
    dueDate: '2025-04-01',
    status: '수주확정',  // ⚠️ 아직 생산지시 안됨
    paymentStatus: '선입금대기',
    // 회계 상태 (C등급: 경리승인 필요)
    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: '대전시 서구 둔산동 300',
    receiverName: '강시공',
    receiverPhone: '010-3333-3333',
    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-02-10 14:00', changeType: '수주등록', description: 'C등급 거래처 - 경리승인 필요', changedBy: '영업팀 박영업' },
      { id: 2, changedAt: '2025-02-10 15:00', changeType: '승인요청', description: '경리팀에 생산 승인 요청', changedBy: '영업팀 박영업' },
      { id: 3, changedAt: '2025-02-11 09:00', changeType: '경리확인', description: '거래처 통화 - 선입금 50% 약속 확인', changedBy: '회계팀 김회계' },
    ],
    createdAt: '2025-02-10',
    createdBy: '영업팀 박영업',
    note: '[시나리오3] C등급 - 경리승인 대기 중 (생산보류)',
  },
  
  // ========== 시나리오 4: 추가분 수주 (삼성건설) ==========
  {
    id: 4,
    orderNo: 'KD-SO-250205-01-A',
    lotNo: 'KD-SO-250205-01-A',
    orderDate: '2025-02-20',
    quoteId: 4,
    quoteNo: 'KD-PR-250220-01',
    orderType: 'additional',  // 추가분
    parentLotNo: 'KD-SO-250205-01',  // 원 로트번호
    customerId: 1,
    customerName: '삼성건설(주)',
    creditGrade: 'A',
    siteName: '강남 타워 신축현장',
    siteCode: 'PJ-202502-001',
    manager: '이건설',
    contact: '010-1111-1111',
    dueDate: '2025-03-30',
    status: '생산중',
    paymentStatus: '계약금입금',
    accountingStatus: '입금확인',
    accountingConfirmedBy: '회계팀 박회계',
    accountingConfirmedAt: '2025-02-21 10:00',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    invoiceIssuedAt: '2025-02-20 16:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-02-20 16:30',
    totalAmount: 12000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 12000000,
    paidAmount: 6000000,
    remainingAmount: 6000000,
    deliveryMethod: '상차',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    receiverName: '이건설',
    receiverPhone: '010-1111-1111',
    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-SO-250205-01-A-01',
        lotNo: 'KD-SO-250205-01-A',
        splitOrder: 1, 
        splitType: '일괄',
        itemIds: [1], 
        dueDate: '2025-03-25', 
        productionStatus: '작업중', 
        shipmentStatus: '대기',
        productionOrderNo: 'KD-PL-250222-01',
        totalQty: 3,
        completedQty: 1,
        remainingQty: 2,
      },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-02-20 15:00', changeType: '추가분등록', description: '원 수주 KD-SO-250205-01의 3층 추가분', changedBy: '영업팀 김영업' },
      { id: 2, changedAt: '2025-02-22 09:00', changeType: '생산지시', description: '생산지시 완료', changedBy: '영업팀 김영업' },
    ],
    createdAt: '2025-02-20',
    createdBy: '영업팀 김영업',
    note: '[시나리오4] 추가분 수주 - 기존 현장 3층 추가',
  },
  
  // ========== 시나리오 5: 분할 출하 (부산건설) ==========
  {
    id: 5,
    orderNo: 'KD-SO-250212-01',
    lotNo: 'KD-SO-250212-01',
    orderDate: '2025-02-12',
    quoteId: 5,
    quoteNo: 'KD-PR-250207-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 4,
    customerName: '부산건설(주)',
    creditGrade: 'A',
    siteName: '해운대 타워',
    siteCode: 'PJ-202502-004',
    manager: '박해운',
    contact: '010-4444-4444',
    dueDate: '2025-03-25',
    status: '생산완료',
    paymentStatus: '전액입금',
    accountingStatus: '회계확인완료',
    accountingConfirmedBy: '회계팀 박회계',
    accountingConfirmedAt: '2025-02-13 10:00',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    invoiceIssuedAt: '2025-02-12 15:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-02-12 15:30',
    totalAmount: 35000000,
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 35000000,
    paidAmount: 35000000,
    remainingAmount: 0,
    deliveryMethod: '직접배차',
    deliveryAddress: '부산시 해운대구 우동 400',
    receiverName: '박해운',
    receiverPhone: '010-4444-4444',
    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-SO-250212-01-01',
        lotNo: 'KD-SO-250212-01',
        splitOrder: 1, 
        splitType: '층별',
        itemIds: [1], 
        dueDate: '2025-03-15',  // 1차 출고일
        productionStatus: '작업완료', 
        shipmentStatus: '배송완료',
        productionOrderNo: 'KD-PL-250215-01',
        totalQty: 3,
        completedQty: 3,
        remainingQty: 0,
      },
      { 
        id: 2, 
        splitNo: 'KD-SO-250212-01-02',
        lotNo: 'KD-SO-250212-01',
        splitOrder: 2, 
        splitType: '층별',
        itemIds: [2], 
        dueDate: '2025-03-25',  // 2차 출고일 (다른 날짜)
        productionStatus: '작업완료', 
        shipmentStatus: '출하준비',
        productionOrderNo: 'KD-PL-250217-01',
        totalQty: 2,
        completedQty: 2,
        remainingQty: 0,
      },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-02-12 14:00', changeType: '수주등록', description: '분할 출하 설정 - 1차 3/15, 2차 3/25', changedBy: '영업팀 최영업' },
      { id: 2, changedAt: '2025-03-15 16:00', changeType: '1차출하', description: '1층 스크린 셔터 출하 완료', changedBy: '물류팀 박배송' },
    ],
    createdAt: '2025-02-12',
    createdBy: '영업팀 최영업',
    note: '[시나리오5] 분할 출하 - 1차 완료, 2차 대기',
  },
  
  // ========== 시나리오 6: 품질 불량 (삼성건설) ==========
  {
    id: 6,
    orderNo: 'KD-SO-250215-01',
    lotNo: 'KD-SO-250215-01',
    orderDate: '2025-02-15',
    quoteId: 6,
    quoteNo: 'KD-PR-250210-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 1,
    customerName: '삼성건설(주)',
    creditGrade: 'A',
    siteName: '강남 타워 신축현장 (B동)',
    siteCode: 'PJ-202502-005',
    manager: '이건설',
    contact: '010-1111-1111',
    dueDate: '2025-03-20',
    status: '생산중',
    paymentStatus: '계약금입금',
    accountingStatus: '입금확인',
    accountingConfirmedBy: '회계팀 박회계',
    accountingConfirmedAt: '2025-02-16 10:00',
    requireApproval: false,
    requirePaymentBeforeShip: false,
    invoiceIssued: true,
    invoiceIssuedAt: '2025-02-15 15:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-02-15 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-SO-250215-01-01',
        lotNo: 'KD-SO-250215-01',
        splitOrder: 1, 
        splitType: '일괄',
        itemIds: [1], 
        dueDate: '2025-03-15', 
        productionStatus: '재작업중',  // ⚠️ 품질불량으로 재작업
        shipmentStatus: '대기',
        productionOrderNo: 'KD-PL-250218-01',
        totalQty: 4,
        completedQty: 2,
        remainingQty: 2,
        qualityIssue: true,
        qualityIssueNote: '중간검사 불합격 - 치수불량 2EA 재작업',
      },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-02-15 14:00', changeType: '수주등록', description: 'B동 슬랫 셔터', changedBy: '영업팀 김영업' },
      { id: 2, changedAt: '2025-02-18 14:00', changeType: '품질불량', description: '중간검사 불합격 - 치수불량 2EA', changedBy: '품질팀 이검사' },
      { id: 3, changedAt: '2025-02-19 09:00', changeType: '재작업지시', description: '불량 2EA 재작업 지시', changedBy: '생산팀 박생산' },
    ],
    createdAt: '2025-02-15',
    createdBy: '영업팀 김영업',
    note: '[시나리오6] 품질 불량 - 중간검사 불합격, 재작업 진행 중',
  },
  
  // ========== 시나리오 7: 할인 적용 (현대개발) ==========
  {
    id: 7,
    orderNo: 'KD-SO-250218-01',
    lotNo: 'KD-SO-250218-01',
    orderDate: '2025-02-18',
    quoteId: 7,
    quoteNo: 'KD-PR-250215-01',
    orderType: 'initial',
    parentLotNo: null,
    customerId: 2,
    customerName: '현대개발(주)',
    creditGrade: 'B',
    siteName: '연수 오피스텔',
    siteCode: 'PJ-202502-006',
    manager: '최개발',
    contact: '010-2222-2222',
    dueDate: '2025-04-10',
    status: '생산중',
    paymentStatus: '미입금',
    accountingStatus: '세금계산서발행',
    accountingConfirmedBy: null,
    accountingConfirmedAt: null,
    requireApproval: false,
    requirePaymentBeforeShip: true,
    invoiceIssued: true,
    invoiceIssuedAt: '2025-02-18 15:00',
    taxInvoiceIssued: true,
    taxInvoiceIssuedAt: '2025-02-18 15:30',
    // 할인 적용
    totalAmount: 30000000,
    discountRate: 10,
    discountAmount: 3000000,
    finalAmount: 27000000,  // 할인 후 금액
    paidAmount: 0,
    remainingAmount: 27000000,
    deliveryMethod: '직접배차',
    deliveryAddress: '인천시 연수구 동춘동 500',
    receiverName: '최개발',
    receiverPhone: '010-2222-2222',
    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-SO-250218-01-01',
        lotNo: 'KD-SO-250218-01',
        splitOrder: 1, 
        splitType: '일괄',
        itemIds: [1], 
        dueDate: '2025-04-05', 
        productionStatus: '작업중', 
        shipmentStatus: '대기',
        productionOrderNo: 'KD-PL-250220-01',
        totalQty: 6,
        completedQty: 2,
        remainingQty: 4,
      },
    ],
    documentHistory: [
      { id: 1, docType: '거래명세서', sentAt: '2025-02-18 15:00', sentBy: '영업팀', sentMethod: '이메일', status: '발송완료', note: '할인 10% 적용' },
      { id: 2, docType: '세금계산서', sentAt: '2025-02-18 15:30', sentBy: '회계팀', sentMethod: '전자발행', status: '발행완료', note: '공급가액 24,545,455원' },
    ],
    changeHistory: [
      { id: 1, changedAt: '2025-02-18 14:00', changeType: '수주등록', description: 'B등급 거래처 - 대량 주문 10% 할인 적용', changedBy: '영업팀 이영업' },
      { id: 2, changedAt: '2025-02-18 14:30', changeType: '할인적용', description: '할인 10% (3,000,000원) 적용', changedBy: '회계팀 김회계' },
    ],
    createdAt: '2025-02-18',
    createdBy: '영업팀 이영업',
    note: '[시나리오7] 할인 적용 - 대량 주문 10% 할인',
  },

  // ========== 시나리오 8: 발주서 양식 테스트 (용산고등학교) ==========
  {
    id: 8,
    orderNo: 'KD-WE-251015-01',
    lotNo: 'KD-WE-251015-01',
    orderDate: '2025-10-15',
    quoteId: null,
    quoteNo: null,
    orderType: 'direct',
    parentLotNo: null,
    customerId: null,
    customerName: '주말건설',
    creditGrade: 'B',
    siteName: '용산고등학교(4층)',
    siteCode: 'PJ-202510-001',
    manager: '김명현과장',
    contact: '010-6414-7929',
    dueDate: '2025-10-30',
    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-WE-251015-01-01',
        lotNo: 'KD-WE-251015-01',
        splitOrder: 1, 
        splitType: '일괄',
        itemIds: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 
        dueDate: '2025-10-30', 
        productionStatus: '작업대기', 
        shipmentStatus: '미출고',
        productionOrderNo: 'KD-PL-251016-01',
        totalQty: 11,
        completedQty: 0,
        remainingQty: 11,
      },
    ],
    documentHistory: [],
    changeHistory: [
      { id: 1, changedAt: '2025-10-15 09:00', changeType: '수주등록', description: '용산고등학교 4층 방화셔터 11개소', changedBy: '영업팀 김영업' },
      { id: 2, changedAt: '2025-10-16 10:00', changeType: '생산지시', description: '전체 일괄 생산지시', changedBy: '생산팀 박생산' },
    ],
    createdAt: '2025-10-15',
    createdBy: '영업팀 김영업',
    note: '[시나리오8] 발주서 양식 테스트 - 용산고등학교 4층 방화셔터 11개소',
  },
];

// 작업지시
const initialWorkOrders = [
  /*
   * ============================================================
   * 📋 생산 데이터 - 7개 테스트 시나리오 연동
   * ============================================================
   * [1] KD-PL-250207-01 ← KD-SO-250205-01-01 (시나리오1: 삼성건설 A) → 작업완료 ✅
   * [2] KD-PL-250210-01 ← KD-SO-250208-01-01 (시나리오2: 현대개발 B 스크린) → 작업완료
   * [3] KD-PL-250212-01 ← KD-SO-250208-01-02 (시나리오2: 현대개발 B 슬랫) → 작업완료
   * [4] KD-PL-250222-01 ← KD-SO-250205-01-A-01 (시나리오4: 삼성건설 추가분) → 작업중
   * [5] KD-PL-250215-01 ← KD-SO-250212-01-01 (시나리오5: 부산건설 1차) → 작업완료 ✅
   * [6] KD-PL-250217-01 ← KD-SO-250212-01-02 (시나리오5: 부산건설 2차) → 작업완료
   * [7] KD-PL-250218-01 ← KD-SO-250215-01-01 (시나리오6: 품질불량) → 재작업중 ⚠️
   * [8] KD-PL-250220-01 ← KD-SO-250218-01-01 (시나리오7: 할인적용) → 작업중
   * 
   * ※ 시나리오3 (한화시공 C등급)은 경리승인 대기로 생산 미시작
   * ============================================================
   */
  
  // ========== 시나리오 1: A등급 정상 플로우 (삼성건설) - 작업완료 ==========
  {
    id: 1,
    workOrderNo: 'KD-PL-250207-01',
    orderNo: 'KD-SO-250205-01',
    splitNo: 'KD-SO-250205-01-01',
    orderDate: '2025-02-07',
    processType: '스크린',
    customerName: '삼성건설(주)',
    siteName: '강남 타워 신축현장',
    dueDate: '2025-03-01',
    status: '작업완료',
    priority: '긴급',
    assignee: '김작업',
    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: '생산팀 박생산',
  },
  
  // ========== 시나리오 2: B등급 입금 후 출고 (현대개발) - 스크린 작업완료 ==========
  {
    id: 2,
    workOrderNo: 'KD-PL-250210-01',
    orderNo: 'KD-SO-250208-01',
    splitNo: 'KD-SO-250208-01-01',
    orderDate: '2025-02-10',
    processType: '스크린',
    customerName: '현대개발(주)',
    siteName: '송도 오피스빌딩',
    dueDate: '2025-03-15',
    status: '작업완료',
    priority: '일반',
    assignee: '이작업',
    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: '생산팀 박생산',
  },
  
  // ========== 시나리오 2: B등급 입금 후 출고 (현대개발) - 슬랫 작업완료 ==========
  {
    id: 3,
    workOrderNo: 'KD-PL-250212-01',
    orderNo: 'KD-SO-250208-01',
    splitNo: 'KD-SO-250208-01-02',
    orderDate: '2025-02-12',
    processType: '슬랫',
    customerName: '현대개발(주)',
    siteName: '송도 오피스빌딩',
    dueDate: '2025-03-20',
    status: '작업완료',
    priority: '일반',
    assignee: '박작업',
    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: '생산팀 박생산',
  },
  
  // ========== 시나리오 4: 추가분 수주 (삼성건설) - 작업중 ==========
  {
    id: 4,
    workOrderNo: 'KD-PL-250222-01',
    orderNo: 'KD-SO-250205-01-A',
    splitNo: 'KD-SO-250205-01-A-01',
    orderDate: '2025-02-22',
    processType: '스크린',
    customerName: '삼성건설(주)',
    siteName: '강남 타워 신축현장',
    dueDate: '2025-03-25',
    status: '작업중',
    priority: '일반',
    assignee: '김작업',
    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: '생산팀 박생산',
  },
  
  // ========== 시나리오 5: 분할 출하 (부산건설) - 1차분 작업완료 ==========
  {
    id: 5,
    workOrderNo: 'KD-PL-250215-01',
    orderNo: 'KD-SO-250212-01',
    splitNo: 'KD-SO-250212-01-01',
    orderDate: '2025-02-15',
    processType: '스크린',
    customerName: '부산건설(주)',
    siteName: '해운대 타워',
    dueDate: '2025-03-15',
    status: '작업완료',
    priority: '긴급',
    assignee: '이작업',
    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: '생산팀 박생산',
  },
  
  // ========== 시나리오 5: 분할 출하 (부산건설) - 2차분 작업완료 ==========
  {
    id: 6,
    workOrderNo: 'KD-PL-250217-01',
    orderNo: 'KD-SO-250212-01',
    splitNo: 'KD-SO-250212-01-02',
    orderDate: '2025-02-17',
    processType: '슬랫',
    customerName: '부산건설(주)',
    siteName: '해운대 타워',
    dueDate: '2025-03-25',
    status: '작업완료',
    priority: '일반',
    assignee: '박작업',
    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: '생산팀 박생산',
  },
  
  // ========== 시나리오 6: 품질 불량 (삼성건설) - 재작업중 ⚠️ ==========
  {
    id: 7,
    workOrderNo: 'KD-PL-250218-01',
    orderNo: 'KD-SO-250215-01',
    splitNo: 'KD-SO-250215-01-01',
    orderDate: '2025-02-18',
    processType: '슬랫',
    customerName: '삼성건설(주)',
    siteName: '강남 타워 신축현장 (B동)',
    dueDate: '2025-03-15',
    status: '재작업중',
    priority: '긴급',
    assignee: '박작업',
    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: '생산팀 박생산',
  },
  
  // ========== 시나리오 7: 할인 적용 (현대개발) - 작업중 ==========
  {
    id: 8,
    workOrderNo: 'KD-PL-250220-01',
    orderNo: 'KD-SO-250218-01',
    splitNo: 'KD-SO-250218-01-01',
    orderDate: '2025-02-20',
    processType: '스크린',
    customerName: '현대개발(주)',
    siteName: '연수 오피스텔',
    dueDate: '2025-04-05',
    status: '작업중',
    priority: '일반',
    assignee: '이작업',
    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: '생산팀 박생산',
  },

  // ========== 시나리오 8: 발주서 양식 테스트 (용산고등학교) - 작업대기 ==========
  {
    id: 9,
    workOrderNo: 'KD-PL-251016-01',
    orderNo: 'KD-WE-251015-01',
    splitNo: 'KD-WE-251015-01-01',
    orderDate: '2025-10-16',
    processType: '스크린',
    customerName: '주말건설',
    siteName: '용산고등학교(4층)',
    dueDate: '2025-10-30',
    status: '작업대기',
    priority: '일반',
    assignee: null,
    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: '생산팀 박생산',
  },
]; 
// 공정별 작업단계 정의
const processSteps = {
  '스크린': ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'],
  '슬랫': ['코일절단', '중간검사', '미미작업', '포장'],
  '절곡': ['절단', '절곡', '중간검사', '포장'],
};

// 이슈 유형
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',
  },
];

// 출하 (출하번호는 별도로 관리하지 않음 - 수주분할번호로 식별)
const initialShipments = [
  /*
   * ============================================================
   * 📋 출하 데이터 (수주 분할과 연동)
   * ============================================================
   * [1] KD-SO-250115-01-01 (서울 1차분) → 배송완료 ✓
   * [2] KD-SO-250115-01-02 (서울 2차분) → 출고지시 (생산중)
   *     → 서울건축 출하진행률: 50% (1/2 완료)
   * 
   * [3] KD-SO-250118-01-01 (인천 1차분) → 배송완료 ✓
   * [4] KD-SO-250118-01-02 (인천 2차분) → 배송완료 ✓
   *     → 인천건설 출하진행률: 100% (2/2 완료)
   * 
   * [5] KD-SO-250115-01-A-01 (서울 추가분) → 출하준비
   *     → 서울건축 추가분 출하진행률: 0% (0/1 완료)
   * ============================================================
   */
  {
    id: 1,
    // shipmentNo 없음: 분할번호(splitNo)로 출하 식별
    shipmentDate: '2025-02-15',
    lotNo: 'KD-SO-250115-01',         // 로트번호 (추적 기준)
    splitNo: 'KD-SO-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,
    shipmentDate: '2025-02-18',
    lotNo: 'KD-SO-250115-01',
    splitNo: 'KD-SO-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-SO-250118-01 출하 (100% 완료)
  {
    id: 3,
    shipmentDate: '2025-02-20',
    lotNo: 'KD-SO-250118-01',
    splitNo: 'KD-SO-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,
    shipmentDate: '2025-03-01',
    lotNo: 'KD-SO-250118-01',
    splitNo: 'KD-SO-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-SO-250115-01-A 출하 (0% - 출하준비)
  {
    id: 5,
    shipmentDate: '2025-03-20',
    lotNo: 'KD-SO-250115-01-A',
    splitNo: 'KD-SO-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: '추가분 출하 예정',
  },
];

// 품질검사 (제품검사)
// 제품검사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-SO-250115-01',         // 로트번호 (추적 기준)
    splitNo: 'KD-SO-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-SO-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: '품질팀 최품질',
  },
];

// ============ 거래처 관리 샘플 데이터 ============
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: '공급업체',
    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: 'SS-GN-001',
    siteName: '강남 더리버 아파트 신축현장',
    customerId: 'CUS-001',
    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: 'HD-JG-001',
    siteName: '중구 을지타워 리모델링현장',
    customerId: 'CUS-002',
    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: 'BS-HU-001',
    siteName: '해운대 마린시티 오피스텔',
    customerId: 'CUS-004',
    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: 'CUS-001',
    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: 'CUS-001',
    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: 'CUS-002',
    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: '시스템',
  },
];

// ============ 견적 관리 ============

// 견적 샘플 데이터
const sampleQuotesData = [
  /*
   * ============================================================
   * 📋 테스트 시나리오 (견적 → 수주 → 생산 → 출하 → 회계)
   * ============================================================
   * 
   * [시나리오 1] A등급 정상 플로우 - 삼성건설
   *   견적: KD-PR-250201-01 → 수주: KD-SO-250205-01 → 출하완료
   * 
   * [시나리오 2] B등급 입금 후 출고 - 현대개발
   *   견적: KD-PR-250203-01 → 수주: KD-SO-250208-01 → 입금대기
   * 
   * [시나리오 3] C등급 경리승인 후 생산 - 한화시공
   *   견적: KD-PR-250205-01 → 수주: KD-SO-250210-01 → 경리승인 대기
   * 
   * [시나리오 4] 추가분 수주 - 삼성건설
   *   견적: KD-PR-250220-01 → 수주: KD-SO-250205-01-A → 생산중
   * 
   * [시나리오 5] 분할 출하 (다른 출고일) - 부산건설
   *   견적: KD-PR-250207-01 → 수주: KD-SO-250212-01 → 분할출하
   * 
   * [시나리오 6] 품질 불량 (중간검사 불합격) - 삼성건설
   *   견적: KD-PR-250210-01 → 수주: KD-SO-250215-01 → 재작업
   * 
   * [시나리오 7] 할인 적용 - 현대개발
   *   견적: KD-PR-250215-01 → 수주: KD-SO-250218-01 → 할인10%
   * 
   * ============================================================
   */
  
  // ========== 시나리오 1: A등급 정상 플로우 (삼성건설) ==========
  { 
    id: 1, 
    quoteNo: 'KD-PR-250201-01', 
    quoteDate: '2025-02-01', 
    status: '수주전환',
    productName: '스크린 셔터',
    productCode: 'SCR-001',
    qty: 2,
    totalAmount: 52000000,
    customerId: 1,
    customerName: '삼성건설(주)',
    creditGrade: 'A',
    siteName: '강남 타워 신축현장',
    siteCode: 'PJ-202502-001',
    manager: '이건설',
    contact: '010-1111-1111',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    dueDate: '2025-03-15',
    createdBy: '영업1팀 김영업',
    note: '[시나리오1] A등급 정상 플로우 - 자동 진행',
    relatedOrders: ['KD-SO-250205-01'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 52000000,
    items: [
      { id: 1, floor: '1층', location: 'A-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 7660, height: 2550, guideType: '일반', motorPower: '220V', controller: '없음', qty: 1, wingIndex: 50, inspectionFee: 50000, unitPrice: 35000000, amount: 35000000, orderStatus: 'ordered', orderId: 1 },
      { id: 2, floor: '1층', location: 'A-02', category: '스크린', productName: '스크린 셔터 (표준형)', width: 6500, height: 2400, guideType: '일반', motorPower: '220V', controller: '없음', qty: 1, wingIndex: 50, inspectionFee: 50000, unitPrice: 17000000, amount: 17000000, orderStatus: 'ordered', orderId: 1 },
    ]
  },
  
  // ========== 시나리오 2: B등급 입금 후 출고 (현대개발) ==========
  { 
    id: 2, 
    quoteNo: 'KD-PR-250203-01', 
    quoteDate: '2025-02-03', 
    status: '수주전환',
    productName: '스크린/슬랫 셔터',
    productCode: 'SCR-001',
    qty: 4,
    totalAmount: 28000000,
    customerId: 2,
    customerName: '현대개발(주)',
    creditGrade: 'B',
    siteName: '송도 오피스빌딩',
    siteCode: 'PJ-202502-002',
    manager: '최개발',
    contact: '010-2222-2222',
    deliveryAddress: '인천시 연수구 송도동 200',
    dueDate: '2025-03-20',
    createdBy: '영업1팀 이영업',
    note: '[시나리오2] B등급 - 입금확인 후 출고',
    relatedOrders: ['KD-SO-250208-01'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 28000000,
    items: [
      { id: 1, floor: 'B1', location: 'C-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 6000, height: 2400, guideType: '일반', motorPower: '220V', controller: '없음', qty: 2, wingIndex: 50, inspectionFee: 50000, unitPrice: 8000000, amount: 16000000, orderStatus: 'ordered', orderId: 2 },
      { id: 2, floor: '1층', location: 'D-01', category: '슬랫', productName: '슬랫 셔터', width: 4500, height: 2000, guideType: '일반', motorPower: '220V', controller: '없음', qty: 2, wingIndex: 45, inspectionFee: 50000, unitPrice: 6000000, amount: 12000000, orderStatus: 'ordered', orderId: 2 }
    ]
  },
  
  // ========== 시나리오 3: C등급 경리승인 후 생산 (한화시공) ==========
  { 
    id: 3, 
    quoteNo: 'KD-PR-250205-01', 
    quoteDate: '2025-02-05', 
    status: '수주전환',
    productName: '슬랫 셔터',
    productCode: 'SLT-001',
    qty: 6,
    totalAmount: 18000000,
    customerId: 3,
    customerName: '한화시공(주)',
    creditGrade: 'C',
    siteName: '둔산 상가 리모델링',
    siteCode: 'PJ-202502-003',
    manager: '강시공',
    contact: '010-3333-3333',
    deliveryAddress: '대전시 서구 둔산동 300',
    dueDate: '2025-04-01',
    createdBy: '영업2팀 박영업',
    note: '[시나리오3] C등급 - 경리승인 후 생산, 입금확인 후 출고',
    relatedOrders: ['KD-SO-250210-01'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 18000000,
    items: [
      { id: 1, floor: '1층', location: 'G-01', category: '슬랫', productName: '슬랫 셔터', width: 4000, height: 2000, guideType: '일반', motorPower: '220V', controller: '없음', qty: 6, wingIndex: 45, inspectionFee: 50000, unitPrice: 3000000, amount: 18000000, orderStatus: 'ordered', orderId: 3 }
    ]
  },
  
  // ========== 시나리오 4: 추가분 수주 (삼성건설) ==========
  { 
    id: 4, 
    quoteNo: 'KD-PR-250220-01', 
    quoteDate: '2025-02-20', 
    status: '수주전환',
    productName: '스크린 셔터 (프리미엄)',
    productCode: 'SCR-002',
    qty: 3,
    totalAmount: 12000000,
    customerId: 1,
    customerName: '삼성건설(주)',
    creditGrade: 'A',
    siteName: '강남 타워 신축현장',
    siteCode: 'PJ-202502-001',
    manager: '이건설',
    contact: '010-1111-1111',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    dueDate: '2025-03-30',
    createdBy: '영업1팀 김영업',
    note: '[시나리오4] 추가분 수주 - 기존 현장 3층 추가',
    relatedOrders: ['KD-SO-250205-01-A'],
    parentQuoteNo: 'KD-PR-250201-01',
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 12000000,
    items: [
      { id: 1, floor: '3층', location: 'C-01', category: '스크린', productName: '스크린 셔터 (프리미엄)', width: 8000, height: 2800, guideType: '일반', motorPower: '220V', controller: '리모컨', qty: 3, wingIndex: 55, inspectionFee: 50000, unitPrice: 4000000, amount: 12000000, orderStatus: 'ordered', orderId: 4 }
    ]
  },
  
  // ========== 시나리오 5: 분할 출하 (부산건설) ==========
  { 
    id: 5, 
    quoteNo: 'KD-PR-250207-01', 
    quoteDate: '2025-02-07', 
    status: '수주전환',
    productName: '스크린/슬랫 셔터',
    productCode: 'SCR-001',
    qty: 5,
    totalAmount: 35000000,
    customerId: 4,
    customerName: '부산건설(주)',
    creditGrade: 'A',
    siteName: '해운대 타워',
    siteCode: 'PJ-202502-004',
    manager: '박해운',
    contact: '010-4444-4444',
    deliveryAddress: '부산시 해운대구 우동 400',
    dueDate: '2025-03-25',
    createdBy: '영업2팀 최영업',
    note: '[시나리오5] 분할 출하 - 1차 3/15, 2차 3/25',
    relatedOrders: ['KD-SO-250212-01'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 35000000,
    items: [
      { id: 1, floor: '1층', location: 'E-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 7000, height: 2500, guideType: '일반', motorPower: '220V', controller: '없음', qty: 3, wingIndex: 50, inspectionFee: 50000, unitPrice: 8000000, amount: 24000000, orderStatus: 'ordered', orderId: 5 },
      { id: 2, floor: '2층', location: 'F-01', category: '슬랫', productName: '슬랫 셔터', width: 5000, height: 2200, guideType: '일반', motorPower: '220V', controller: '없음', qty: 2, wingIndex: 45, inspectionFee: 50000, unitPrice: 5500000, amount: 11000000, orderStatus: 'ordered', orderId: 5 }
    ]
  },
  
  // ========== 시나리오 6: 품질 불량 (삼성건설) ==========
  { 
    id: 6, 
    quoteNo: 'KD-PR-250210-01', 
    quoteDate: '2025-02-10', 
    status: '수주전환',
    productName: '슬랫 셔터',
    productCode: 'SLT-001',
    qty: 4,
    totalAmount: 16000000,
    customerId: 1,
    customerName: '삼성건설(주)',
    creditGrade: 'A',
    siteName: '강남 타워 신축현장 (B동)',
    siteCode: 'PJ-202502-005',
    manager: '이건설',
    contact: '010-1111-1111',
    deliveryAddress: '서울시 강남구 테헤란로 100',
    dueDate: '2025-03-20',
    createdBy: '영업1팀 김영업',
    note: '[시나리오6] 품질 불량 - 중간검사 불합격 → 재작업',
    relatedOrders: ['KD-SO-250215-01'],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 16000000,
    items: [
      { id: 1, floor: '1층', location: 'H-01', category: '슬랫', productName: '슬랫 셔터', width: 4500, height: 2000, guideType: '일반', motorPower: '220V', controller: '없음', qty: 4, wingIndex: 45, inspectionFee: 50000, unitPrice: 4000000, amount: 16000000, orderStatus: 'ordered', orderId: 6 }
    ]
  },
  
  // ========== 시나리오 7: 할인 적용 (현대개발) ==========
  { 
    id: 7, 
    quoteNo: 'KD-PR-250215-01', 
    quoteDate: '2025-02-15', 
    status: '수주전환',
    productName: '스크린 셔터',
    productCode: 'SCR-001',
    qty: 6,
    totalAmount: 30000000,
    customerId: 2,
    customerName: '현대개발(주)',
    creditGrade: 'B',
    siteName: '연수 오피스텔',
    siteCode: 'PJ-202502-006',
    manager: '최개발',
    contact: '010-2222-2222',
    deliveryAddress: '인천시 연수구 동춘동 500',
    dueDate: '2025-04-10',
    createdBy: '영업1팀 이영업',
    note: '[시나리오7] 할인 적용 - 대량 주문 10% 할인',
    relatedOrders: ['KD-SO-250218-01'],
    discountRate: 10,
    discountAmount: 3000000,
    finalAmount: 27000000,
    items: [
      { id: 1, floor: '1층', location: 'I-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 6000, height: 2400, guideType: '일반', motorPower: '220V', controller: '없음', qty: 6, wingIndex: 50, inspectionFee: 50000, unitPrice: 5000000, amount: 30000000, orderStatus: 'ordered', orderId: 7 }
    ]
  },
  
  // ========== 견적 대기 (수주전환 전) ==========
  { 
    id: 8, 
    quoteNo: 'KD-PR-250225-01', 
    quoteDate: '2025-02-25', 
    status: '최종확정',
    productName: '스크린 셔터',
    productCode: 'SCR-001',
    qty: 10,
    totalAmount: 45000000,
    customerId: 4,
    customerName: '부산건설(주)',
    creditGrade: 'A',
    siteName: '해운대 주상복합',
    siteCode: 'PJ-202502-007',
    manager: '박해운',
    contact: '010-4444-4444',
    deliveryAddress: '부산시 해운대구 우동 450',
    dueDate: '2025-04-30',
    createdBy: '영업2팀 최영업',
    note: '수주전환 대기 - 발주처 최종 확인 중',
    relatedOrders: [],
    discountRate: 0,
    discountAmount: 0,
    finalAmount: 45000000,
    items: [
      { id: 1, floor: '1층', location: 'J-01', category: '스크린', productName: '스크린 셔터 (표준형)', width: 5500, height: 2300, guideType: '일반', motorPower: '220V', controller: '없음', qty: 10, wingIndex: 50, inspectionFee: 50000, unitPrice: 4500000, amount: 45000000, orderStatus: 'pending', orderId: null }
    ]
  },
  
  // ========== 테스트용: 스크린+슬랫 혼합 견적 ==========
  { 
    id: 9, 
    quoteNo: 'KD-PR-250301-01', 
    quoteDate: '2025-03-01', 
    status: '최종확정',
    productName: '스크린/슬랫 셔터',
    productCode: 'MIX-001',
    qty: 5,
    totalAmount: 32000000,
    customerId: 2,
    customerName: '현대개발(주)',
    creditGrade: 'B',
    siteName: '판교 테크노밸리 신축',
    siteCode: 'PJ-202503-001',
    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 }
    ]
  },
];

// ============ 거래처 관리 ============

// 신용등급 배지 컴포넌트
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 [showForm, setShowForm] = useState(false);
  const [editingProcess, setEditingProcess] = useState(null);
  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())
    );

  const handleCreate = () => {
    setEditingProcess(null);
    setShowForm(true);
  };

  const handleEdit = (process) => {
    setEditingProcess(process);
    setShowForm(true);
  };

  const handleSave = (formData) => {
    if (editingProcess) {
      // 수정
      setProcessList(prev => prev.map(p => 
        p.id === editingProcess.id ? { ...p, ...formData, updatedAt: new Date().toISOString().split('T')[0] } : p
      ));
    } else {
      // 신규 등록
      const newCode = `P-${String(processList.length + 1).padStart(3, '0')}`;
      const newProcess = {
        id: processList.length + 1,
        processCode: newCode,
        ...formData,
        createdAt: new Date().toISOString().split('T')[0],
        updatedAt: new Date().toISOString().split('T')[0],
      };
      setProcessList(prev => [...prev, newProcess]);
    }
    setShowForm(false);
    setEditingProcess(null);
  };

  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="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">공정관리</h1>
          <p className="text-sm text-gray-500 mt-1">생산 공정 마스터 데이터를 관리합니다</p>
        </div>
        <Button variant="primary" onClick={handleCreate}>
          <Plus className="w-4 h-4" /> 공정 등록
        </Button>
      </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-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-right 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>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {filtered.map((process) => (
                <tr key={process.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3">
                    <span className="font-mono text-blue-600 font-medium">{process.processCode}</span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="font-medium text-gray-900">{process.processName}</div>
                    <div className="text-xs text-gray-500">{process.description}</div>
                  </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 text-sm">{process.standardTime}분</td>
                  <td className="px-4 py-3 text-right text-sm">{process.processCost?.toLocaleString()}원</td>
                  <td className="px-4 py-3 text-center text-sm">{process.personnel}명</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>
                  <td className="px-4 py-3 text-center">
                    <div className="flex items-center justify-center gap-1">
                      <button
                        onClick={() => onNavigate('process-detail', process)}
                        className="p-1 text-gray-400 hover:text-blue-600 rounded"
                        title="상세보기"
                      >
                        <Eye className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => handleEdit(process)}
                        className="p-1 text-gray-400 hover:text-green-600 rounded"
                        title="수정"
                      >
                        <Edit className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {filtered.length === 0 && (
          <div className="text-center py-12 text-gray-500">
            검색 결과가 없습니다
          </div>
        )}
      </Card>

      {/* 등록/수정 모달 */}
      {showForm && (
        <ProcessForm
          process={editingProcess}
          onSave={handleSave}
          onClose={() => { setShowForm(false); setEditingProcess(null); }}
        />
      )}
    </div>
  );
};

// 공정 등록/수정 폼
const ProcessForm = ({ process, onSave, onClose }) => {
  const [formData, setFormData] = useState({
    processName: process?.processName || '',
    processType: process?.processType || '생산',
    department: process?.department || '',
    standardTime: process?.standardTime || 60,
    processCost: process?.processCost || 0,
    equipment: process?.equipment || '',
    personnel: process?.personnel || 1,
    workSheetType: process?.workSheetType || '',
    sortOrder: process?.sortOrder || 1,
    isActive: process?.isActive ?? true,
    description: process?.description || '',
    workSteps: process?.workSteps?.join(', ') || '',
  });

  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="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 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-2">
            <GitBranch className="w-5 h-5 text-blue-600" />
            <h2 className="text-lg font-bold">{process ? '공정 수정' : '공정 등록'}</h2>
            {process && <span className="text-sm text-gray-500 font-mono">{process.processCode}</span>}
          </div>
          <button onClick={onClose} className="p-2 hover:bg-gray-200 rounded-lg">
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 폼 */}
        <div className="p-4 space-y-4" style={{ flex: 1, overflowY: 'auto' }}>
          <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.processName}
                onChange={(e) => setFormData(prev => ({ ...prev, processName: e.target.value }))}
                className="w-full border rounded-lg px-3 py-2"
                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 rounded-lg px-3 py-2"
              >
                <option value="생산">생산</option>
                <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={formData.department}
                onChange={(e) => setFormData(prev => ({ ...prev, department: e.target.value }))}
                className="w-full border rounded-lg px-3 py-2"
                placeholder="예: 스크린생산부서"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">작업일지 양식</label>
              <input
                type="text"
                value={formData.workSheetType}
                onChange={(e) => setFormData(prev => ({ ...prev, workSheetType: e.target.value }))}
                className="w-full border rounded-lg px-3 py-2"
                placeholder="예: 스크린형"
              />
            </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="number"
                value={formData.standardTime}
                onChange={(e) => setFormData(prev => ({ ...prev, standardTime: parseInt(e.target.value) || 0 }))}
                className="w-full border rounded-lg px-3 py-2"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">공정비용 (원)</label>
              <input
                type="number"
                value={formData.processCost}
                onChange={(e) => setFormData(prev => ({ ...prev, processCost: parseInt(e.target.value) || 0 }))}
                className="w-full border rounded-lg px-3 py-2"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">필요인원</label>
              <input
                type="number"
                value={formData.personnel}
                onChange={(e) => setFormData(prev => ({ ...prev, personnel: parseInt(e.target.value) || 1 }))}
                className="w-full border rounded-lg px-3 py-2"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">설비정보</label>
            <input
              type="text"
              value={formData.equipment}
              onChange={(e) => setFormData(prev => ({ ...prev, equipment: e.target.value }))}
              className="w-full border rounded-lg px-3 py-2"
              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 rounded-lg px-3 py-2"
              placeholder="예: 원단절단, 미싱, 앤드락작업, 중간검사, 포장"
            />
          </div>

          <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 rounded-lg px-3 py-2"
              rows={2}
              placeholder="공정에 대한 설명"
            />
          </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={formData.sortOrder}
                onChange={(e) => setFormData(prev => ({ ...prev, sortOrder: parseInt(e.target.value) || 1 }))}
                className="w-full border rounded-lg px-3 py-2"
              />
            </div>
            <div className="flex items-center gap-2 pt-6">
              <input
                type="checkbox"
                id="isActive"
                checked={formData.isActive}
                onChange={(e) => setFormData(prev => ({ ...prev, isActive: e.target.checked }))}
                className="w-4 h-4"
              />
              <label htmlFor="isActive" className="text-sm text-gray-700">사용함</label>
            </div>
          </div>
        </div>

        {/* 하단 버튼 */}
        <div className="flex justify-end gap-2 p-4 border-t bg-gray-50" style={{ flexShrink: 0 }}>
          <Button variant="outline" onClick={onClose}>취소</Button>
          <Button variant="primary" onClick={handleSubmit}>
            {process ? '수정' : '등록'}
          </Button>
        </div>
      </div>
    </div>
  );
};

// 공정 상세
const ProcessDetail = ({ process, workOrders = [], onNavigate, onBack }) => {
  if (!process) return null;

  // 해당 공정을 사용한 작업지시 필터링
  const relatedWorkOrders = workOrders.filter(wo => 
    wo.processType === process.processType || 
    wo.processCode === process.processCode ||
    (process.processName && wo.processType?.includes(process.processName.replace(' 공정', '')))
  ).slice(0, 10); // 최근 10건만

  return (
    <div className="space-y-4">
      {/* 헤더 */}
      <div className="flex items-center gap-4">
        <button onClick={onBack} className="p-2 hover:bg-gray-100 rounded-lg">
          <ArrowLeft className="w-5 h-5" />
        </button>
        <div className="flex-1">
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold text-gray-900">{process.processName}</h1>
            <span className="font-mono text-blue-600 bg-blue-50 px-2 py-1 rounded text-sm">{process.processCode}</span>
            <span 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 ? '사용중' : '미사용'}
            </span>
          </div>
          <p className="text-sm text-gray-500 mt-1">{process.description}</p>
        </div>
        <Button variant="outline" onClick={() => onNavigate('process-edit', process)}>
          <Edit className="w-4 h-4" /> 수정
        </Button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* 기본 정보 */}
        <Card title="기본 정보" className="lg:col-span-2">
          <div className="grid grid-cols-2 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>
              <p className="font-medium">{process.standardTime}분</p>
            </div>
            <div>
              <label className="text-sm text-gray-500">공정비용</label>
              <p className="font-medium">{process.processCost?.toLocaleString()}원</p>
            </div>
            <div>
              <label className="text-sm text-gray-500">필요인원</label>
              <p className="font-medium">{process.personnel}명</p>
            </div>
            <div>
              <label className="text-sm text-gray-500">작업일지 양식</label>
              <p className="font-medium">{process.workSheetType || '-'}</p>
            </div>
            <div className="col-span-2">
              <label className="text-sm text-gray-500">설비정보</label>
              <p className="font-medium">{process.equipment || '-'}</p>
            </div>
          </div>
        </Card>

        {/* 등록 정보 */}
        <Card title="등록 정보">
          <div className="space-y-3">
            <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>
              <label className="text-sm text-gray-500">정렬순서</label>
              <p className="font-medium">{process.sortOrder}</p>
            </div>
          </div>
        </Card>
      </div>

      {/* 세부 작업단계 */}
      <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 bg-gray-100 px-3 py-2 rounded-lg">
                <span className="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-xs font-medium">
                  {idx + 1}
                </span>
                <span className="font-medium">{step}</span>
                {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>

      {/* 공정 사용 이력 */}
      <Card title={`공정 사용 이력 (최근 ${relatedWorkOrders.length}건)`}>
        {relatedWorkOrders.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>
                  <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">
                {relatedWorkOrders.map(wo => (
                  <tr 
                    key={wo.id} 
                    className="hover:bg-gray-50 cursor-pointer"
                    onClick={() => onNavigate('work-order-detail', wo)}
                  >
                    <td className="px-3 py-2 font-mono text-blue-600">{wo.workOrderNo}</td>
                    <td className="px-3 py-2 font-mono text-gray-600">{wo.orderNo}</td>
                    <td className="px-3 py-2 text-gray-900">{wo.itemName}</td>
                    <td className="px-3 py-2 text-center">{wo.quantity}</td>
                    <td className="px-3 py-2 text-center"><StatusBadge status={wo.status} /></td>
                    <td className="px-3 py-2 text-gray-600">{wo.startDate || wo.plannedDate || '-'}</td>
                    <td className="px-3 py-2 text-gray-600">{wo.assignee || '-'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="text-center py-8 text-gray-500">
            <Clock className="w-12 h-12 mx-auto mb-2 text-gray-300" />
            <p>해당 공정을 사용한 작업지시 내역이 없습니다</p>
          </div>
        )}
      </Card>
    </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="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <ShieldCheck className="w-6 h-6 text-green-500" />
          <h1 className="text-xl font-bold text-gray-900">검사기준관리</h1>
          <span className="text-sm text-gray-500">검사 기준 및 항목 관리</span>
        </div>
        <Button variant="primary" onClick={handleCreate}>
          <Plus className="w-4 h-4" /> 품질기준 등록
        </Button>
      </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-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>
  );
};

// ============================================================
// 번호기준 관리 컴포넌트
// ============================================================
const NumberRuleManagement = ({ onNavigate }) => {
  // 번호기준 목록
  const [numberRules, setNumberRules] = useState([
    { id: 1, name: '견적번호 기준', target: '견적번호', prefix: 'KD-PR', dateFormat: 'YYMMDD', seqDigits: 2, separator: '-', resetCycle: 'daily', status: '활성', example: 'KD-PR-251205-01' },
    { id: 2, name: '수주번호 기준', target: '수주번호', prefix: 'KD-SO', dateFormat: 'YYMMDD', seqDigits: 2, separator: '-', resetCycle: 'daily', status: '활성', example: 'KD-SO-251205-01' },
    { id: 3, name: '생산지시번호 기준', target: '생산지시번호', prefix: 'KD-MO', dateFormat: 'YYMMDD', seqDigits: 2, separator: '-', resetCycle: 'daily', status: '활성', example: 'KD-MO-251205-01' },
    { id: 4, name: '출하지시번호 기준', target: '출하지시번호', prefix: 'KD-OT', dateFormat: 'YYMMDD', seqDigits: 2, separator: '-', resetCycle: 'daily', status: '활성', example: 'KD-OT-251205-01' },
    { id: 5, name: '발주번호 기준', target: '발주번호', prefix: 'KD-PO', dateFormat: 'YYMMDD', seqDigits: 2, separator: '-', resetCycle: 'daily', status: '활성', example: 'KD-PO-251205-01' },
  ]);
  
  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: '',
  });
  
  // 적용대상 목록 및 템플릿
  const targetTemplates = [
    { value: '견적번호', label: '견적번호', prefix: 'KD-PR', icon: '📋' },
    { value: '수주번호', label: '수주번호', prefix: 'KD-SO', icon: '📦' },
    { value: '생산지시번호', label: '생산지시번호', prefix: 'KD-MO', icon: '🏭' },
    { value: '출하지시번호', label: '출하지시번호', prefix: 'KD-OT', icon: '🚚' },
    { value: '발주번호', label: '발주번호', prefix: 'KD-PO', icon: '🛒' },
  ];
  
  // 날짜 형식 옵션
  const dateFormats = [
    { value: 'YYMMDD', label: 'YYMMDD (251205)', example: '251205' },
    { value: 'YYYYMMDD', label: 'YYYYMMDD (20251205)', example: '20251205' },
    { value: 'YYMM', label: 'YYMM (2512)', example: '2512' },
    { value: 'YYYYMM', label: 'YYYYMM (202512)', example: '202512' },
    { value: 'YY', label: 'YY (25)', example: '25' },
    { value: 'NONE', label: '사용안함', example: '' },
  ];
  
  // 순번 자릿수 옵션
  const seqDigitOptions = [
    { value: 2, label: '2자리 (01~99)' },
    { value: 3, label: '3자리 (001~999)' },
    { value: 4, label: '4자리 (0001~9999)' },
  ];
  
  // 리셋 주기 옵션
  const resetCycleOptions = [
    { value: 'daily', label: '매일 (일자 바뀌면 01부터)' },
    { value: 'monthly', label: '매월 (월 바뀌면 01부터)' },
    { value: 'yearly', label: '매년 (년 바뀌면 01부터)' },
    { value: 'never', label: '리셋 안함 (계속 증가)' },
  ];
  
  // 구분자 옵션
  const separatorOptions = [
    { value: '-', label: '하이픈 (-)' },
    { value: '_', label: '언더스코어 (_)' },
    { value: '', label: '없음' },
  ];
  
  // 번호 미리보기 생성
  const generatePreview = (data) => {
    const today = new Date();
    const dateStr = data.dateFormat === 'NONE' ? '' : (() => {
      const yy = String(today.getFullYear()).slice(-2);
      const yyyy = String(today.getFullYear());
      const mm = String(today.getMonth() + 1).padStart(2, '0');
      const dd = String(today.getDate()).padStart(2, '0');
      switch(data.dateFormat) {
        case 'YYMMDD': return `${yy}${mm}${dd}`;
        case 'YYYYMMDD': return `${yyyy}${mm}${dd}`;
        case 'YYMM': return `${yy}${mm}`;
        case 'YYYYMM': return `${yyyy}${mm}`;
        case 'YY': return yy;
        default: return '';
      }
    })();
    const seq = '01'.padStart(data.seqDigits, '0');
    const sep = data.separator;
    
    if (data.dateFormat === 'NONE') {
      return `${data.prefix}${sep}${seq}`;
    }
    return `${data.prefix}${sep}${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
    ));
  };
  
  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 mt-1">견적서, 수주서, 생산지시서 등의 문서 번호 생성 규칙을 관리합니다.</p>
        </div>
        <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 className="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <div className="flex gap-3">
          <div className="text-blue-500 text-xl">💡</div>
          <div>
            <h4 className="font-medium text-blue-900">번호기준이란?</h4>
            <p className="text-sm text-blue-700 mt-1">
              <strong>문서</strong>에 부여하는 일련번호 규칙입니다. 견적번호, 수주번호, 생산지시번호 등 문서 식별에 사용됩니다.
            </p>
          </div>
        </div>
      </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-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">
            {numberRules.map((rule, idx) => (
              <tr key={rule.id} 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-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>
                <td className="px-4 py-3 text-center">
                  <div className="flex justify-center gap-1">
                    <button 
                      onClick={() => openEditModal(rule)}
                      className="p-1 hover:bg-gray-100 rounded"
                      title="수정"
                    >
                      <Edit3 className="w-4 h-4 text-gray-500" />
                    </button>
                    <button 
                      onClick={() => handleDelete(rule.id)}
                      className="p-1 hover:bg-red-50 rounded"
                      title="삭제"
                    >
                      <Trash2 className="w-4 h-4 text-red-400" />
                    </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">
                <X className="w-5 h-5" />
              </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-blue-100 text-blue-600 rounded-full flex items-center justify-center text-sm">1</span>
                  기본 정보
                </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-2xl mb-1">{template.icon}</div>
                        <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 flex items-center gap-2">
                  <span className="w-6 h-6 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center text-sm">2</span>
                  번호 구성
                </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 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">
                  <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>
  );
};

// ============================================================
// 코드기준 관리 컴포넌트
// ============================================================
const CodeRuleManagement = ({ onNavigate }) => {
  // 코드기준 목록
  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: '품목유형 + 카테고리 + 일련번호' },
    { id: 2, name: '입고LOT 기준', target: '입고LOT', codeType: 'lot', prefix: 'L', useDate: true, dateFormat: 'YYMMDD', useProcess: false, seqDigits: 3, separator: '-', components: ['prefix', 'date', 'seq'], example: 'L-251205-001', status: '활성', description: '자재 입고 시 부여되는 LOT' },
    { id: 3, name: '생산LOT 기준', target: '생산LOT', codeType: 'lot', prefix: 'P', useDate: true, dateFormat: 'YYMMDD', useProcess: true, seqDigits: 2, separator: '-', components: ['prefix', 'date', 'process', 'seq'], example: 'P-251205-SC-01', status: '활성', description: '생산 시 부여되는 LOT' },
    { id: 4, name: '거래처코드 기준', target: '거래처코드', codeType: 'simple', prefix: 'C', useDate: false, dateFormat: '', useProcess: false, seqDigits: 3, separator: '-', components: ['prefix', 'seq'], example: 'C-001', status: '활성', description: '거래처 식별코드' },
    { id: 5, name: '현장코드 기준', target: '현장코드', codeType: 'simple', prefix: 'S', useDate: false, dateFormat: '', useProcess: false, seqDigits: 3, separator: '-', components: ['prefix', 'seq'], example: 'S-001', status: '활성', description: '현장 식별코드' },
  ]);
  
  const [showModal, setShowModal] = useState(false);
  const [editingRule, setEditingRule] = useState(null);
  const [formData, setFormData] = useState({
    name: '',
    target: '',
    codeType: 'simple',
    prefix: '',
    useDate: false,
    dateFormat: 'YYMMDD',
    useProcess: false,
    seqDigits: 3,
    separator: '-',
    status: '활성',
    description: '',
  });
  
  // 적용대상 및 템플릿
  const targetTemplates = [
    { value: '품목코드', label: '품목코드', icon: '📦', codeType: 'composite', prefix: '', useDate: false, useProcess: false, seqDigits: 3 },
    { value: '입고LOT', label: '입고LOT', icon: '📥', codeType: 'lot', prefix: 'L', useDate: true, useProcess: false, seqDigits: 3 },
    { value: '생산LOT', label: '생산LOT', icon: '🏭', codeType: 'lot', prefix: 'P', useDate: true, useProcess: true, seqDigits: 2 },
    { value: '거래처코드', label: '거래처코드', icon: '🏢', codeType: 'simple', prefix: 'C', useDate: false, useProcess: false, seqDigits: 3 },
    { value: '현장코드', label: '현장코드', icon: '📍', codeType: 'simple', prefix: 'S', useDate: false, useProcess: false, seqDigits: 3 },
  ];
  
  // 코드 유형
  const codeTypes = [
    { value: 'simple', label: '단순형', desc: '접두사 + 순번', example: 'C-001' },
    { value: 'lot', label: 'LOT형', desc: '접두사 + 날짜 + 순번', example: 'L-251205-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: '없음' },
  ];
  
  // 코드 미리보기 생성
  const generatePreview = (data) => {
    const sep = data.separator;
    const seq = '1'.padStart(data.seqDigits, '0');
    
    // 날짜 생성
    const today = new Date();
    const yy = String(today.getFullYear()).slice(-2);
    const yyyy = String(today.getFullYear());
    const mm = String(today.getMonth() + 1).padStart(2, '0');
    const dd = String(today.getDate()).padStart(2, '0');
    let dateStr = '';
    if (data.useDate) {
      switch(data.dateFormat) {
        case 'YYMMDD': dateStr = `${yy}${mm}${dd}`; break;
        case 'YYYYMMDD': dateStr = `${yyyy}${mm}${dd}`; break;
        case 'YYMM': dateStr = `${yy}${mm}`; break;
        default: dateStr = `${yy}${mm}${dd}`;
      }
    }
    
    // 코드 유형별 생성
    switch(data.codeType) {
      case 'simple':
        return `${data.prefix}${sep}${seq}`;
      case 'lot':
        if (data.useProcess) {
          return `${data.prefix}${sep}${dateStr}${sep}SC${sep}${seq}`;
        }
        return `${data.prefix}${sep}${dateStr}${sep}${seq}`;
      case 'composite':
        return `BP${sep}GR${sep}${seq}`;
      default:
        return `${data.prefix}${sep}${seq}`;
    }
  };
  
  // 구조 설명 생성
  const getStructureDescription = (data) => {
    const parts = [];
    switch(data.codeType) {
      case 'simple':
        parts.push('접두사');
        parts.push('순번');
        break;
      case 'lot':
        parts.push('접두사');
        if (data.useDate) parts.push('날짜');
        if (data.useProcess) 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="flex justify-between items-center">
        <div>
          <h2 className="text-xl font-bold text-gray-900">코드기준 관리</h2>
          <p className="text-sm text-gray-500 mt-1">품목코드, LOT번호, 거래처코드 등 마스터/실물 식별코드 규칙을 관리합니다.</p>
        </div>
        <button 
          onClick={openCreateModal}
          className="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 flex items-center gap-2"
        >
          <Plus className="w-4 h-4" /> 규칙 추가
        </button>
      </div>
      
      {/* 안내 카드 */}
      <div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
        <div className="flex gap-3">
          <div className="text-orange-500 text-xl">🏷️</div>
          <div>
            <h4 className="font-medium text-orange-900">코드기준이란?</h4>
            <p className="text-sm text-orange-700 mt-1">
              <strong>실물/마스터</strong>에 부여하는 식별코드 규칙입니다. 품목코드, 입고LOT, 생산LOT, 거래처코드 등에 사용됩니다.
            </p>
          </div>
        </div>
      </div>
      
      {/* 번호기준 vs 코드기준 비교 */}
      <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">
            <span className="text-xl">🔢</span> 번호기준 (문서용)
          </h4>
          <ul className="text-sm text-blue-700 mt-2 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">
            <span className="text-xl">🏷️</span> 코드기준 (실물용)
          </h4>
          <ul className="text-sm text-orange-700 mt-2 space-y-1">
            <li>• 품목코드 (RC30, CB24 등)</li>
            <li>• 입고LOT, 생산LOT</li>
            <li>• 거래처코드, 현장코드</li>
          </ul>
        </div>
      </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">
            {codeRules.map((rule, idx) => (
              <tr key={rule.id} 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-medium text-gray-900">{rule.name}</td>
                <td className="px-4 py-3 text-sm text-gray-600">
                  <span className="mr-1">{targetTemplates.find(t => t.value === rule.target)?.icon}</span>
                  {rule.target}
                </td>
                <td className="px-4 py-3 text-sm">
                  <span className={`px-2 py-0.5 rounded text-xs ${
                    rule.codeType === 'simple' ? 'bg-gray-100 text-gray-600' :
                    rule.codeType === 'lot' ? 'bg-purple-100 text-purple-700' :
                    'bg-orange-100 text-orange-700'
                  }`}>
                    {codeTypes.find(t => t.value === rule.codeType)?.label || rule.codeType}
                  </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-1">
                    <button 
                      onClick={() => openEditModal(rule)}
                      className="p-1 hover:bg-gray-100 rounded" 
                      title="수정"
                    >
                      <Edit3 className="w-4 h-4 text-gray-500" />
                    </button>
                    <button 
                      onClick={() => handleDelete(rule.id)}
                      className="p-1 hover:bg-red-50 rounded" 
                      title="삭제"
                    >
                      <Trash2 className="w-4 h-4 text-red-400" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      
      {/* 품목코드 매핑 규칙 (경동기업 특화) */}
      <div className="bg-white rounded-lg shadow-sm border p-4">
        <h3 className="font-medium text-gray-900 mb-3 flex items-center gap-2">
          <Layers className="w-5 h-5 text-orange-500" />
          품목코드 매핑 규칙 (자동 분류)
        </h3>
        <p className="text-sm text-gray-500 mb-4">
          품목코드 패턴으로 품목유형/카테고리를 자동 분류합니다. 코드 체계가 있는 회사에서 사용합니다.
        </p>
        <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-left text-xs font-medium text-gray-500">예시</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              <tr><td className="px-3 py-2 font-mono">R*</td><td className="px-3 py-2">절곡부품</td><td className="px-3 py-2">가이드레일</td><td className="px-3 py-2 text-gray-500">RC30, RD24, RM30</td></tr>
              <tr><td className="px-3 py-2 font-mono">C*</td><td className="px-3 py-2">절곡부품</td><td className="px-3 py-2">케이스</td><td className="px-3 py-2 text-gray-500">CB30, CF24, CL30</td></tr>
              <tr><td className="px-3 py-2 font-mono">B*</td><td className="px-3 py-2">절곡부품</td><td className="px-3 py-2">하단마감재</td><td className="px-3 py-2 text-gray-500">BE30, BS40</td></tr>
              <tr><td className="px-3 py-2 font-mono">G*</td><td className="px-3 py-2">절곡부품</td><td className="px-3 py-2">연기차단재</td><td className="px-3 py-2 text-gray-500">GI30, GI40</td></tr>
              <tr><td className="px-3 py-2 font-mono">L*</td><td className="px-3 py-2">절곡부품</td><td className="px-3 py-2">L-Bar</td><td className="px-3 py-2 text-gray-500">LA30, LA40</td></tr>
              <tr><td className="px-3 py-2 font-mono">E-*</td><td className="px-3 py-2">구매부품</td><td className="px-3 py-2">전동개폐기</td><td className="px-3 py-2 text-gray-500">E-300K220V-W</td></tr>
            </tbody>
          </table>
        </div>
      </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">
                <X className="w-5 h-5" />
              </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-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-orange-500 bg-orange-50 ring-2 ring-orange-200'
                          : 'border-gray-200 hover:border-gray-300'
                      }`}
                    >
                      <div className="text-2xl mb-1">{template.icon}</div>
                      <div className="text-xs 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>
              
              {/* 상태 */}
              <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 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);
  
  // 검색 필터 적용
  const filteredItems = filteredByCategory.filter(item => {
    if (!search) return true;
    return item.materialCode.toLowerCase().includes(search.toLowerCase()) ||
           item.materialName.toLowerCase().includes(search.toLowerCase());
  });
  
  // 품목유형별 통계
  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('전체');
  };
  
  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 mt-1">원자재, 절곡부품, 구매부품, 부자재 등 전체 재고 관리</p>
        </div>
        <div className="flex gap-2">
          <button className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 flex items-center gap-2 text-sm">
            <Download className="w-4 h-4" /> 엑셀 다운로드
          </button>
        </div>
      </div>
      
      {/* 품목유형 탭 */}
      <div className="bg-white rounded-lg shadow-sm border">
        <div className="border-b">
          <nav className="flex -mb-px overflow-x-auto">
            {itemTypes.map(type => {
              const stats = getTypeStats(type.code);
              return (
                <button
                  key={type.code}
                  onClick={() => handleTypeChange(type.code)}
                  className={`px-5 py-3 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
                    selectedItemType === type.code
                      ? 'border-blue-500 text-blue-600 bg-blue-50'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                  }`}
                >
                  <span>{type.name}</span>
                  <span className="ml-2 text-xs text-gray-400">
                    {stats.count}
                    {stats.lowStock > 0 && (
                      <span className="ml-1 text-orange-500">⚠{stats.lowStock}</span>
                    )}
                  </span>
                </button>
              );
            })}
          </nav>
        </div>
        
        {/* 필터 영역 */}
        <div className="p-4 border-b bg-gray-50 flex gap-4 items-center flex-wrap">
          <div className="flex-1 min-w-[200px]">
            <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 rounded-lg text-sm"
              />
            </div>
          </div>
          {/* 카테고리 필터 (전체가 아닐 때만 표시) */}
          {selectedItemType !== '전체' && categories.length > 1 && (
            <div className="flex items-center gap-2">
              <span className="text-sm text-gray-500">카테고리:</span>
              <select
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
                className="border rounded-lg px-3 py-2 text-sm"
              >
                {categories.map(cat => (
                  <option key={cat} value={cat}>{cat}</option>
                ))}
              </select>
            </div>
          )}
          <div className="text-sm text-gray-500">
            검색결과: <span className="font-medium text-gray-900">{filteredItems.length}</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-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">상태</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">
              {filteredItems.length === 0 ? (
                <tr>
                  <td colSpan="9" className="px-4 py-8 text-center text-gray-500">
                    해당 조건의 품목이 없습니다.
                  </td>
                </tr>
              ) : (
                filteredItems.map(item => {
                  const status = getStockStatus(item);
                  return (
                    <tr key={item.id} className="hover:bg-gray-50 cursor-pointer">
                      <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-gray-600">{item.category || '-'}</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">
                        <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>
                    </tr>
                  );
                })
              )}
            </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 className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
        {itemTypes.filter(t => t.code !== '전체').map(type => {
          const stats = getTypeStats(type.code);
          const items = inventory.filter(i => i.itemType === type.code);
          const totalStock = items.reduce((sum, i) => sum + i.stock, 0);
          return (
            <div
              key={type.code}
              onClick={() => handleTypeChange(type.code)}
              className={`bg-white rounded-lg shadow-sm border p-3 cursor-pointer hover:shadow transition-shadow ${
                selectedItemType === type.code ? 'ring-2 ring-blue-500' : ''
              }`}
            >
              <h3 className="text-xs font-medium text-gray-500">{type.name}</h3>
              <p className="text-lg font-bold text-gray-900 mt-1">{stats.count}종</p>
              <div className="flex justify-between mt-1 text-xs">
                <span className="text-gray-400">재고 {totalStock.toLocaleString()}</span>
                {stats.lowStock > 0 && (
                  <span className="text-orange-500 font-medium">부족 {stats.lowStock}</span>
                )}
              </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 CustomerList = ({ customers = initialCustomers, onNavigate }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [showPanel, setShowPanel] = useState(false);
  const [panelMode, setPanelMode] = useState('create'); // 'create' | 'edit' | 'detail'
  const [selectedCustomer, setSelectedCustomer] = useState(null);
  const [formData, setFormData] = useState({});

  const tabs = [
    { id: 'all', label: '전체', count: customers.length },
    { id: 'customer', label: '고객사', count: customers.filter(c => c.customerType === '고객사').length },
    { id: 'supplier', label: '공급업체', count: customers.filter(c => c.customerType === '공급업체').length },
  ];

  const filtered = customers
    .filter(c => activeTab === 'all' || 
      (activeTab === 'customer' && c.customerType === '고객사') ||
      (activeTab === 'supplier' && c.customerType === '공급업체'))
    .filter(c =>
      c.customerCode.toLowerCase().includes(search.toLowerCase()) ||
      c.customerName.includes(search) ||
      c.ceo?.includes(search) ||
      c.businessNo?.includes(search)
    );

  const openCreatePanel = () => {
    setPanelMode('create');
    setFormData({
      customerType: '고객사',
      creditGrade: 'B',
      paymentMethod: '계좌이체',
    });
    setSelectedCustomer(null);
    setShowPanel(true);
  };

  const openEditPanel = (customer) => {
    setPanelMode('edit');
    setFormData({ ...customer });
    setSelectedCustomer(customer);
    setShowPanel(true);
  };

  const openDetailPanel = (customer) => {
    setPanelMode('detail');
    setSelectedCustomer(customer);
    setShowPanel(true);
  };

  const handleSave = () => {
    alert(panelMode === 'create' ? '거래처가 등록되었습니다.' : '거래처가 수정되었습니다.');
    setShowPanel(false);
  };

  // 통계
  const totalReceivables = customers.reduce((sum, c) => sum + (c.receivables?.total || 0), 0);
  const overdueReceivables = customers.reduce((sum, c) => sum + (c.receivables?.overdue || 0), 0);
  const gradeACount = customers.filter(c => c.creditGrade === 'A').length;
  const gradeCCount = customers.filter(c => c.creditGrade === 'C').length;

  return (
    <div className="space-y-6">
      <PageHeader 
        icon={Users} 
        title="거래처 관리"
        actions={
          <Button variant="primary" onClick={openCreatePanel}>
            <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" />
        <DashboardCard icon={DollarSign} title="총 미수금" value={`${(totalReceivables / 10000).toLocaleString()}만원`} color="yellow" />
        <DashboardCard icon={AlertCircle} title="연체 미수금" value={`${(overdueReceivables / 10000).toLocaleString()}만원`} color="red" />
        <DashboardCard icon={CheckCircle} title="A등급 거래처" value={`${gradeACount}개`} 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-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-center text-xs font-medium text-gray-500">액션</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map((customer) => (
              <tr key={customer.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => openDetailPanel(customer)}>
                <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' : 'bg-purple-100 text-purple-700'}`}>
                    {customer.customerType}
                  </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>
                <td className="px-4 py-3"><CreditGradeBadge grade={customer.creditGrade} /></td>
                <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>
                <td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                  <Button variant="ghost" size="sm" onClick={() => openEditPanel(customer)}>
                    <Edit className="w-4 h-4" />
                  </Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 슬라이드 패널 */}
      <SlidePanel
        isOpen={showPanel}
        onClose={() => setShowPanel(false)}
        title={panelMode === 'create' ? '거래처 등록' : panelMode === 'edit' ? '거래처 수정' : '거래처 상세'}
        width="max-w-4xl"
      >
        {panelMode === 'detail' && selectedCustomer ? (
          <CustomerDetailPanel customer={selectedCustomer} onEdit={() => openEditPanel(selectedCustomer)} onClose={() => setShowPanel(false)} />
        ) : (
          <CustomerFormPanel formData={formData} setFormData={setFormData} onSave={handleSave} onCancel={() => setShowPanel(false)} isEdit={panelMode === 'edit'} />
        )}
      </SlidePanel>
    </div>
  );
};

// 거래처 상세 패널
const CustomerDetailPanel = ({ customer, onEdit, onClose }) => {
  const [activeTab, setActiveTab] = useState('basic');

  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">
              <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 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>
            <div>
              <span className="text-gray-500">결제조건</span>
              <p className="font-medium">{customer.paymentTerms}</p>
            </div>
          </div>
        </div>

        {/* 탭 */}
        <div className="border-b">
          <div className="flex gap-4">
            {[
              { id: 'basic', label: '기본정보' },
              { id: 'transaction', label: '거래내역' },
              { id: 'receivable', label: '미수금현황' },
              { id: 'history', label: '변경이력' },
            ].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}
              </button>
            ))}
          </div>
        </div>

        {/* 탭 내용 */}
        {activeTab === 'basic' && (
          <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>
                  <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?.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>
                ))}
              </div>
            </div>
            {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>
        )}

        {activeTab === 'transaction' && (
          <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?.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.toLocaleString()}원</td>
                    <td className="px-4 py-2 text-right">{tx.balance.toLocaleString()}원</td>
                    <td className="px-4 py-2 text-gray-600">{tx.note}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {activeTab === 'receivable' && (
          <div className="space-y-4">
            <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>
        )}

        {activeTab === 'history' && (
          <div className="text-sm text-gray-500 text-center py-8">
            변경이력이 없습니다.
          </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 }) => {
  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 flex items-center gap-2">
            <Building className="w-5 h-5 text-gray-600" /> 기본 정보
          </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 flex items-center gap-2">
            <Phone className="w-5 h-5 text-gray-600" /> 연락처 정보
          </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>

        {/* 신용정보 */}
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
            <CreditCard className="w-5 h-5 text-gray-600" /> 신용 및 결제 정보
          </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 [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [showPanel, setShowPanel] = useState(false);
  const [panelMode, setPanelMode] = useState('create');
  const [selectedSite, setSelectedSite] = useState(null);
  const [formData, setFormData] = useState({});

  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',
      '수주확정': 'bg-gray-100 text-gray-700',
    };
    return colors[status] || 'bg-gray-100 text-gray-700';
  };

  const tabs = [
    { id: 'all', label: '전체', count: sites.length },
    { id: 'progress', label: '진행중', count: sites.filter(s => s.status !== '설치완료').length },
    { id: 'complete', label: '완료', count: sites.filter(s => s.status === '설치완료').length },
  ];

  const filtered = sites
    .filter(s => activeTab === 'all' || 
      (activeTab === 'progress' && s.status !== '설치완료') ||
      (activeTab === 'complete' && s.status === '설치완료'))
    .filter(s =>
      s.siteCode.toLowerCase().includes(search.toLowerCase()) ||
      s.siteName.includes(search) ||
      s.customerName.includes(search)
    );

  const openCreatePanel = () => {
    setPanelMode('create');
    setFormData({ status: '수주확정', progress: 0 });
    setSelectedSite(null);
    setShowPanel(true);
  };

  const openDetailPanel = (site) => {
    setPanelMode('detail');
    setSelectedSite(site);
    setShowPanel(true);
  };

  const openEditPanel = (site) => {
    setPanelMode('edit');
    setFormData({ ...site });
    setSelectedSite(site);
    setShowPanel(true);
  };

  // 통계
  const progressCount = sites.filter(s => s.status !== '설치완료').length;
  const completeCount = sites.filter(s => s.status === '설치완료').length;
  const totalAmount = sites.reduce((sum, s) => sum + (s.orders?.[0]?.amount || 0), 0);

  return (
    <div className="space-y-6">
      <PageHeader 
        icon={Building} 
        title="현장 관리"
        actions={
          <Button variant="primary" onClick={openCreatePanel}>
            <Plus className="w-4 h-4" /> 현장 등록
          </Button>
        }
      />

      {/* 대시보드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <DashboardCard icon={Building} title="전체 현장" value={`${sites.length}건`} color="blue" />
        <DashboardCard icon={Clock} title="진행중" value={`${progressCount}건`} color="yellow" />
        <DashboardCard icon={CheckCircle} title="설치완료" value={`${completeCount}건`} color="green" />
        <DashboardCard icon={DollarSign} title="총 수주금액" value={`${(totalAmount / 100000000).toFixed(1)}억원`} 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">
        <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">설치담당</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((site) => (
              <tr key={site.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => openDetailPanel(site)}>
                <td className="px-4 py-3 text-sm font-mono text-blue-600">{site.siteCode}</td>
                <td className="px-4 py-3">
                  <div className="text-sm font-medium text-gray-900">{site.siteName}</div>
                  <div className="text-xs text-gray-500">{site.siteAddress}</div>
                </td>
                <td className="px-4 py-3 text-sm text-gray-900">{site.customerName}</td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-0.5 rounded text-xs ${getStatusColor(site.status)}`}>{site.status}</span>
                </td>
                <td className="px-4 py-3">
                  <div className="flex items-center gap-2">
                    <div className="w-20 h-2 bg-gray-200 rounded-full overflow-hidden">
                      <div className="h-full bg-blue-500 rounded-full" style={{ width: `${site.progress}%` }} />
                    </div>
                    <span className="text-xs text-gray-600">{site.progress}%</span>
                  </div>
                </td>
                <td className="px-4 py-3 text-sm text-gray-600">{site.installScheduledDate}</td>
                <td className="px-4 py-3 text-sm text-gray-600">{site.installManager}</td>
                <td className="px-4 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                  <Button variant="ghost" size="sm" onClick={() => openEditPanel(site)}>
                    <Edit className="w-4 h-4" />
                  </Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 슬라이드 패널 */}
      <SlidePanel
        isOpen={showPanel}
        onClose={() => setShowPanel(false)}
        title={panelMode === 'create' ? '현장 등록' : panelMode === 'edit' ? '현장 수정' : '현장 상세'}
        width="max-w-4xl"
      >
        {panelMode === 'detail' && selectedSite ? (
          <SiteDetailPanel site={selectedSite} onEdit={() => openEditPanel(selectedSite)} onClose={() => setShowPanel(false)} />
        ) : (
          <SiteFormPanel formData={formData} setFormData={setFormData} onSave={() => { alert('저장되었습니다.'); setShowPanel(false); }} onCancel={() => setShowPanel(false)} isEdit={panelMode === 'edit'} />
        )}
      </SlidePanel>
    </div>
  );
};

// 현장 상세 패널
const SiteDetailPanel = ({ site, onEdit, onClose }) => {
  const [activeTab, setActiveTab] = useState('basic');

  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="border-b">
          <div className="flex gap-4">
            {[
              { id: 'basic', label: '기본정보' },
              { id: 'orders', label: '수주내역' },
              { id: 'shipments', label: '출고내역' },
              { id: 'history', label: '변경이력' },
            ].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-green-500 text-green-600' : 'border-transparent text-gray-500 hover:text-gray-700'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>
        </div>

        {/* 탭 내용 */}
        {activeTab === 'basic' && (
          <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>
        )}

        {activeTab === 'orders' && (
          <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?.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>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {activeTab === 'shipments' && (
          <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>
        )}

        {activeTab === 'history' && (
          <div className="space-y-3">
            {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>
        )}
      </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 flex items-center gap-2">
            <MapPin className="w-5 h-5 text-gray-600" /> 현장 정보
          </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 flex items-center gap-2">
            <User className="w-5 h-5 text-gray-600" /> 설치 담당자
          </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 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="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Calculator className="w-6 h-6 text-blue-500" />
          <div>
            <h1 className="text-xl font-bold text-gray-900">견적수식 목록</h1>
            <p className="text-sm text-gray-500">품목별 수량, 면적 등을 계산하는 수식을 제품과 카테고리별로 관리합니다</p>
          </div>
        </div>
      </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-blue-500 text-white border-blue-500'
                        : 'bg-white text-gray-700 border-gray-300 hover:border-blue-300'
                    }`}
                  >
                    {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">
          <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">
              <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">
                <X className="w-5 h-5" />
              </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">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md mx-4">
            <div className="flex items-center justify-between p-4 border-b">
              <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">
                <X className="w-5 h-5" />
              </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">
          <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">
              <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">
                <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-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">
          <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">
              <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">
                <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-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: '백면',
    MP: '220V',
    CT: '기본형',
    QTY: 1,
    WS: 0,
    INSP: 0,
  });
  const [calculatedItems, setCalculatedItems] = useState([]);
  const [totalAmount, setTotalAmount] = useState(0);
  
  // 샘플 단가 데이터
  const priceList = [
    { itemCode: 'BP-GR-001', itemName: '가이드레일', sellingPrice: 45000 },
    { itemCode: 'BP-GB-001', itemName: '하부베이스', sellingPrice: 25000 },
    { itemCode: 'BP-CS-001', itemName: '케이스', sellingPrice: 80000 },
    { itemCode: 'BP-SC-001', itemName: '측면덮개', sellingPrice: 15000 },
    { itemCode: 'BP-TC-001', itemName: '상부덮개', sellingPrice: 20000 },
    { itemCode: 'BP-BF-001', itemName: '하단마감재', sellingPrice: 30000 },
    { itemCode: 'BP-BB-001', itemName: '하단보강빔바', sellingPrice: 25000 },
  ];
  
  // 견적 계산
  const handleCalculate = () => {
    const result = formulaEngine.calculateQuoteItems(inputs, formulas, priceList);
    setCalculatedItems(result.items);
    setTotalAmount(result.totalAmount);
  };
  
  return (
    <Card title="자동 견적 산출" subtitle="입력값을 기반으로 견적을 자동으로 산출합니다">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 입력 폼 */}
        <div className="space-y-4">
          <h3 className="font-medium text-gray-900 mb-4">견적 입력</h3>
          
          <div className="border rounded-lg p-4 bg-gray-50">
            <div className="grid grid-cols-3 gap-4 mb-4">
              <div>
                <label className="block text-xs text-gray-500 mb-1">층수</label>
                <input
                  type="text"
                  placeholder="예: 1층, B1, 지하1층"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">부호</label>
                <input
                  type="text"
                  placeholder="예: A, B, C"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">제품 카테고리 (PC) *</label>
                <select
                  value={inputs.PC}
                  onChange={e => setInputs({...inputs, PC: 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-4 mb-4">
              <div>
                <label className="block text-xs text-gray-500 mb-1">오픈사이즈 (W0) *</label>
                <input
                  type="number"
                  value={inputs.W0}
                  onChange={e => setInputs({...inputs, W0: Number(e.target.value)})}
                  placeholder="예: 2000"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">오픈사이즈 (H0) *</label>
                <input
                  type="number"
                  value={inputs.H0}
                  onChange={e => setInputs({...inputs, H0: Number(e.target.value)})}
                  placeholder="예: 2500"
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
            </div>
            
            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <label className="block text-xs text-gray-500 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"
                >
                  <option value="백면">백면형</option>
                  <option value="측면">측면형</option>
                  <option value="양측">양측면형</option>
                </select>
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">모터 전원 (MP) *</label>
                <select
                  value={inputs.MP}
                  onChange={e => setInputs({...inputs, MP: e.target.value})}
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                >
                  <option value="220V">220V</option>
                  <option value="380V">380V</option>
                </select>
              </div>
            </div>
            
            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <label className="block text-xs text-gray-500 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"
                >
                  <option value="기본형">기본형</option>
                  <option value="고급형">고급형</option>
                </select>
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">수량 (QTY) *</label>
                <input
                  type="number"
                  value={inputs.QTY}
                  onChange={e => setInputs({...inputs, QTY: Number(e.target.value)})}
                  min={1}
                  className="w-full px-3 py-2 border rounded-lg text-sm"
                />
              </div>
            </div>
          </div>
          
          <div className="flex gap-2">
            <button
              onClick={handleCalculate}
              className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
            >
              <Calculator className="w-5 h-5" />
              견적 계산
            </button>
            <button className="p-3 border rounded-lg hover:bg-gray-50">
              <Copy className="w-5 h-5 text-gray-500" />
            </button>
            <button className="p-3 border rounded-lg hover:bg-gray-50">
              <Trash2 className="w-5 h-5 text-gray-500" />
            </button>
          </div>
        </div>
        
        {/* 산출 결과 */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="font-medium text-gray-900">산출 결과</h3>
            {calculatedItems.length > 0 && (
              <span className="text-sm text-gray-500">{calculatedItems.length}개 품목</span>
            )}
          </div>
          
          {calculatedItems.length > 0 ? (
            <>
              <div className="border rounded-lg overflow-hidden">
                <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">
                    {calculatedItems.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">
                          <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' :
                            'bg-gray-100 text-gray-700'
                          }`}>
                            {item.process || '-'}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              
              <div className="flex items-center justify-between p-4 bg-blue-50 rounded-lg">
                <span className="font-medium text-gray-900">합계</span>
                <span className="text-xl font-bold text-blue-600">{totalAmount.toLocaleString()}원</span>
              </div>
            </>
          ) : (
            <div className="border rounded-lg p-8 text-center text-gray-500">
              <Calculator className="w-12 h-12 mx-auto mb-3 text-gray-300" />
              <p>입력값을 입력하고 "견적 계산" 버튼을 클릭하세요.</p>
            </div>
          )}
        </div>
      </div>
    </Card>
  );
};

// ============ 단가 관리 ============

const PriceList = ({ onNavigate }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('기본단가');
  const [itemTypeTab, setItemTypeTab] = useState('전체');
  const [showModal, setShowModal] = useState(false);
  const [modalMode, setModalMode] = useState('edit'); // edit, customer, detail
  const [selectedItem, setSelectedItem] = useState(null);
  
  // 품목별 기본단가 데이터
  const [basePrices, setBasePrices] = useState([
    { id: 1, itemType: '제품', itemCode: 'SCREEN-001', itemName: '스크린 셔터 기본형', spec: '표준형', unit: 'SET', purchasePrice: null, processingCost: null, sellingPrice: null, marginRate: null, validFrom: null, validTo: null, status: '미등록' },
    { id: 2, itemType: '제품', itemCode: 'SCREEN-002', itemName: '스크린 셔터 오픈형', spec: '오픈형', unit: 'SET', purchasePrice: null, processingCost: null, sellingPrice: null, marginRate: null, validFrom: null, validTo: null, status: '미등록' },
    { id: 3, itemType: '제품', itemCode: 'STEEL-001', itemName: '철재 셔터 기본형', spec: '표준형', unit: 'SET', purchasePrice: null, processingCost: null, sellingPrice: null, marginRate: null, validFrom: null, validTo: null, status: '미등록' },
    { id: 4, itemType: '부품', itemCode: 'GR-001', itemName: '가이드레일 130×80', spec: '130×80×2438', unit: 'EA', purchasePrice: 45000, processingCost: 5000, sellingPrice: 60000, marginRate: 20.0, validFrom: '2025-01-01', validTo: '2025-12-31', status: '활성', supplier: '철강공업', lossRate: 0, qtyPricing: [{ minQty: 1, maxQty: 9, price: 60000 }, { minQty: 10, maxQty: 49, price: 57000 }, { minQty: 50, maxQty: 999, price: 54000 }], history: [{ date: '2025-01-01', action: '단가 등록', oldPrice: null, newPrice: 60000, by: '김관리' }] },
    { id: 5, itemType: '부품', itemCode: 'CASE-001', itemName: '케이스 철재', spec: '표준형', unit: 'EA', purchasePrice: 35000, processingCost: 10000, sellingPrice: 56250, marginRate: 25.0, validFrom: '2025-01-01', validTo: '2025-12-31', status: '활성', supplier: '케이스공업', lossRate: 0, qtyPricing: [], history: [{ date: '2025-01-01', action: '단가 등록', oldPrice: null, newPrice: 56250, by: '김관리' }] },
    { id: 6, itemType: '부품', itemCode: 'MOTOR-001', itemName: '모터 0.4KW', spec: '0.4KW', unit: 'EA', purchasePrice: 120000, processingCost: 10000, sellingPrice: 149500, marginRate: 15.0, validFrom: '2025-01-01', validTo: null, status: '활성', supplier: '모터공급사', lossRate: 0, qtyPricing: [], history: [{ date: '2025-01-01', action: '단가 등록', oldPrice: null, newPrice: 149500, by: '김관리' }, { date: '2025-06-01', action: '단가 변경', oldPrice: 145000, newPrice: 149500, by: '이담당' }] },
    { id: 7, itemType: '부품', itemCode: 'CTL-001', itemName: '제어기 기본형', spec: '기본형', unit: 'EA', purchasePrice: 80000, processingCost: 5000, sellingPrice: 102000, marginRate: 20.0, validFrom: '2025-01-01', validTo: null, status: '활성', supplier: '제어기공급사', lossRate: 0, qtyPricing: [], history: [] },
  ]);
  
  // 거래처별 특별단가 데이터
  const [customerPrices, setCustomerPrices] = useState([
    { id: 1, customerId: 'C001', customerName: '삼성전자', itemCode: 'GR-001', itemName: '가이드레일 130×80', unit: 'EA', basePrice: 60000, discountRate: 10, sellingPrice: 54000, validFrom: '2025-01-01', validTo: '2025-12-31', status: '활성', note: 'VIP 고객 특별가' },
    { id: 2, customerId: 'C001', customerName: '삼성전자', itemCode: 'CASE-001', itemName: '케이스 철재', unit: 'EA', basePrice: 56250, discountRate: 10, sellingPrice: 50625, validFrom: '2025-01-01', validTo: '2025-12-31', status: '활성', note: 'VIP 고객 특별가' },
    { id: 3, customerId: 'C002', customerName: 'LG전자', itemCode: 'GR-001', itemName: '가이드레일 130×80', unit: 'EA', basePrice: 60000, discountRate: 5, sellingPrice: 57000, validFrom: '2025-01-01', validTo: '2025-06-30', status: '활성', note: '계약 단가' },
    { id: 4, customerId: 'C003', customerName: '현대건설', itemCode: 'MOTOR-001', itemName: '모터 0.4KW', unit: 'EA', basePrice: 149500, discountRate: 8, sellingPrice: 137540, validFrom: '2025-03-01', validTo: null, status: '활성', note: '대량 구매 계약' },
  ]);
  
  // 탭
  const mainTabs = ['기본단가', '거래처별 단가'];
  const itemTypeTabs = ['전체', '제품', '부품', '부자재', '원자재', '소모품'];
  
  // 품목유형별 카운트
  const getTypeCount = (type) => {
    if (type === '전체') return basePrices.length;
    return basePrices.filter(p => p.itemType === type).length;
  };
  
  // 필터링
  const filteredBase = basePrices
    .filter(p => itemTypeTab === '전체' || p.itemType === itemTypeTab)
    .filter(p => 
      p.itemCode.toLowerCase().includes(search.toLowerCase()) ||
      p.itemName.includes(search) ||
      p.spec?.includes(search)
    );
  
  const filteredCustomer = customerPrices
    .filter(p => 
      p.customerName.includes(search) ||
      p.itemCode.toLowerCase().includes(search.toLowerCase()) ||
      p.itemName.includes(search)
    );
  
  // 통계
  const totalItems = basePrices.length;
  const registeredCount = basePrices.filter(p => p.status === '활성').length;
  const unregisteredCount = basePrices.filter(p => p.status === '미등록').length;
  const customerPriceCount = customerPrices.length;
  
  // 기본단가 수정 모달
  const openEditModal = (item) => {
    setSelectedItem(item);
    setModalMode('edit');
    setShowModal(true);
  };
  
  // 기본단가 상세보기
  const openDetailModal = (item) => {
    setSelectedItem(item);
    setModalMode('detail');
    setShowModal(true);
  };
  
  // 거래처별 단가 등록/수정 모달
  const openCustomerPriceModal = (item = null) => {
    setSelectedItem(item);
    setModalMode('customer');
    setShowModal(true);
  };
  
  // 기본단가 저장
  const handleSaveBasePrice = (updatedItem) => {
    setBasePrices(prev => prev.map(p => 
      p.id === updatedItem.id ? updatedItem : p
    ));
    setShowModal(false);
  };
  
  // 거래처별 단가 저장
  const handleSaveCustomerPrice = (newPrice) => {
    if (newPrice.id) {
      setCustomerPrices(prev => prev.map(p => p.id === newPrice.id ? newPrice : p));
    } else {
      setCustomerPrices(prev => [...prev, { ...newPrice, id: Math.max(...prev.map(p => p.id)) + 1 }]);
    }
    setShowModal(false);
  };
  
  // 거래처별 단가 삭제
  const handleDeleteCustomerPrice = (id) => {
    if (confirm('이 거래처 단가를 삭제하시겠습니까?')) {
      setCustomerPrices(prev => prev.filter(p => p.id !== id));
    }
  };
  
  return (
    <div className="space-y-4">
      {/* 헤더 */}
      <div className="flex justify-between items-center">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
            <DollarSign className="w-5 h-5 text-green-600" />
          </div>
          <div>
            <h2 className="text-xl font-bold text-gray-900">단가 관리</h2>
            <p className="text-sm text-gray-500">품목별 기본단가 및 거래처별 특별단가를 관리합니다</p>
          </div>
        </div>
        <div className="flex gap-2">
          <button className="text-sm text-gray-600 hover:text-gray-700 flex items-center gap-1 px-3 py-2 border rounded-lg">
            <GitBranch className="w-4 h-4" /> 품목 마스터 동기화
          </button>
          {activeTab === '거래처별 단가' && (
            <button 
              onClick={() => openCustomerPriceModal()}
              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-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">{totalItems}</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>
        <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">{registeredCount}</p>
            </div>
            <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
              <DollarSign 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">미등록</p>
              <p className="text-2xl font-bold text-red-600 mt-1">-{unregisteredCount}</p>
            </div>
            <div className="w-10 h-10 bg-red-100 rounded-lg flex items-center justify-center">
              <AlertCircle className="w-5 h-5 text-red-500" />
            </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-purple-600 mt-1">{customerPriceCount}</p>
            </div>
            <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
              <Users className="w-5 h-5 text-purple-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={activeTab === '기본단가' ? "품목코드, 품목명, 규격 검색..." : "거래처명, 품목코드, 품목명 검색..."}
            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>
      
      {/* 메인 탭 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        <div className="border-b">
          <div className="flex">
            {mainTabs.map(tab => (
              <button
                key={tab}
                onClick={() => setActiveTab(tab)}
                className={`px-6 py-3 text-sm font-medium border-b-2 transition-colors ${
                  activeTab === tab 
                    ? 'border-blue-500 text-blue-600 bg-blue-50/50' 
                    : 'border-transparent text-gray-500 hover:text-gray-700'
                }`}
              >
                {tab}
                <span className="ml-2 px-2 py-0.5 bg-gray-100 rounded-full text-xs">
                  {tab === '기본단가' ? totalItems : customerPriceCount}
                </span>
              </button>
            ))}
          </div>
        </div>
        
        {/* 기본단가 탭 */}
        {activeTab === '기본단가' && (
          <>
            {/* 품목유형 서브탭 */}
            <div className="px-4 py-2 border-b bg-gray-50">
              <div className="flex gap-4">
                {itemTypeTabs.map(tab => (
                  <button
                    key={tab}
                    onClick={() => setItemTypeTab(tab)}
                    className={`text-sm px-1 py-1 ${
                      itemTypeTab === tab 
                        ? 'text-blue-600 font-medium' 
                        : 'text-gray-500 hover:text-gray-700'
                    }`}
                  >
                    {tab} ({getTypeCount(tab)})
                  </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-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-center text-xs font-medium text-gray-500">작업</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {filteredBase.map((item, idx) => (
                    <tr key={item.id} 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">
                        <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-right text-gray-600">
                        {item.purchasePrice ? `${item.purchasePrice.toLocaleString()}원` : '-'}
                      </td>
                      <td className="px-4 py-3 text-sm text-right text-gray-600">
                        {item.processingCost ? `${item.processingCost.toLocaleString()}원` : '-'}
                      </td>
                      <td className="px-4 py-3 text-sm text-right font-medium text-gray-900">
                        {item.sellingPrice ? `${item.sellingPrice.toLocaleString()}원` : '-'}
                      </td>
                      <td className="px-4 py-3 text-center">
                        {item.marginRate ? (
                          <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs font-medium">
                            {item.marginRate.toFixed(1)}%
                          </span>
                        ) : '-'}
                      </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">
                        <div className="flex justify-center gap-1">
                          {item.status === '활성' && (
                            <button
                              onClick={() => openDetailModal(item)}
                              className="p-1 hover:bg-gray-100 rounded"
                              title="상세보기"
                            >
                              <Eye className="w-4 h-4 text-gray-500" />
                            </button>
                          )}
                          <button
                            onClick={() => openEditModal(item)}
                            className="p-1 hover:bg-gray-100 rounded"
                            title={item.status === '활성' ? '수정' : '등록'}
                          >
                            {item.status === '활성' ? (
                              <Edit3 className="w-4 h-4 text-gray-500" />
                            ) : (
                              <Plus className="w-4 h-4 text-blue-500" />
                            )}
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}
        
        {/* 거래처별 단가 탭 */}
        {activeTab === '거래처별 단가' && (
          <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-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">
                {filteredCustomer.map((item, idx) => (
                  <tr key={item.id} 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-medium text-gray-900">{item.customerName}</td>
                    <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-center text-gray-600">{item.unit}</td>
                    <td className="px-4 py-3 text-sm text-right text-gray-500">
                      {item.basePrice.toLocaleString()}원
                    </td>
                    <td className="px-4 py-3 text-center">
                      <span className="text-sm text-red-600 font-medium">-{item.discountRate}%</span>
                    </td>
                    <td className="px-4 py-3 text-sm text-right font-bold text-blue-600">
                      {item.sellingPrice.toLocaleString()}원
                    </td>
                    <td className="px-4 py-3 text-sm text-center text-gray-600">
                      <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-sm text-gray-500 max-w-32 truncate">{item.note || '-'}</td>
                    <td className="px-4 py-3 text-center">
                      <div className="flex justify-center gap-1">
                        <button
                          onClick={() => openCustomerPriceModal(item)}
                          className="p-1 hover:bg-gray-100 rounded"
                          title="수정"
                        >
                          <Edit3 className="w-4 h-4 text-gray-500" />
                        </button>
                        <button
                          onClick={() => handleDeleteCustomerPrice(item.id)}
                          className="p-1 hover:bg-red-50 rounded"
                          title="삭제"
                        >
                          <Trash2 className="w-4 h-4 text-red-400" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
                {filteredCustomer.length === 0 && (
                  <tr>
                    <td colSpan={12} className="px-4 py-8 text-center text-gray-500">
                      등록된 거래처별 단가가 없습니다.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </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">
            <X className="w-5 h-5" />
          </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">
            <X className="w-5 h-5" />
          </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">
            <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-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 }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  
  // 수주전환 슬라이드 패널 상태
  const [showConvertPanel, setShowConvertPanel] = useState(false);
  const [selectedQuote, setSelectedQuote] = useState(null);
  const [convertForm, setConvertForm] = useState({
    deliveryMethod: '상차',
    receiverName: '',
    receiverPhone: '',
    deliveryAddress: '',
    dueDate: '',
    note: '',
  });

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

  // 통계 계산
  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 handleOpenConvertPanel = (quote, e) => {
    e.stopPropagation();
    setSelectedQuote(quote);
    // 견적 정보로 기본값 설정
    setConvertForm({
      deliveryMethod: '상차',
      receiverName: quote.manager || '',
      receiverPhone: quote.contact || '',
      deliveryAddress: quote.deliveryAddress || '',
      dueDate: quote.dueDate || '',
      note: '',
    });
    setShowConvertPanel(true);
  };

  // 수주전환 실행
  const handleConvertToOrder = () => {
    if (!selectedQuote) return;
    
    // 여기서 실제 수주 생성 로직 실행
    const newOrderNo = `KD-SO-${new Date().toISOString().slice(2,10).replace(/-/g, '')}-01`;
    
    alert(`수주전환 완료!\n\n로트번호: ${newOrderNo}\n발주처: ${selectedQuote.customerName}\n현장: ${selectedQuote.siteName}\n금액: ${(selectedQuote.finalAmount || selectedQuote.totalAmount).toLocaleString()}원`);
    
    setShowConvertPanel(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>
        }
      />

      {/* 대시보드 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <DashboardCard 
          icon={Calendar} 
          title="이번 달 견적 금액" 
          value={`${(thisMonthAmount / 10000).toLocaleString()}만원`} 
          color="blue" 
        />
        <DashboardCard 
          icon={FileText} 
          title="진행중 견적 금액" 
          value={`${(progressAmount / 10000).toLocaleString()}만원`} 
          color="yellow" 
        />
        <DashboardCard 
          icon={Edit} 
          title="이번 주 신규 견적" 
          value={`${thisWeekNew}건`} 
          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">
        <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-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-center text-xs font-medium text-gray-500">액션</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map((quote) => (
              <tr 
                key={quote.id} 
                className="hover:bg-gray-50 cursor-pointer"
                onClick={() => onNavigate('quote-detail', quote)}
              >
                <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">
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-900">{quote.customerName}</span>
                    {quote.creditGrade && <CreditGradeBadge grade={quote.creditGrade} />}
                  </div>
                </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">
                  <div className="text-sm text-gray-900">{quote.productName}</div>
                  <div className="text-xs text-gray-500">{quote.qty}개</div>
                </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>
                  {quote.discountRate > 0 && (
                    <div className="text-xs text-red-500">할인 {quote.discountRate}%</div>
                  )}
                </td>
                <td className="px-4 py-3 text-sm text-gray-600">{quote.dueDate}</td>
                <td className="px-4 py-3 text-center">
                  {quote.status === '최종확정' && (
                    <Button 
                      variant="primary" 
                      size="sm"
                      onClick={(e) => handleOpenConvertPanel(quote, e)}
                    >
                      <ShoppingCart className="w-3.5 h-3.5" /> 수주전환
                    </Button>
                  )}
                  {quote.status === '수주전환' && (
                    <span className="text-xs text-gray-400">전환완료</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        
        {filtered.length === 0 && (
          <div className="text-center py-12 text-gray-500">
            검색 결과가 없습니다.
          </div>
        )}
      </div>

      {/* 수주전환 슬라이드 패널 */}
      <SlidePanel
        isOpen={showConvertPanel}
        onClose={() => setShowConvertPanel(false)}
        title="수주 전환"
        width="max-w-3xl"
      >
        {selectedQuote && (
          <div className="p-6 space-y-6">
            {/* 견적 정보 요약 (읽기 전용) */}
            <div className="bg-blue-50 rounded-xl p-5 border border-blue-100">
              <div className="flex items-center gap-2 mb-4">
                <FileText className="w-5 h-5 text-blue-600" />
                <h3 className="font-bold text-blue-900">견적 정보</h3>
                <span className="text-xs text-blue-600 bg-blue-100 px-2 py-0.5 rounded">자동 반영</span>
              </div>
              
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-gray-500">견적번호</span>
                  <p className="font-mono font-medium text-gray-900">{selectedQuote.quoteNo}</p>
                </div>
                <div>
                  <span className="text-gray-500">견적일자</span>
                  <p className="font-medium text-gray-900">{selectedQuote.quoteDate}</p>
                </div>
                <div>
                  <span className="text-gray-500">발주처</span>
                  <div className="flex items-center gap-2">
                    <p className="font-medium text-gray-900">{selectedQuote.customerName}</p>
                    {selectedQuote.creditGrade && <CreditGradeBadge grade={selectedQuote.creditGrade} />}
                  </div>
                </div>
                <div>
                  <span className="text-gray-500">현장명</span>
                  <p className="font-medium text-gray-900">{selectedQuote.siteName}</p>
                </div>
                <div>
                  <span className="text-gray-500">담당자</span>
                  <p className="font-medium text-gray-900">{selectedQuote.manager} ({selectedQuote.contact})</p>
                </div>
                <div>
                  <span className="text-gray-500">제품</span>
                  <p className="font-medium text-gray-900">{selectedQuote.productName} ({selectedQuote.qty}개)</p>
                </div>
              </div>
              
              {/* 금액 정보 */}
              <div className="mt-4 pt-4 border-t border-blue-200">
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">견적금액</span>
                  <span className="font-medium">{selectedQuote.totalAmount.toLocaleString()}원</span>
                </div>
                {selectedQuote.discountRate > 0 && (
                  <>
                    <div className="flex justify-between items-center text-red-600">
                      <span>할인 ({selectedQuote.discountRate}%)</span>
                      <span>-{selectedQuote.discountAmount?.toLocaleString()}원</span>
                    </div>
                    <div className="flex justify-between items-center mt-2 pt-2 border-t border-blue-200">
                      <span className="font-bold text-blue-900">최종금액</span>
                      <span className="text-xl font-bold text-blue-600">
                        {selectedQuote.finalAmount?.toLocaleString()}원
                      </span>
                    </div>
                  </>
                )}
                {!selectedQuote.discountRate && (
                  <div className="flex justify-between items-center mt-2 pt-2 border-t border-blue-200">
                    <span className="font-bold text-blue-900">최종금액</span>
                    <span className="text-xl font-bold text-blue-600">
                      {selectedQuote.totalAmount.toLocaleString()}원
                    </span>
                  </div>
                )}
              </div>
            </div>

            {/* 품목 목록 */}
            <div className="bg-white rounded-xl border">
              <div className="px-4 py-3 border-b bg-gray-50">
                <h3 className="font-semibold text-gray-900">품목 내역 ({selectedQuote.items?.length || 0}건)</h3>
              </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-left text-xs text-gray-500">층/위치</th>
                      <th className="px-3 py-2 text-left text-xs text-gray-500">제품명</th>
                      <th className="px-3 py-2 text-left text-xs text-gray-500">규격</th>
                      <th className="px-3 py-2 text-right text-xs text-gray-500">수량</th>
                      <th className="px-3 py-2 text-right text-xs text-gray-500">금액</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {selectedQuote.items?.map((item, idx) => (
                      <tr key={idx} className="hover:bg-gray-50">
                        <td className="px-3 py-2 text-gray-900">{item.floor} {item.location}</td>
                        <td className="px-3 py-2 text-gray-900">{item.productName}</td>
                        <td className="px-3 py-2 text-gray-600">{item.width}×{item.height}</td>
                        <td className="px-3 py-2 text-right">{item.qty}</td>
                        <td className="px-3 py-2 text-right font-medium">{item.amount?.toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* 배송 정보 입력 */}
            <div className="bg-white rounded-xl border p-5">
              <div className="flex items-center gap-2 mb-4">
                <Truck className="w-5 h-5 text-gray-600" />
                <h3 className="font-bold text-gray-900">배송 정보</h3>
                <span className="text-xs text-orange-600 bg-orange-100 px-2 py-0.5 rounded">입력 필요</span>
              </div>
              
              <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={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>
                  </select>
                </FormField>
                
                <FormField label="납기일" required>
                  <input
                    type="date"
                    className="w-full border rounded-lg px-3 py-2 text-sm"
                    value={convertForm.dueDate}
                    onChange={(e) => setConvertForm({...convertForm, dueDate: e.target.value})}
                  />
                </FormField>
                
                <FormField label="수령인">
                  <input
                    type="text"
                    className="w-full border rounded-lg px-3 py-2 text-sm"
                    placeholder="수령인 성함"
                    value={convertForm.receiverName}
                    onChange={(e) => setConvertForm({...convertForm, receiverName: 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={convertForm.receiverPhone}
                    onChange={(e) => setConvertForm({...convertForm, receiverPhone: e.target.value})}
                  />
                </FormField>
                
                <div className="col-span-2">
                  <FormField label="배송지 주소">
                    <input
                      type="text"
                      className="w-full border rounded-lg px-3 py-2 text-sm"
                      placeholder="배송지 주소를 입력하세요"
                      value={convertForm.deliveryAddress}
                      onChange={(e) => setConvertForm({...convertForm, deliveryAddress: 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={convertForm.note}
                      onChange={(e) => setConvertForm({...convertForm, note: e.target.value})}
                    />
                  </FormField>
                </div>
              </div>
            </div>

            {/* 신용등급 안내 */}
            {selectedQuote.creditGrade && (
              <div className={`rounded-xl p-4 border ${
                selectedQuote.creditGrade === 'A' ? 'bg-green-50 border-green-200' :
                selectedQuote.creditGrade === 'B' ? 'bg-yellow-50 border-yellow-200' :
                'bg-red-50 border-red-200'
              }`}>
                <div className="flex items-start gap-3">
                  <AlertCircle className={`w-5 h-5 mt-0.5 ${
                    selectedQuote.creditGrade === 'A' ? 'text-green-600' :
                    selectedQuote.creditGrade === 'B' ? 'text-yellow-600' :
                    'text-red-600'
                  }`} />
                  <div className="text-sm">
                    <p className="font-medium">
                      {selectedQuote.creditGrade === 'A' && '✅ A등급 (우량) - 자동 진행'}
                      {selectedQuote.creditGrade === 'B' && '⚠️ B등급 (관리) - 입금확인 후 출고'}
                      {selectedQuote.creditGrade === 'C' && '🚨 C등급 (위험) - 경리승인 필요'}
                    </p>
                    <p className="text-gray-600 mt-1">
                      {selectedQuote.creditGrade === 'A' && '수주 확정 후 생산지시, 출고가 자동으로 진행됩니다.'}
                      {selectedQuote.creditGrade === 'B' && '생산은 자동 진행되지만, 출고 시 입금확인이 필요합니다.'}
                      {selectedQuote.creditGrade === 'C' && '경리팀 승인 후에만 생산지시가 가능합니다. 출고 시 입금확인 필요.'}
                    </p>
                  </div>
                </div>
              </div>
            )}

            {/* 하단 버튼 */}
            <div className="flex gap-3 pt-4 border-t sticky bottom-0 bg-white pb-2">
              <Button 
                variant="secondary" 
                className="flex-1"
                onClick={() => setShowConvertPanel(false)}
              >
                취소
              </Button>
              <Button 
                variant="primary" 
                className="flex-1"
                onClick={handleConvertToOrder}
              >
                <CheckCircle className="w-4 h-4" /> 수주 전환 확정
              </Button>
            </div>
          </div>
        )}
      </SlidePanel>
    </div>
  );
};

// 견적 상세
const QuoteDetail = ({ quote, orders = [], onNavigate, onBack, onConvertToOrder, onUpdateQuote }) => {
  const [activeTab, setActiveTab] = useState('quote');
  const [showItemAddModal, setShowItemAddModal] = useState(false);
  const [newItem, setNewItem] = useState({
    category: '스크린',
    productName: '스크린 셔터 (표준형)',
    floor: '',
    location: '',
    width: '',
    height: '',
    qty: 1,
  });

  // 연관 수주 찾기
  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 tabs = [
    { id: 'quote', label: '견적서', icon: FileText },
    { id: 'calculation', label: '산출내역서', icon: Clipboard },
    { id: 'order', label: '발주서', icon: ClipboardList },
    { id: 'orderHistory', label: `수주이력 (${relatedOrders.length})`, icon: Package },
  ];

  const handleConvertToOrder = () => {
    if (quote.status === '수주전환' && pendingItems.length === 0) {
      alert('모든 품목이 이미 수주로 전환되었습니다.');
      return;
    }
    onConvertToOrder?.(quote);
    onNavigate('order-create-from-quote', quote);
  };

  // 추가분 수주전환
  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="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" />
          <div>
            <h1 className="text-xl font-bold text-gray-900">견적 상세</h1>
            <p className="text-sm text-gray-500 font-mono">{quote.quoteNo}</p>
          </div>
          <StatusBadge status={quote.status} />
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={onBack}>
            <ClipboardList className="w-4 h-4" /> 목록
          </Button>
          {/* 최초 수주전환 (확정된 견적) */}
          {quote.status === '최종확정' && relatedOrders.length === 0 && (
            <Button variant="primary" onClick={handleConvertToOrder}>
              <ShoppingCart className="w-4 h-4" /> 수주전환
            </Button>
          )}
          {/* 추가분 수주전환 */}
          {relatedOrders.length > 0 && pendingItems.length > 0 && (
            <Button variant="primary" onClick={handleConvertPendingItems}>
              <Plus className="w-4 h-4" /> 추가분 수주전환 ({pendingItems.length}건)
            </Button>
          )}
        </div>
      </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>

      {/* 기본 정보 */}
      <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">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg">
            <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">견적에 품목을 추가합니다.</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>
      )}
    </div>
  );
};

// 견적 등록
const QuoteCreate = ({ onNavigate, onBack, onSave }) => {
  const [formData, setFormData] = useState({
    quoteDate: new Date().toISOString().split('T')[0],
    createdBy: '박영업',
    customerName: '',
    siteName: '',
    manager: '',
    contact: '',
    dueDate: '',
    note: '',
  });

  const [items, setItems] = useState([{
    id: Date.now(),
    floor: '',
    location: '',
    category: '',
    productName: '',
    width: '',
    height: '',
    guideType: '백면',
    motorPower: '220V',
    controller: '단독제어',
    qty: 1,
    wingIndex: 50,
    inspectionFee: 50000,
  }]);

  // 산출된 품목 리스트 (수식 기반)
  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,
      wingIndex: 50,
      inspectionFee: 50000,
    }]);
  };

  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);
      
      // 검사비 추가
      const inspectionAmount = item.inspectionFee || 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,
        totalAmount: itemTotal + inspectionAmount,
      };
    });
    
    // items 업데이트
    setItems(calculatedItemsDetails.map(d => ({
      ...d,
      unitPrice: d.itemTotal,
      amount: d.totalAmount,
    })));
    
    setCalculatedItems(allCalculatedItems);
    setShowCalculatedItems(true);
  };

  const handleSubmit = () => {
    if (!formData.customerName) {
      alert('발주처를 선택해주세요.');
      return;
    }
    
    if (!showCalculatedItems) {
      alert('먼저 견적을 산출해주세요.');
      return;
    }

    // 견적번호 생성
    const dateCode = formData.quoteDate.replace(/-/g, '').slice(2);
    const seq = String(Math.floor(Math.random() * 99) + 1).padStart(2, '0');
    const quoteNo = `KQ#-SC-${dateCode}-${seq}`;

    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>
            <select
              value={formData.customerName}
              onChange={(e) => {
                const customer = sampleCustomers.find(c => c.name === e.target.value);
                if (customer) handleCustomerSelect(customer);
              }}
              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>
              {sampleCustomers.map(c => (
                <option key={c.id} value={c.name}>{c.name} - {c.manager}</option>
              ))}
            </select>
          </FormField>
          <FormField label="현장명">
            <select
              value={formData.siteName}
              onChange={(e) => handleChange('siteName', 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>
          </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="납기일">
            <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"
            />
          </FormField>
          <div className="col-span-2">
            <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-4">
                <span className="px-3 py-1 bg-blue-100 text-blue-700 rounded-lg text-sm font-medium">
                  견적 {idx + 1}
                </span>
                <div className="flex gap-2">
                  <button
                    onClick={() => handleDuplicateItem(item.id)}
                    className="p-1.5 hover:bg-gray-200 rounded"
                    title="복사"
                  >
                    <Copy className="w-4 h-4 text-gray-500" />
                  </button>
                  <button
                    onClick={() => handleRemoveItem(item.id)}
                    className="p-1.5 hover:bg-red-100 rounded"
                    title="삭제"
                  >
                    <Trash2 className="w-4 h-4 text-red-500" />
                  </button>
                </div>
              </div>

              <div className="grid grid-cols-3 gap-4">
                <FormField label="층수">
                  <TextInput
                    value={item.floor}
                    onChange={(val) => handleItemChange(item.id, 'floor', val)}
                    placeholder="예: 1층, B1, 지하1층"
                  />
                </FormField>
                <FormField label="부호">
                  <TextInput
                    value={item.location}
                    onChange={(val) => handleItemChange(item.id, 'location', val)}
                    placeholder="예: A, B, C"
                  />
                </FormField>
                <FormField label="제품 카테고리 (PC)" required>
                  <select
                    value={item.category}
                    onChange={(e) => handleItemChange(item.id, '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>
                    {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-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    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-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <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-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <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-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <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-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </FormField>
                <FormField label="마구리 날개지수 (WS)">
                  <input
                    type="number"
                    value={item.wingIndex}
                    onChange={(e) => handleItemChange(item.id, 'wingIndex', 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="검사비 (INSP)">
                  <input
                    type="number"
                    value={item.inspectionFee}
                    onChange={(e) => handleItemChange(item.id, 'inspectionFee', 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>

              {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 = [], onNavigate }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const { isMobile, isTablet, isDesktop } = useResponsive();

  const tabs = [
    { id: 'all', label: '전체', count: orders.length },
    { id: 'confirmed', label: '수주확정', count: orders.filter(o => o.status === '수주확정').length },
    { id: 'production', label: '생산중', count: orders.filter(o => o.status === '생산중').length },
    { id: 'complete', label: '생산완료', count: orders.filter(o => o.status === '생산완료').length },
    { id: 'shipped', label: '출하완료', count: orders.filter(o => o.status === '출하완료').length },
    { id: 'canceled', label: '취소', count: orders.filter(o => o.status === '취소').length },
  ];

  const statusFilter = {
    all: () => true,
    confirmed: (o) => o.status === '수주확정',
    production: (o) => o.status === '생산중',
    complete: (o) => o.status === '생산완료',
    shipped: (o) => o.status === '출하완료',
    canceled: (o) => o.status === '취소',
  };

  const filtered = orders
    .filter(statusFilter[activeTab])
    .filter(o => 
      o.orderNo.toLowerCase().includes(search.toLowerCase()) ||
      o.customerName.includes(search) ||
      o.siteName.includes(search)
    );

  // 출하진행률 계산 헬퍼 (출하 데이터에서 직접 조회)
  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}`;
  };

  return (
    <div className="space-y-6">
      {/* 헤더 - 반응형 */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div className="flex items-center gap-3">
          <Package className="w-6 h-6 text-blue-500" />
          <h1 className="text-xl font-bold text-gray-900">수주 목록</h1>
        </div>
        <Button variant="primary" onClick={() => onNavigate('order-create')}>
          <Plus className="w-4 h-4" /> 수주 등록
        </Button>
      </div>

      {/* 수주관리 대시보드 카드 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <DashboardCard 
          icon={DollarSign} 
          title="이번 달 수주" 
          value={`${(thisMonthAmount / 10000).toLocaleString()}만원`} 
          color="blue" 
        />
        <DashboardCard 
          icon={GitBranch} 
          title="분할 대기" 
          value={`${needSplit}건`} 
          subtitle="분할 필요"
          color="purple" 
        />
        <DashboardCard 
          icon={Factory} 
          title="생산지시 대기" 
          value={`${productionPending}건`} 
          subtitle="지시 필요"
          color="green" 
        />
        <DashboardCard 
          icon={Truck} 
          title="출하 대기" 
          value={`${shipmentPending}건`} 
          subtitle="출하진행 0%"
          color="yellow" 
        />
      </div>

      {/* 검색 */}
      <Card className="!p-4">
        <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={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-3 border-0 bg-transparent focus:outline-none text-gray-900 placeholder-gray-400"
          />
        </div>
      </Card>

      {/* 탭 필터 - 모바일에서는 스크롤 */}
      {!isMobile && (
        <TabFilter tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />
      )}

      {/* 데스크탑: 테이블 뷰 */}
      {isDesktop && (
        <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 text-xs font-medium text-gray-500 w-12">
                  <input type="checkbox" className="rounded" />
                </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>
              </tr>
            </thead>
            <tbody className="divide-y">
              {filtered.map((order, idx) => {
                // 분할 표시
                const hasSplit = order.splits?.length > 0;
                
                // 생산지시 상태
                const productionStatus = getProductionStatus(order);
                const isProductionComplete = productionStatus === '완료';
                
                // 출하진행률 (출하 데이터에서 직접 조회)
                const shipmentPercent = getShipmentPercentByOrder(order);
                
                return (
                  <tr 
                    key={order.id} 
                    className="hover:bg-gray-50 cursor-pointer"
                    onClick={() => onNavigate('order-detail', order)}
                  >
                    <td className="px-3 py-3 text-center" onClick={(e) => e.stopPropagation()}>
                      <input type="checkbox" className="rounded" />
                    </td>
                    <td className="px-3 py-3 text-center text-sm text-gray-500">
                      {orders.length - orders.indexOf(order)}
                    </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">
                      {isProductionComplete ? (
                        <span className="text-xs px-2 py-1 rounded bg-green-100 text-green-700">완료</span>
                      ) : (
                        <span className="text-sm text-gray-400">아니요</span>
                      )}
                    </td>
                    <td className="px-3 py-3">
                      <div className="flex items-center gap-2">
                        <div className="flex-1 bg-gray-200 rounded-full h-2 min-w-[60px]">
                          <div 
                            className={`h-2 rounded-full ${shipmentPercent === 100 ? 'bg-green-500' : shipmentPercent > 0 ? 'bg-blue-500' : 'bg-gray-300'}`}
                            style={{ width: `${shipmentPercent}%` }}
                          />
                        </div>
                        <span className="text-xs text-gray-500 w-8">{shipmentPercent}%</span>
                      </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,
                shipmentProgress: getShipmentPercentByOrder(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,
                shipmentProgress: getShipmentPercentByOrder(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>
      )}
    </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">
          <div className="bg-white rounded-xl w-full max-w-lg">
            <div className="flex items-center justify-between p-4 border-b">
              <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, onNavigate, onBack, onUpdate, onCreateWorkOrder }) => {
  const [activeTab, setActiveTab] = useState('basic');
  const [showSplitModal, setShowSplitModal] = useState(false);
  const [showProductionModal, setShowProductionModal] = useState(false);
  const [showProductionSheet, setShowProductionSheet] = useState(false);
  const [sheetTitle, setSheetTitle] = useState('수주서');
  const [splitForm, setSplitForm] = useState({
    splitType: '개소별',
    dueDate: '',
    selectedItems: [],
  });

  const tabs = [
    { id: 'basic', label: '기본정보', icon: FileText },
    { id: 'items', label: '제품내역', icon: Package },
    { id: 'splits', label: '분할/생산지시', icon: ClipboardList },
    { id: 'accounting', label: '회계현황', icon: CreditCard },
    { id: 'payment', label: '결제현황', icon: DollarSign },
    { id: 'documents', label: '문서발송', icon: Send },
    { id: 'history', label: '변경이력', icon: Clock },
  ];

  // 분할에 포함된 아이템 정보 연결
  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) => {
    // 신용등급 체크
    if (order.creditGrade === 'C' && order.accountingStatus !== '회계확인완료') {
      alert('C등급 거래처는 경리승인 후 생산지시가 가능합니다.\n회계현황 탭에서 경리승인을 먼저 진행해주세요.');
      setActiveTab('accounting');
      return;
    }

    // 분할에 포함된 품목 가져오기
    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 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);
      
      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: null,
        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);
      
      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: null,
        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: '대기',
            });
          }
        });
      });
    }
    
    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: null,
      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],
    });

    const processInfo = workOrders.map(wo => `• ${wo.processType}: ${wo.workOrderNo}`).join('\n');
    alert(`✅ 분할 생산지시가 완료되었습니다!\n\n분할번호: ${split.splitNo}\n\n📋 생성된 작업지시 (${workOrders.length}건):\n${processInfo}\n\n품목 수: ${splitItems.length}건\n\n[생산관리 > 작업지시 관리]에서 작업을 진행하세요.`);
  };

  // 전체 생산지시 (분할 없이 전체 품목 한번에) - 공정별 자동 분리
  const handleFullProductionOrder = () => {
    // 신용등급 체크
    if (order.creditGrade === 'C' && order.accountingStatus !== '회계확인완료') {
      alert('C등급 거래처는 경리승인 후 생산지시가 가능합니다.\n회계현황 탭에서 경리승인을 먼저 진행해주세요.');
      setShowProductionModal(false);
      setActiveTab('accounting');
      return;
    }

    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);
        
        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: null,
          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);
        
        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: null,
          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);
        
        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: null,
          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: '대기',
              });
            }
          });
        });
      }
      
      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: null,
        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);
    
    // 생산지시 완료 후 다음 단계 안내
    const nextStep = order.creditGrade === 'A' 
      ? '자동으로 생산이 진행됩니다.'
      : order.creditGrade === 'B'
      ? '생산 완료 후 입금확인 시 출고됩니다.'
      : '생산 완료 후 경리확인 및 입금확인 시 출고됩니다.';
    
    const processInfo = workOrders.map(wo => `• ${wo.processType}: ${wo.workOrderNo}`).join('\n');
    alert(`✅ 생산지시가 완료되었습니다!\n\n📋 생성된 작업지시 (${workOrders.length}건):\n${processInfo}\n\n다음 단계:\n${nextStep}\n\n[생산관리 > 작업지시 관리]에서 작업을 진행하세요.`);
  };

  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>
          <Package className="w-6 h-6 text-blue-500" />
          <div>
            <h1 className="text-xl font-bold text-gray-900">수주 상세</h1>
            <p className="text-sm text-gray-500 font-mono">{order.orderNo}</p>
          </div>
          <StatusBadge status={order.status} />
          <StatusBadge status={order.paymentStatus} />
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={() => { setSheetTitle('수주서'); setShowProductionSheet(true); }}>
            <FileText className="w-4 h-4" /> 수주서
          </Button>
          {/* 수정 버튼 - 출하완료/취소 상태가 아니면 표시 */}
          {order.status !== '출하완료' && order.status !== '취소' && (
            <Button variant="outline" onClick={() => onNavigate('order-edit', order)}>
              <Edit className="w-4 h-4" /> 수정
            </Button>
          )}
          {/* 분할 없이 전체 생산지시 (분할 있으면 분할 탭에서 개별 지시) */}
          {order.status === '수주확정' && order.splits.length === 0 && (
            <Button variant="primary" onClick={() => setShowProductionModal(true)}>
              <Factory className="w-4 h-4" /> 생산지시
            </Button>
          )}
        </div>
      </div>

      {/* 탭 */}
      <DetailTabs tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />

      {/* 기본정보 탭 */}
      {activeTab === 'basic' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <Card title="기본 정보">
            <div className="grid grid-cols-2 gap-4">
              <InfoRow label="로트번호" value={order.orderNo} />
              <InfoRow label="수주일자" value={order.orderDate} />
              <InfoRow label="견적번호" value={order.quoteNo} />
              <InfoRow label="담당자" value={order.createdBy} />
              <InfoRow label="납기일" value={order.dueDate} />
              <InfoRow label="수주상태" value={<StatusBadge status={order.status} />} />
              <InfoRow label="배송방식" value={order.deliveryMethod || '-'} />
              <InfoRow label="등록일" value={order.createdAt} />
            </div>
          </Card>

          <Card title="발주처 정보">
            <div className="grid grid-cols-2 gap-4">
              <InfoRow label="발주처" value={order.customerName} />
              <InfoRow label="현장명" value={order.siteName} />
              <InfoRow label="현장코드" value={order.siteCode} />
              <InfoRow label="담당자" value={order.manager} />
              <InfoRow label="연락처" value={order.contact} />
              <div className="col-span-2">
                <InfoRow label="배송주소" value={order.deliveryAddress} />
              </div>
            </div>
          </Card>

          <Card title="인수자 정보">
            <div className="grid grid-cols-2 gap-4">
              <InfoRow label="인수자명" value={order.receiverName} />
              <InfoRow label="연락처" value={order.receiverPhone} />
            </div>
          </Card>

          <Card title="금액 정보">
            <div className="grid grid-cols-2 gap-4">
              <InfoRow label="공급가액" value={`${Math.round(order.totalAmount / 1.1).toLocaleString()}원`} />
              <InfoRow label="부가세" value={`${Math.round(order.totalAmount - order.totalAmount / 1.1).toLocaleString()}원`} />
              <div className="col-span-2 pt-2 border-t">
                <InfoRow label="합계금액" value={<span className="text-xl font-bold text-blue-600">{order.totalAmount.toLocaleString()}원</span>} />
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* 제품내역 탭 */}
      {activeTab === 'items' && (
        <Card title={`제품 내역 (${order.items.length}건)`}>
          <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">규격(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>
                </tr>
              </thead>
              <tbody className="divide-y">
                {order.items.map((item, idx) => (
                  <tr key={item.id} 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}</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}</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>
                  </tr>
                ))}
              </tbody>
              <tfoot className="bg-gray-50">
                <tr>
                  <td colSpan={9} className="px-4 py-3 text-sm font-bold text-right">합계</td>
                  <td className="px-4 py-3 text-sm font-bold text-right text-blue-600">{order.totalAmount.toLocaleString()}원</td>
                </tr>
              </tfoot>
            </table>
          </div>
        </Card>
      )}

      {/* 분할/생산지시 탭 */}
      {activeTab === 'splits' && (
        <div className="space-y-6">
          {/* 헤더 */}
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-lg font-semibold text-gray-900">분할 관리</h3>
              <p className="text-sm text-gray-500">개소별/층별/자재별로 분할하여 출고예정일을 지정할 수 있습니다.</p>
            </div>
            {getUnassignedItems().length > 0 && (
              <Button variant="primary" onClick={() => setShowSplitModal(true)}>
                <Plus className="w-4 h-4" /> 분할 추가
              </Button>
            )}
          </div>

          {/* 잔여 품목 안내 */}
          {getUnassignedItems().length > 0 && (
            <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
              <div className="flex items-center gap-2 text-yellow-700 font-medium mb-2">
                <AlertCircle className="w-5 h-5" />
                미분할 품목 {getUnassignedItems().length}건
              </div>
              <p className="text-sm text-yellow-600">아래 품목이 아직 분할되지 않았습니다. 분할 추가 시 누락되지 않도록 확인해주세요.</p>
              <div className="mt-2 text-sm text-yellow-700">
                {getUnassignedItems().map(item => (
                  <span key={item.id} className="inline-block mr-2 px-2 py-1 bg-yellow-100 rounded">
                    {item.productCode} ({item.floor}/{item.location})
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* 분할 완료 안내 */}
          {getUnassignedItems().length === 0 && order.splits.length > 0 && (
            <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
              <div className="flex items-center gap-2 text-green-700 font-medium">
                <CheckCircle className="w-5 h-5" />
                모든 품목이 분할되었습니다.
              </div>
            </div>
          )}

          {order.splits.length > 0 ? (
            <>
              {order.splits.map(split => (
                <Card key={split.id} title={
                  <div className="flex items-center gap-2">
                    <span>{split.splitOrder}차 분할</span>
                    <span className="text-sm font-mono text-gray-500">({split.splitNo})</span>
                    {split.splitType && (
                      <span className="text-xs px-2 py-0.5 bg-gray-100 text-gray-600 rounded">{split.splitType} 분할</span>
                    )}
                  </div>
                }>
                  <div className="space-y-4">
                    {/* 상태 및 진행률 */}
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-4">
                        <StatusBadge status={split.productionStatus} />
                        <StatusBadge status={split.shipmentStatus} />
                        <span className="text-sm text-gray-500">출고예정: {split.dueDate}</span>
                      </div>
                      {split.productionOrderNo && (
                        <span className="text-sm text-gray-500">
                          작업지시: <span className="font-mono text-blue-600">{split.productionOrderNo}</span>
                        </span>
                      )}
                    </div>

                    {/* 진행률 표시 */}
                    {split.totalQty > 0 && (
                      <div className="flex items-center gap-4">
                        <div className="flex-1 bg-gray-200 rounded-full h-2">
                          <div 
                            className="bg-blue-500 h-2 rounded-full" 
                            style={{ width: `${(split.completedQty / split.totalQty) * 100}%` }}
                          />
                        </div>
                        <span className="text-sm text-gray-600">
                          {split.completedQty}/{split.totalQty} 완료
                          {split.remainingQty > 0 && (
                            <span className="text-yellow-600 ml-2">(잔여: {split.remainingQty})</span>
                          )}
                        </span>
                      </div>
                    )}

                    {/* 품목 테이블 */}
                    <table className="w-full">
                      <thead className="bg-gray-50">
                        <tr>
                          <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">
                        {getSplitItems(split).map(item => (
                          <tr key={item.id}>
                            <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>

                    {/* 액션 버튼 */}
                    <div className="flex gap-2 pt-2 border-t">
                      {!split.productionOrderNo && (
                        <Button size="sm" variant="primary" onClick={() => handleProductionOrder(split)}>
                          <Factory className="w-4 h-4" /> 생산지시
                        </Button>
                      )}
                      {split.productionStatus === '작업완료' && split.shipmentStatus !== '출하완료' && (
                        <Button size="sm" variant="success" onClick={() => onNavigate('shipment-create', { order, split })}>
                          <Truck className="w-4 h-4" /> 출하 등록
                        </Button>
                      )}
                      {split.productionOrderNo && (
                        <Button size="sm" variant="outline" onClick={() => onNavigate('work-order-detail', { workOrderNo: split.productionOrderNo })}>
                          <Eye className="w-4 h-4" /> 작업지시 보기
                        </Button>
                      )}
                    </div>
                  </div>
                </Card>
              ))}
            </>
          ) : (
            <Card>
              <div className="text-center py-8 text-gray-500">
                <ClipboardList className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                <p>분할 설정이 없습니다.</p>
                <p className="text-sm text-gray-400 mt-1">개소별/층별/자재별로 분할하여 출고예정일을 지정할 수 있습니다.</p>
                <Button variant="primary" className="mt-4" onClick={() => setShowSplitModal(true)}>
                  <Plus className="w-4 h-4" /> 분할 추가
                </Button>
              </div>
            </Card>
          )}
        </div>
      )}

      {/* 회계확인 탭 - 참고용 조회 (실제 확인은 출하관리에서) */}
      {activeTab === 'accounting' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* C등급 경리승인 카드 */}
          {order.creditGrade === 'C' && (
            <div className="lg:col-span-2">
              <Card title="경리 승인">
                <div className="space-y-4">
                  <div className={`p-4 rounded-lg border ${order.accountingStatus === '회계확인완료' ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'}`}>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        {order.accountingStatus === '회계확인완료' ? (
                          <CheckCircle className="w-6 h-6 text-green-500" />
                        ) : (
                          <AlertCircle className="w-6 h-6 text-red-500" />
                        )}
                        <div>
                          <p className="font-medium">
                            {order.accountingStatus === '회계확인완료' 
                              ? '경리 승인 완료' 
                              : '🚨 C등급 거래처 - 경리 승인 필요'}
                          </p>
                          <p className="text-sm text-gray-600">
                            {order.accountingStatus === '회계확인완료' 
                              ? `승인자: ${order.accountingConfirmedBy} (${order.accountingConfirmedAt})`
                              : '경리팀 승인 후 생산지시가 가능합니다.'}
                          </p>
                        </div>
                      </div>
                      {order.accountingStatus !== '회계확인완료' && (
                        <Button 
                          variant="primary" 
                          onClick={() => {
                            if (confirm('경리 승인을 진행하시겠습니까?\n\n승인 후 생산지시가 가능합니다.')) {
                              const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
                              onUpdate?.({
                                ...order,
                                accountingStatus: '회계확인완료',
                                accountingConfirmedBy: '회계팀 현재사용자',
                                accountingConfirmedAt: now,
                                productionHold: false,
                                changeHistory: [...(order.changeHistory || []), {
                                  id: Date.now(),
                                  changedAt: now,
                                  changeType: '경리승인',
                                  description: 'C등급 거래처 경리 승인 완료',
                                  changedBy: '회계팀 현재사용자',
                                }],
                              });
                              alert('✅ 경리 승인이 완료되었습니다.\n\n이제 생산지시가 가능합니다.');
                            }
                          }}
                        >
                          <CheckCircle className="w-4 h-4" /> 경리 승인
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
              </Card>
            </div>
          )}

          {/* 입금 현황 및 확인 */}
          <Card title="입금 현황">
            <div className="space-y-4">
              <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                <span className="text-sm text-gray-600">입금 상태</span>
                <StatusBadge status={order.paymentStatus || '미입금'} />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <InfoRow label="수주금액" value={`${order.totalAmount?.toLocaleString() || 0}원`} />
                <InfoRow label="입금액" value={`${order.paidAmount?.toLocaleString() || 0}원`} />
                <InfoRow label="잔액" value={`${((order.totalAmount || 0) - (order.paidAmount || 0)).toLocaleString()}원`} />
                <InfoRow label="입금일" value={order.paymentDate || '-'} />
              </div>
              
              {/* 입금확인 버튼 (B/C등급 또는 미입금 시) */}
              {(order.creditGrade !== 'A' || order.paymentStatus !== '전액입금') && order.paymentStatus !== '전액입금' && (
                <div className="pt-4 border-t">
                  <div className="flex items-center gap-2 p-3 mb-3 bg-yellow-50 border border-yellow-200 rounded-lg text-sm text-yellow-700">
                    <AlertCircle className="w-4 h-4" />
                    <span>
                      {order.creditGrade === 'B' || order.creditGrade === 'C' 
                        ? '입금 확인 후 출하가 가능합니다.' 
                        : '입금 현황을 업데이트할 수 있습니다.'}
                    </span>
                  </div>
                  <div className="flex gap-2">
                    <Button 
                      variant="outline" 
                      size="sm"
                      onClick={() => {
                        const amount = prompt('입금액을 입력하세요:', order.totalAmount?.toString() || '0');
                        if (amount && !isNaN(Number(amount))) {
                          const paidAmount = Number(amount);
                          const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
                          const isFullPaid = paidAmount >= (order.totalAmount || 0);
                          onUpdate?.({
                            ...order,
                            paidAmount: (order.paidAmount || 0) + paidAmount,
                            paymentStatus: isFullPaid ? '전액입금' : '일부입금',
                            paymentDate: now.split(' ')[0],
                            changeHistory: [...(order.changeHistory || []), {
                              id: Date.now(),
                              changedAt: now,
                              changeType: '입금확인',
                              description: `입금 ${paidAmount.toLocaleString()}원 확인 (${isFullPaid ? '전액입금' : '일부입금'})`,
                              changedBy: '회계팀 현재사용자',
                            }],
                          });
                          alert(`✅ 입금이 확인되었습니다.\n\n입금액: ${paidAmount.toLocaleString()}원\n상태: ${isFullPaid ? '전액입금' : '일부입금'}`);
                        }
                      }}
                    >
                      <CreditCard className="w-4 h-4" /> 입금 확인
                    </Button>
                    <Button 
                      variant="primary" 
                      size="sm"
                      onClick={() => {
                        if (confirm('전액 입금 처리하시겠습니까?')) {
                          const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
                          onUpdate?.({
                            ...order,
                            paidAmount: order.totalAmount,
                            remainingAmount: 0,
                            paymentStatus: '전액입금',
                            paymentDate: now.split(' ')[0],
                            changeHistory: [...(order.changeHistory || []), {
                              id: Date.now(),
                              changedAt: now,
                              changeType: '입금확인',
                              description: `전액 입금 확인 (${order.totalAmount?.toLocaleString()}원)`,
                              changedBy: '회계팀 현재사용자',
                            }],
                          });
                          alert('✅ 전액 입금이 확인되었습니다.\n\n이제 출하가 가능합니다.');
                        }
                      }}
                    >
                      <Check className="w-4 h-4" /> 전액입금 처리
                    </Button>
                  </div>
                </div>
              )}
              
              {order.paymentStatus === '전액입금' && (
                <div className="pt-4 border-t">
                  <div className="flex items-center gap-2 p-3 bg-green-50 border border-green-200 rounded-lg text-sm text-green-700">
                    <CheckCircle className="w-4 h-4" />
                    <span>전액 입금 완료 - 출하 가능</span>
                  </div>
                </div>
              )}
            </div>
          </Card>

          <Card title="세금계산서 현황">
            <div className="space-y-4">
              <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                <span className="text-sm text-gray-600">발행 상태</span>
                {order.taxInvoiceStatus === '발행완료' ? (
                  <span className="px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-700">✓ 발행완료</span>
                ) : order.taxInvoiceStatus === '발행대기' ? (
                  <span className="px-2 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-700">발행대기</span>
                ) : (
                  <span className="px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-500">미발행</span>
                )}
              </div>
              <div className="grid grid-cols-2 gap-4">
                <InfoRow label="발행일" value={order.taxInvoiceDate || '-'} />
                <InfoRow label="발행금액" value={order.taxInvoiceAmount ? `${order.taxInvoiceAmount.toLocaleString()}원` : '-'} />
                <InfoRow label="승인번호" value={<span className="font-mono text-sm">{order.taxInvoiceNo || '-'}</span>} />
              </div>
              {order.taxInvoiceStatus !== '발행완료' && (
                <div className="pt-4 border-t">
                  <Button variant="outline" size="sm">
                    <FileText className="w-4 h-4" /> 세금계산서 발행 요청
                  </Button>
                </div>
              )}
            </div>
          </Card>
        </div>
      )}

      {/* 결제현황 탭 */}
      {activeTab === 'payment' && (
        <Card title="결제 현황">
          <div className="space-y-4">
            <div className="grid grid-cols-3 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-xl font-bold">{order.totalAmount.toLocaleString()}원</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-xl font-bold text-green-600">{order.paymentStatus === '완납' ? order.totalAmount.toLocaleString() : Math.round(order.totalAmount * 0.3).toLocaleString()}원</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-xl font-bold text-red-600">{order.paymentStatus === '완납' ? '0' : Math.round(order.totalAmount * 0.7).toLocaleString()}원</p>
              </div>
            </div>
            <table className="w-full mt-4">
              <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-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">
                <tr>
                  <td className="px-4 py-3 text-sm">2025-01-15</td>
                  <td className="px-4 py-3 text-sm">계약금</td>
                  <td className="px-4 py-3 text-sm text-right font-medium">{Math.round(order.totalAmount * 0.3).toLocaleString()}원</td>
                  <td className="px-4 py-3 text-sm">계좌이체</td>
                  <td className="px-4 py-3 text-sm">회계팀 김회계</td>
                </tr>
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {/* 문서발송 탭 */}
      {activeTab === 'documents' && (
        <DocumentSendSection order={order} />
      )}

      {/* 변경이력 탭 */}
      {activeTab === 'history' && (
        <Card title="변경 이력">
          <div className="space-y-4">
            {/* 등록 이력 */}
            <div className="flex gap-4 p-4 bg-blue-50 rounded-lg">
              <div className="w-2 h-2 mt-2 bg-blue-500 rounded-full flex-shrink-0" />
              <div className="flex-1">
                <div className="flex items-center justify-between">
                  <span className="font-medium text-blue-700">수주 등록</span>
                  <span className="text-sm text-gray-500">{order.createdAt}</span>
                </div>
                <p className="text-sm text-gray-600 mt-1">{order.createdBy}</p>
              </div>
            </div>

            {/* 변경 이력 */}
            {order.changeHistory?.length > 0 ? (
              order.changeHistory.map(history => (
                <div key={history.id} 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.description}</p>
                    <p className="text-xs text-gray-400 mt-1">{history.changedBy}</p>
                  </div>
                </div>
              ))
            ) : (
              <div className="text-center py-4 text-gray-500">
                <p className="text-sm">추가 변경 이력이 없습니다.</p>
              </div>
            )}
          </div>
        </Card>
      )}

      {/* 분할 추가 모달 */}
      {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);
          }}
        />
      )}
    </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)
    );

  // 페이지네이션
  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 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)
  );

  const deliveryMethods = ['직접배차', '상차', '택배', '화물', '직접배송'];

  // 추가분 수주번호 생성
  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 (!formData.customerName) {
      alert('발주처를 입력해주세요.');
      return;
    }
    if (!formData.siteName) {
      alert('현장명을 입력해주세요.');
      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-${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 999) + 1).padStart(3, '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);

  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>
          <ClipboardList className="w-6 h-6 text-blue-500" />
          <div>
            <h1 className="text-xl font-bold text-gray-900">
              {isAdditional ? '추가분 수주 등록' : '수주 등록'}
            </h1>
            {isAdditional && relatedOrders.length > 0 && (
              <p className="text-sm text-gray-500">
                원 수주: <span className="font-mono text-blue-600">{relatedOrders[0]?.orderNo}</span>
              </p>
            )}
          </div>
          {isAdditional && <StatusBadge status="추가" />}
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={onBack}>취소</Button>
          <Button variant="primary" onClick={handleSubmit} disabled={!canSubmit}>
            <Check 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>
                <label className="block text-sm font-medium text-gray-700 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"
                >
                  {deliveryMethods.map(method => (
                    <option key={method} value={method}>{method}</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={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>
      ) : (
      /* ========== 일반 수주 등록 (직접 입력 기본) ========== */
      <div className="space-y-6">
        {/* 견적 불러오기 영역 */}
        <div className={`p-4 rounded-lg border-2 ${selectedQuote ? 'bg-blue-50 border-blue-300' : 'bg-gray-50 border-dashed border-gray-300'}`}>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <FileText className={`w-5 h-5 ${selectedQuote ? 'text-blue-600' : 'text-gray-400'}`} />
              {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} />
                    <span className="text-sm text-gray-500">에서 불러옴</span>
                  </div>
                  <p className="text-sm text-gray-600 mt-0.5">
                    {selectedQuote.customerName} / {selectedQuote.siteName} / {selectedQuote.totalAmount?.toLocaleString()}원
                  </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">
              {selectedQuote && (
                <Button variant="ghost" size="sm" onClick={handleClearQuote}>
                  <X className="w-4 h-4" /> 해제
                </Button>
              )}
              <Button variant={selectedQuote ? "outline" : "primary"} size="sm" onClick={() => setShowQuotePanel(true)}>
                <FileText className="w-4 h-4" /> {selectedQuote ? '변경' : '견적 선택'}
              </Button>
            </div>
          </div>
        </div>

        {/* 신용등급 안내 (견적에서 불러온 경우) */}
        {selectedQuote?.creditGrade && (
          <div className={`p-3 rounded-lg text-sm ${
            selectedQuote.creditGrade === 'A' ? 'bg-green-50 border border-green-200 text-green-800' :
            selectedQuote.creditGrade === 'B' ? 'bg-yellow-50 border border-yellow-200 text-yellow-800' :
            'bg-red-50 border border-red-200 text-red-800'
          }`}>
            <div className="flex items-center gap-2">
              {selectedQuote.creditGrade === 'A' ? (
                <><CheckCircle className="w-4 h-4" /> A등급: 자동 진행</>
              ) : selectedQuote.creditGrade === 'B' ? (
                <><AlertCircle className="w-4 h-4" /> B등급: 입금확인 후 출고</>
              ) : (
                <><AlertCircle className="w-4 h-4" /> C등급: 경리승인 필요</>
              )}
            </div>
          </div>
        )}

        {/* 기본 정보 */}
        <Card title="기본 정보">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField label="발주처" required>
              {selectedQuote ? (
                <input
                  type="text"
                  value={formData.customerName}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-700"
                  readOnly
                />
              ) : (
                <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 || '');
                  }}
                  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>
                  {initialCustomers.filter(c => c.customerType === '고객사').map(customer => (
                    <option key={customer.id} value={customer.id}>
                      {customer.customerName} ({customer.creditGrade}등급)
                    </option>
                  ))}
                </select>
              )}
            </FormField>
            <FormField label="현장명" required>
              <input
                type="text"
                value={formData.siteName}
                onChange={(e) => handleChange('siteName', 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 ${selectedQuote ? 'bg-gray-50' : ''}`}
                placeholder="현장명 입력"
                readOnly={!!selectedQuote}
              />
            </FormField>
            <FormField 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="담당자명"
              />
            </FormField>
            <FormField 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"
              />
            </FormField>
          </div>
        </Card>

        {/* 수주/배송 정보 */}
        <Card title="수주/배송 정보">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField label="수주일자" required>
              <input
                type="date"
                value={formData.orderDate}
                onChange={(e) => handleChange('orderDate', 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>
              <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"
              />
            </FormField>
            <FormField 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"
              >
                {deliveryMethods.map(method => (
                  <option key={method} value={method}>{method}</option>
                ))}
              </select>
            </FormField>
            <FormField 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="수령인 이름"
              />
            </FormField>
            <div className="md:col-span-2">
              <FormField 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"
                  placeholder="배송지 주소"
                />
              </FormField>
            </div>
            <FormField 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"
              />
            </FormField>
            <FormField label="비고">
              <input
                type="text"
                value={formData.note}
                onChange={(e) => handleChange('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"
                placeholder="특이사항"
              />
            </FormField>
          </div>
        </Card>

        {/* 품목 내역 */}
        <Card title="품목 내역">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <p className="text-sm text-gray-500">
                {selectedQuote ? '견적에서 불러온 품목입니다. 수정 가능합니다.' : '수주할 품목을 추가하세요 (상세 스펙 자동 계산)'}
              </p>
              <Button variant="outline" size="sm" onClick={handleAddItem}>
                <Plus className="w-4 h-4" /> 품목 추가
              </Button>
            </div>

            {directItems.length === 0 ? (
              <div className="text-center py-8 border-2 border-dashed rounded-lg">
                <Package className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                <p className="text-gray-500">품목이 없습니다</p>
                <p className="text-sm text-gray-400 mt-1">
                  {selectedQuote ? '견적에 품목이 없습니다.' : '품목 추가 버튼을 클릭해 상세 스펙을 입력하세요'}
                </p>
              </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 text-xs font-medium text-gray-500">No.</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 bg-green-50">오픈사이즈</th>
                      <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 bg-red-50">제작사이즈</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-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 w-20"></th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {directItems.map((item, idx) => {
                      const spec = item.productionSpec || {};
                      return (
                        <tr key={item.id} className="hover:bg-gray-50">
                          <td className="px-3 py-2">{String(idx + 1).padStart(2, '0')}</td>
                          <td className="px-3 py-2 font-medium">{item.floor} {item.location}</td>
                          <td className="px-3 py-2 bg-green-50 text-green-700">
                            {spec.openWidth?.toLocaleString()}×{spec.openHeight?.toLocaleString()}
                          </td>
                          <td className="px-3 py-2 bg-red-50 text-red-700 font-bold">
                            {spec.prodWidth?.toLocaleString()}×{spec.prodHeight?.toLocaleString()}
                          </td>
                          <td className="px-3 py-2">{spec.guideRailType}<br/><span className="text-gray-500 text-xs">({spec.guideRailSpec})</span></td>
                          <td className="px-3 py-2 text-center">{spec.shaft}"</td>
                          <td className="px-3 py-2">{spec.capacity}K</td>
                          <td className="px-3 py-2 text-right">{item.unitPrice?.toLocaleString()}</td>
                          <td className="px-3 py-2 text-right font-medium">{item.amount?.toLocaleString()}</td>
                          <td className="px-3 py-2">
                            <div className="flex gap-1">
                              <button
                                onClick={() => handleEditItem(item)}
                                className="p-1 text-blue-500 hover:bg-blue-50 rounded"
                                title="수정"
                              >
                                <Edit className="w-4 h-4" />
                              </button>
                              <button
                                onClick={() => handleRemoveItem(item.id)}
                                className="p-1 text-red-500 hover:bg-red-50 rounded"
                                title="삭제"
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                  <tfoot className="bg-gray-50">
                    <tr>
                      <td colSpan="8" className="px-3 py-3 text-right font-medium">
                        총 {directItems.length}개소 합계
                      </td>
                      <td className="px-3 py-3 text-right font-bold text-blue-600 text-lg">
                        {calculateTotal().toLocaleString()}원
                      </td>
                      <td></td>
                    </tr>
                  </tfoot>
                </table>
              </div>
            )}
          </div>
        </Card>

        {/* 품목 추가/수정 모달 */}
        {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">
                  <Package className="w-5 h-5 text-blue-600" />
                  <h3 className="font-bold">{editingItem ? '품목 수정' : '품목 추가'}</h3>
                </div>
                <button onClick={() => setShowItemModal(false)} className="p-1 hover:bg-gray-100 rounded">
                  <X className="w-5 h-5" />
                </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>
      )}

      {/* 견적 선택 슬라이드 패널 */}
      <SlidePanel
        isOpen={showQuotePanel}
        onClose={() => setShowQuotePanel(false)}
        title="견적 선택"
        size="lg"
      >
        <div className="space-y-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"
              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">
                <FileText className="w-12 h-12 mx-auto mb-2 text-gray-300" />
                <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>
      </SlidePanel>
    </div>
  );
};

// 수주 수정
const OrderEdit = ({ order, onNavigate, onBack, onSave }) => {
  const [formData, setFormData] = useState({
    dueDate: order?.dueDate || '',
    deliveryMethod: order?.deliveryMethod || '상차',
    receiverName: order?.receiverName || '',
    receiverPhone: order?.receiverPhone || '',
    deliveryAddress: order?.deliveryAddress || '',
    note: order?.note || '',
  });
  
  // 품목 목록 상태
  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 deliveryMethods = ['직접배차', '상차', '택배', '화물', '직접배송'];
  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">
        <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>
          <ClipboardList className="w-6 h-6 text-blue-500" />
          <div>
            <h1 className="text-xl font-bold text-gray-900">수주 수정</h1>
            <p className="text-sm text-gray-500 font-mono">{order.orderNo}</p>
          </div>
          <StatusBadge status={order.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>

      {/* 상태별 안내 메시지 */}
      {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="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 기본 정보 (읽기 전용) */}
        <Card title="발주처 정보">
          <div className="space-y-3">
            <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 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">{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-4">
            <FormField label="납기일" required>
              <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"
              />
            </FormField>
            <FormField 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"
              >
                {deliveryMethods.map(method => (
                  <option key={method} value={method}>{method}</option>
                ))}
              </select>
            </FormField>
            <div className="grid grid-cols-2 gap-4">
              <FormField 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"
                />
              </FormField>
              <FormField 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"
                />
              </FormField>
            </div>
            <FormField 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"
              />
            </FormField>
            <FormField 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"
              />
            </FormField>
          </div>
        </Card>
      </div>

      {/* 품목 목록 */}
      <Card 
        title={`품목 목록 (${items.length}개)`}
        action={
          canEditItems ? (
            <Button variant="outline" size="sm" onClick={handleAddItem}>
              <Plus className="w-4 h-4" /> 품목 추가
            </Button>
          ) : (
            <span className="text-xs text-gray-400">생산 시작 후 수정 불가</span>
          )
        }
      >
        <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>
            <tfoot className="bg-gray-50">
              <tr>
                <td colSpan={canEditItems ? "10" : "9"} className="px-4 py-3 text-sm font-bold text-right">합계</td>
                <td className="px-4 py-3 text-sm font-bold text-right text-blue-600">{totalAmount.toLocaleString()}원</td>
                {canEditItems && <td></td>}
              </tr>
            </tfoot>
          </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>
        )}
      </Card>

      {/* 품목 추가/수정 모달 */}
      {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">
                <X className="w-5 h-5" />
              </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>
  );
};


// ============ 작업지시 관리 ============

// 작업지시 목록
// ============ 생산관리 현황판 (관리자용) ============
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 }) => {
  const [selectedWorker, setSelectedWorker] = useState('김작업');
  const [activeTab, setActiveTab] = useState('my-tasks');
  const [showIssueModal, setShowIssueModal] = useState(false);
  const [selectedTask, setSelectedTask] = useState(null);

  const workers = ['김작업', '이작업', '박작업', '최작업', '정작업'];

  // 내 작업 목록
  const myTasks = workOrders
    .filter(wo => wo.assignee === selectedWorker && wo.status !== '작업완료')
    .sort((a, b) => {
      // 긴급 우선, 그 다음 납기일 순
      if (a.priority === '긴급' && b.priority !== '긴급') return -1;
      if (a.priority !== '긴급' && b.priority === '긴급') return 1;
      return new Date(a.dueDate) - new Date(b.dueDate);
    });

  // 완료된 작업
  const completedTasks = workOrders
    .filter(wo => wo.assignee === selectedWorker && wo.status === '작업완료')
    .slice(0, 10);

  const getPriorityColor = (priority) => {
    switch(priority) {
      case '긴급': return 'border-l-red-500 bg-red-50';
      case '일반': return 'border-l-blue-500 bg-white';
      case '낮음': return 'border-l-gray-300 bg-gray-50';
      default: return 'border-l-gray-300 bg-white';
    }
  };

  const getPriorityIcon = (priority) => {
    switch(priority) {
      case '긴급': return '🔴';
      case '일반': return '🟡';
      case '낮음': return '⚪';
      default: return '⚪';
    }
  };

  const handleStartWork = (task) => {
    onStartWork?.(task);
  };

  const handleOpenIssue = (task) => {
    setSelectedTask(task);
    setShowIssueModal(true);
  };

  return (
    <div className="space-y-4 max-w-lg mx-auto">
      {/* 헤더 */}
      <div className="flex items-center justify-between bg-white p-4 rounded-xl border">
        <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>
          <div>
            <h1 className="font-bold text-gray-900">내 작업</h1>
            <p className="text-sm text-gray-500">작업자 화면</p>
          </div>
        </div>
        <select
          value={selectedWorker}
          onChange={(e) => setSelectedWorker(e.target.value)}
          className="px-3 py-2 border rounded-lg text-sm"
        >
          {workers.map(w => (
            <option key={w} value={w}>{w}</option>
          ))}
        </select>
      </div>

      {/* 요약 카드 */}
      <div className="grid grid-cols-3 gap-3">
        <div className="bg-yellow-50 p-3 rounded-xl text-center border border-yellow-200">
          <p className="text-2xl font-bold text-yellow-600">{myTasks.filter(t => t.status === '작업대기').length}</p>
          <p className="text-xs text-yellow-700">대기중</p>
        </div>
        <div className="bg-blue-50 p-3 rounded-xl text-center border border-blue-200">
          <p className="text-2xl font-bold text-blue-600">{myTasks.filter(t => t.status === '작업중').length}</p>
          <p className="text-xs text-blue-700">작업중</p>
        </div>
        <div className="bg-red-50 p-3 rounded-xl text-center border border-red-200">
          <p className="text-2xl font-bold text-red-600">{myTasks.filter(t => t.priority === '긴급').length}</p>
          <p className="text-xs text-red-700">긴급</p>
        </div>
      </div>

      {/* 탭 */}
      <div className="flex bg-gray-100 p-1 rounded-lg">
        <button
          onClick={() => setActiveTab('my-tasks')}
          className={`flex-1 py-2 text-sm font-medium rounded-lg transition-colors ${
            activeTab === 'my-tasks' ? 'bg-white shadow text-gray-900' : 'text-gray-500'
          }`}
        >
          할 일 ({myTasks.length})
        </button>
        <button
          onClick={() => setActiveTab('completed')}
          className={`flex-1 py-2 text-sm font-medium rounded-lg transition-colors ${
            activeTab === 'completed' ? 'bg-white shadow text-gray-900' : 'text-gray-500'
          }`}
        >
          완료 ({completedTasks.length})
        </button>
      </div>

      {/* 작업 목록 */}
      <div className="space-y-3">
        {activeTab === 'my-tasks' ? (
          myTasks.length === 0 ? (
            <div className="text-center py-12 text-gray-500">
              <CheckCircle className="w-16 h-16 mx-auto mb-3 text-green-400" />
              <p className="font-medium">모든 작업 완료!</p>
              <p className="text-sm">배정된 작업이 없습니다.</p>
            </div>
          ) : (
            myTasks.map(task => (
              <div 
                key={task.id}
                className={`p-4 rounded-xl border-l-4 ${getPriorityColor(task.priority)} border shadow-sm`}
              >
                <div className="flex items-start justify-between mb-3">
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <span>{getPriorityIcon(task.priority)}</span>
                      <span className="font-mono text-sm text-blue-600">{task.workOrderNo}</span>
                      <StatusBadge status={task.status} />
                    </div>
                    <p className="text-sm font-medium text-gray-900">{task.customerName}</p>
                    <p className="text-xs text-gray-500">{task.siteName}</p>
                  </div>
                  <span className={`px-2 py-1 rounded text-xs font-medium ${
                    task.processType === '스크린' ? 'bg-blue-100 text-blue-700' :
                    task.processType === '슬랫' ? 'bg-purple-100 text-purple-700' :
                    'bg-orange-100 text-orange-700'
                  }`}>
                    {task.processType}
                  </span>
                </div>

                {/* 작업 정보 */}
                <div className="grid grid-cols-2 gap-2 text-xs text-gray-600 mb-3 p-2 bg-gray-50 rounded-lg">
                  <div>
                    <span className="text-gray-400">납기:</span> {task.dueDate}
                  </div>
                  <div>
                    <span className="text-gray-400">수량:</span> {task.totalQty}EA
                  </div>
                </div>

                {/* 공정 진행 상태 */}
                {task.stepStatus && (
                  <div className="flex gap-1 mb-3 overflow-x-auto pb-1">
                    {Object.entries(task.stepStatus).map(([step, stepData], idx) => {
                      const stepStatus = typeof stepData === 'object' ? stepData.status : stepData;
                      return (
                        <span 
                          key={step}
                          className={`flex-shrink-0 px-2 py-1 rounded text-xs ${
                            stepStatus === '완료' ? 'bg-green-100 text-green-700' :
                            stepStatus === '진행중' ? 'bg-blue-100 text-blue-700' :
                            'bg-gray-100 text-gray-500'
                          }`}
                        >
                          {step}
                        </span>
                      );
                    })}
                  </div>
                )}

                {/* 현재 공정 표시 */}
                {task.status === '작업중' && task.currentStep && (
                  <div className="mb-3 p-2 bg-blue-100 rounded-lg">
                    <div className="flex items-center justify-between">
                      <span className="text-xs text-blue-700">현재 공정</span>
                      <span className="text-sm font-medium text-blue-800">{task.currentStep}</span>
                    </div>
                  </div>
                )}

                {/* 버튼 */}
                <div className="flex gap-2">
                  {task.status === '작업대기' && (
                    <Button 
                      variant="primary" 
                      size="sm" 
                      className="flex-1"
                      onClick={() => handleStartWork(task)}
                    >
                      <Play className="w-4 h-4" /> 작업 시작
                    </Button>
                  )}
                  {task.status === '작업중' && (
                    <>
                      <Button 
                        variant="primary" 
                        size="sm" 
                        className="flex-1"
                        onClick={() => onNavigate('work-result-create', task)}
                      >
                        <CheckCircle className="w-4 h-4" /> 실적 입력
                      </Button>
                    </>
                  )}
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={() => handleOpenIssue(task)}
                  >
                    <AlertCircle className="w-4 h-4" />
                  </Button>
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={() => onNavigate('work-order-detail', task)}
                  >
                    <Eye className="w-4 h-4" />
                  </Button>
                </div>
              </div>
            ))
          )
        ) : (
          completedTasks.length === 0 ? (
            <div className="text-center py-12 text-gray-500">
              <Clock className="w-16 h-16 mx-auto mb-3 text-gray-300" />
              <p>완료된 작업이 없습니다.</p>
            </div>
          ) : (
            completedTasks.map(task => (
              <div 
                key={task.id}
                className="p-4 bg-green-50 rounded-xl border border-green-200"
              >
                <div className="flex items-center justify-between">
                  <div>
                    <span className="font-mono text-sm text-green-700">{task.workOrderNo}</span>
                    <p className="text-sm text-gray-700">{task.customerName}</p>
                  </div>
                  <CheckCircle className="w-6 h-6 text-green-500" />
                </div>
              </div>
            ))
          )
        )}
      </div>

      {/* 이슈 보고 모달 */}
      {showIssueModal && selectedTask && (
        <IssueReportModal
          task={selectedTask}
          onClose={() => setShowIssueModal(false)}
          onSubmit={(issue) => {
            onReportIssue?.(selectedTask, issue);
            setShowIssueModal(false);
          }}
        />
      )}
    </div>
  );
};

// 이슈 보고 모달
const IssueReportModal = ({ task, onClose, onSubmit }) => {
  const [issueType, setIssueType] = useState('');
  const [description, setDescription] = useState('');

  const issueTypes = [
    { id: 'defect', label: '불량품 발생', icon: '⚠️' },
    { id: 'no-stock', label: '재고 없음', icon: '📦' },
    { id: 'delay', label: '일정 지연', icon: '⏰' },
    { id: 'equipment', label: '설비 문제', icon: '🔧' },
    { id: 'other', label: '기타', icon: '📝' },
  ];

  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'
                  }`}
                >
                  <span className="text-lg">{type.icon}</span>
                  <p className="text-sm font-medium mt-1">{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 [activeTab, setActiveTab] = useState('info');
  const [priority, setPriority] = useState('일반');
  const [assignees, setAssignees] = useState({
    '스크린': '',
    '슬랫': '',
    '절곡': '',
  });
  const [note, setNote] = useState('');

  // 품목에서 카테고리 추정
  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),
      estimatedTime: screenItems.length * 120, // 분
    });
  }

  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),
      estimatedTime: slatItems.length * 90,
    });
  }

  // 절곡 공정 (항상 필요)
  previewWorkOrders.push({
    processType: '절곡',
    workOrderNo: `KD-PL-${dateCode}-${String(seqNum++).padStart(2, '0')}`,
    steps: ['절단', '절곡', '중간검사', '포장'],
    itemCount: items.length,
    totalQty: items.length,
    estimatedTime: items.length * 60,
  });

  // 자재 소요량 계산
  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 }] },
      ],
    },
  };

  const tabs = [
    { id: 'info', label: '기본정보', icon: FileText },
    { id: 'preview', label: '작업지시 미리보기', icon: ClipboardList },
    { id: 'material', label: '자재 소요량', icon: Box },
    { id: 'screen', label: '스크린 품목', icon: Package },
    { id: 'motor', label: '모터/전장품', icon: Zap },
    { id: 'bom', label: '절곡물 BOM', icon: Layers },
  ];

  // 담당자 목록
  const workerOptions = ['', '김생산', '이작업', '박조립', '최검수', '정포장'];

  // 백면형 가이드레일 전개도 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 totalEstimatedTime = previewWorkOrders.reduce((sum, wo) => sum + wo.estimatedTime, 0);
  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>
              <div className="px-3 py-1 bg-purple-100 rounded-full text-purple-700">
                예상 <span className="font-medium">{Math.ceil(totalEstimatedTime / 60)}</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">
              <X className="w-5 h-5" />
            </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 md:grid-cols-2 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 className="p-4 bg-blue-50 rounded-lg">
                <h4 className="font-medium text-blue-900 mb-3 flex items-center gap-2">
                  <ClipboardList className="w-4 h-4" /> 생산지시 후 진행 프로세스
                </h4>
                <div className="flex items-center gap-2 text-sm flex-wrap">
                  <span className="px-2 py-1 bg-purple-100 text-purple-700 rounded font-medium">생산지시</span>
                  <ChevronRight className="w-4 h-4 text-gray-400" />
                  <span className="px-2 py-1 bg-indigo-100 text-indigo-700 rounded font-medium">생산중</span>
                  <ChevronRight className="w-4 h-4 text-gray-400" />
                  <span className="px-2 py-1 bg-cyan-100 text-cyan-700 rounded font-medium">생산완료</span>
                  <ChevronRight className="w-4 h-4 text-gray-400" />
                  {order.creditGrade !== 'A' && (
                    <>
                      <span className="px-2 py-1 bg-yellow-100 text-yellow-700 rounded font-medium">입금확인</span>
                      <ChevronRight className="w-4 h-4 text-gray-400" />
                    </>
                  )}
                  <span className="px-2 py-1 bg-green-100 text-green-700 rounded font-medium">출하</span>
                </div>
              </div>
            </div>
          )}

          {/* 작업지시 미리보기 탭 */}
          {activeTab === 'preview' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <h3 className="font-bold text-lg flex items-center gap-2">
                  <ClipboardList className="w-5 h-5 text-blue-500" />
                  생성될 작업지시 ({previewWorkOrders.length}건)
                </h3>
                <div className="text-sm text-gray-500">
                  총 예상 작업시간: <span className="font-bold text-blue-600">{Math.floor(totalEstimatedTime / 60)}시간 {totalEstimatedTime % 60}분</span>
                </div>
              </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 className="flex items-center justify-between text-sm pt-3 border-t">
                        <span className="text-gray-500">예상 작업시간</span>
                        <span className="font-medium">{Math.floor(wo.estimatedTime / 60)}시간 {wo.estimatedTime % 60}분</span>
                      </div>

                      {/* 담당자 배정 */}
                      <div>
                        <p className="text-xs text-gray-500 mb-1">담당자 배정</p>
                        <select
                          value={assignees[wo.processType]}
                          onChange={(e) => setAssignees(prev => ({ ...prev, [wo.processType]: e.target.value }))}
                          className="w-full px-3 py-2 border rounded-lg text-sm"
                        >
                          {workerOptions.map(w => (
                            <option key={w} value={w}>{w || '미지정'}</option>
                          ))}
                        </select>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* 옵션 설정 */}
              <Card title="생산지시 옵션">
                <div className="grid grid-cols-1 md:grid-cols-2 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 md:grid-cols-2 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 md:grid-cols-2 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}
            disabled={order.creditGrade === 'C' && order.accountingStatus !== '회계확인완료'}
          >
            <Factory className="w-4 h-4" /> 생산지시 확정 ({previewWorkOrders.length}건)
          </Button>
        </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 || '',
      },
      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">
              <X className="w-5 h-5" />
            </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-64 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">검토</div>
                    <div className="flex-1 text-center border-r border-gray-600 py-1">승인</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"></div>
                    <div className="flex-1 h-12"></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>
  );
};

// ============ 작업일지 시스템 (공정별) ============

// 공정별 작업일지 초기 데이터 생성
const createWorkLogData = (workOrder, order, processType) => {
  const items = workOrder?.items || order?.items || [];
  const itemCount = items.length;
  const process = processType || workOrder?.processType || '절곡';
  
  // 공통 헤더 정보
  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 === '스크린') {
    return {
      ...baseData,
      department: '스크린 생산부서',
      // 원단 정보
      fabric: {
        type: '망사', // 망사, 암막 등
        color: '',
        width: '',
        inputLotNo: '',
      },
      // 작업 내역
      workItems: [
        { id: 1, step: '원단절단', material: '스크린원단', inputLotNo: '', qty: itemCount, unit: 'EA', note: '' },
        { id: 2, step: '미싱', material: '미싱실', inputLotNo: '', qty: null, unit: 'M', note: '' },
        { id: 3, step: '앤드락작업', material: '앤드락', inputLotNo: '', qty: itemCount * 2, unit: 'EA', note: '' },
        { id: 4, step: '하단바조립', material: '하단바', inputLotNo: '', qty: itemCount, unit: 'EA', note: '' },
        { id: 5, step: '중간검사', material: '-', inputLotNo: '', qty: itemCount, unit: 'EA', note: '' },
        { id: 6, step: '포장', material: '포장재', inputLotNo: '', 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 === '슬랫') {
    return {
      ...baseData,
      department: '슬랫 생산부서',
      // 코일 정보
      coil: {
        type: '알루미늄', // 알루미늄, 스틸 등
        color: '',
        thickness: '',
        inputLotNo: '',
      },
      // 작업 내역
      workItems: [
        { id: 1, step: '코일절단', material: '슬랫코일', inputLotNo: '', 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: '', length: '', qty: itemCount * 2, unit: 'EA', note: '' },
        { id: 5, step: '조립', material: '연결부품', inputLotNo: '', length: '', qty: null, unit: 'SET', note: '' },
        { id: 6, step: '포장', material: '포장재', inputLotNo: '', 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
      },
    };
  }

  // 절곡 공정 작업일지 (기존)
  return {
    ...baseData,
    department: '절곡 생산부서',
    productCode: items[0]?.productCode || 'KWE01',
    productType: '와이어',
    finishType: 'SUS마감',
    railType: '벽면형(120·70)',
    
    // 1. 벽면형 (120·70)
    guideRail: [
      { id: 1, name: '마감재', material: 'EGI1.15T', inputLotNo: '', 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: '', 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: '', spec: 'L:2,438', qty: null },
      { id: 6, name: '하부BASE', material: 'EGI1.55T', inputLotNo: '', spec: '하부BASE 130·80', qty: itemCount * 2 },
    ],
    
    // 2. 하단마감재 [60·40]
    bottomFinish: [
      { id: 1, name: '하단마감재', material: 'EGI1.55T', inputLotNo: '', 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: '', 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: '', 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: '', rows: [
        { spec: 'L:4,000', qty: Math.ceil(itemCount * 1.3) },
        { spec: 'L:3,000', qty: Math.ceil(itemCount * 0.6) },
      ]},
    ],
    
    // 3. 케이스 [500*330]
    caseBox: {
      spec: '500*330',
      material: 'EGI1.55T',
      inputLotNo: '',
      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. 연기차단재
    smokeBarrier: {
      rail: { 
        name: '레일용[W50]', 
        material: 'EG0.8T + 화이바 글라스 코팅직물', 
        inputLotNo: '', 
        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: '', 
        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 || createWorkLogData(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">
            <X className="w-5 h-5" />
          </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-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>
          )}

          {/* 품목상세 */}
          {activeSection === 'items' && (
            <Card title="품목별 상세">
              <table className="w-full text-sm">
                <thead className="bg-blue-50">
                  <tr>
                    <th className="px-2 py-2 text-center">No</th>
                    <th className="px-2 py-2 text-left">층</th>
                    <th className="px-2 py-2 text-left">부호</th>
                    <th className="px-2 py-2 text-right">폭(W)</th>
                    <th className="px-2 py-2 text-right">높이(H)</th>
                    <th className="px-2 py-2 text-right">수량</th>
                    <th className="px-2 py-2 text-left">원단LOT</th>
                    <th className="px-2 py-2 text-left">제품LOT</th>
                    <th className="px-2 py-2 text-center">검사</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {data.itemDetails.map((item, idx) => (
                    <tr key={item.id}>
                      <td className="px-2 py-2 text-center text-gray-500">{item.id}</td>
                      <td className="px-2 py-2">{item.floor}</td>
                      <td className="px-2 py-2">{item.location}</td>
                      <td className="px-2 py-2 text-right">{item.width}</td>
                      <td className="px-2 py-2 text-right">{item.height}</td>
                      <td className="px-2 py-2 text-right">{item.qty}</td>
                      <td className="px-2 py-2">
                        <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-24 px-2 py-1 border rounded text-xs font-mono"
                        />
                      </td>
                      <td className="px-2 py-2">
                        <input
                          type="text"
                          value={item.productLotNo}
                          onChange={(e) => {
                            const newItems = [...data.itemDetails];
                            newItems[idx].productLotNo = e.target.value;
                            setData({...data, itemDetails: newItems});
                          }}
                          placeholder="LOT"
                          className="w-24 px-2 py-1 border rounded text-xs font-mono"
                        />
                      </td>
                      <td className="px-2 py-2">
                        <select
                          value={item.inspectionResult}
                          onChange={(e) => {
                            const newItems = [...data.itemDetails];
                            newItems[idx].inspectionResult = e.target.value;
                            setData({...data, itemDetails: newItems});
                          }}
                          className={`w-full px-2 py-1 border rounded text-xs ${
                            item.inspectionResult === '합격' ? 'bg-green-50 text-green-700' :
                            item.inspectionResult === '불합격' ? 'bg-red-50 text-red-700' : ''
                          }`}
                        >
                          <option value="">-</option>
                          <option value="합격">합격</option>
                          <option value="불합격">불합격</option>
                        </select>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </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 || createWorkLogData(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">
            <X className="w-5 h-5" />
          </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-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>
          )}

          {/* 절단내역 */}
          {activeSection === 'cutting' && (
            <Card title="절단 내역">
              <table className="w-full text-sm">
                <thead className="bg-purple-50">
                  <tr>
                    <th className="px-4 py-2 text-left">길이</th>
                    <th className="px-4 py-2 text-right">수량 (EA)</th>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {data.cuttingDetails.map((item, idx) => (
                    <tr key={item.id}>
                      <td className="px-4 py-2 font-medium">{item.length}</td>
                      <td className="px-4 py-2">
                        <input
                          type="number"
                          value={item.qty || ''}
                          onChange={(e) => {
                            const newItems = [...data.cuttingDetails];
                            newItems[idx].qty = e.target.value ? parseInt(e.target.value) : null;
                            setData({...data, cuttingDetails: newItems});
                          }}
                          className="w-24 px-2 py-1 border rounded text-right float-right"
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div className="mt-4 p-3 bg-gray-50 rounded-lg text-sm text-gray-600">
                * 절단 후 총 수량: {data.cuttingDetails.reduce((sum, item) => sum + (item.qty || 0), 0)} EA
              </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 || createWorkLogData(workOrder, order, '절곡'));
  const [activeSection, setActiveSection] = useState('header');

  const sections = [
    { id: 'header', 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">
            <X className="w-5 h-5" />
          </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-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>
          )}

          {/* 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>
  );
};

// 작업일지 출력용 시트
const WorkLogSheet = ({ workOrder, order, workLog, onClose }) => {
  const printRef = React.useRef(null);
  const processType = workOrder?.processType || workLog?.processType || '절곡';
  const data = workLog || createWorkLogData(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 '절곡 생산부서';
      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">
            작업일지 출력
            <span className={`text-sm px-2 py-1 rounded ${
              processType === '스크린' ? 'bg-blue-100 text-blue-700' :
              processType === '슬랫' ? 'bg-purple-100 text-purple-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">
              <X className="w-5 h-5" />
            </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 text-2xl font-bold border-2 border-black" style={{ width: '60%' }}>
                    작 업 일 지
                  </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">판매/전진</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' :
              '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 === '스크린' && (
              <>
                {/* 원단정보 */}
                <table className="mb-4">
                  <tbody>
                    <tr>
                      <td className="border border-black w-20 text-center bg-blue-50 font-bold">원단유형</td>
                      <td className="border border-black">{data.fabric?.type}</td>
                      <td className="border border-black w-20 text-center bg-blue-50 font-bold">색상</td>
                      <td className="border border-black">{data.fabric?.color}</td>
                      <td className="border border-black w-20 text-center bg-blue-50 font-bold">폭(mm)</td>
                      <td className="border border-black">{data.fabric?.width}</td>
                      <td className="border border-black w-20 text-center bg-blue-50 font-bold">입고LOT</td>
                      <td className="border border-black font-mono">{data.fabric?.inputLotNo}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 작업내역 */}
                <div className="text-sm font-bold mb-1">1. 작업 내역</div>
                <table className="mb-4 text-xs">
                  <thead>
                    <tr className="bg-blue-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">단위</th>
                      <th className="border border-black">비고</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.workItems?.map((item, idx) => (
                      <tr key={idx} className={item.step === '중간검사' ? 'bg-yellow-50' : ''}>
                        <td className="border border-black font-medium">{item.step}</td>
                        <td className="border border-black">{item.material}</td>
                        <td className="border border-black font-mono">{item.inputLotNo}</td>
                        <td className="border border-black font-bold">{item.qty || ''}</td>
                        <td className="border border-black">{item.unit}</td>
                        <td className="border border-black">{item.note}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* 생산실적 */}
                <table className="mt-4">
                  <tbody>
                    <tr>
                      <td rowSpan="2" className="border border-black w-32 text-center bg-blue-100 font-bold">생산 실적</td>
                      <td className="border border-black text-center bg-gray-50">총 생산</td>
                      <td className="border border-black text-center bg-green-50">양품</td>
                      <td className="border border-black text-center bg-red-50">불량</td>
                      <td className="border border-black text-center bg-gray-50">불량유형</td>
                    </tr>
                    <tr>
                      <td className="border border-black text-center h-8 font-bold">{data.productionResult?.totalProduced || ''}</td>
                      <td className="border border-black text-center font-bold text-green-700">{data.productionResult?.goodQty || ''}</td>
                      <td className="border border-black text-center font-bold text-red-700">{data.productionResult?.defectQty || ''}</td>
                      <td className="border border-black text-center">{data.productionResult?.defectType || ''}</td>
                    </tr>
                  </tbody>
                </table>
              </>
            )}

            {/* 슬랫 공정 내용 */}
            {processType === '슬랫' && (
              <>
                {/* 코일정보 */}
                <table className="mb-4">
                  <tbody>
                    <tr>
                      <td className="border border-black w-20 text-center bg-purple-50 font-bold">코일유형</td>
                      <td className="border border-black">{data.coil?.type}</td>
                      <td className="border border-black w-20 text-center bg-purple-50 font-bold">색상</td>
                      <td className="border border-black">{data.coil?.color}</td>
                      <td className="border border-black w-20 text-center bg-purple-50 font-bold">두께</td>
                      <td className="border border-black">{data.coil?.thickness}</td>
                      <td className="border border-black w-20 text-center bg-purple-50 font-bold">입고LOT</td>
                      <td className="border border-black font-mono">{data.coil?.inputLotNo}</td>
                    </tr>
                  </tbody>
                </table>

                {/* 절단내역 */}
                <div className="text-sm font-bold mb-1">1. 절단 내역</div>
                <table className="mb-4 text-xs">
                  <thead>
                    <tr className="bg-purple-50">
                      <th className="border border-black">길이</th>
                      <th className="border border-black">수량 (EA)</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.cuttingDetails?.map((item, idx) => (
                      <tr key={idx}>
                        <td className="border border-black">{item.length}</td>
                        <td className="border border-black font-bold">{item.qty || ''}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* 작업내역 */}
                <div className="text-sm font-bold mb-1">2. 작업 내역</div>
                <table className="mb-4 text-xs">
                  <thead>
                    <tr className="bg-purple-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">단위</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.workItems?.map((item, idx) => (
                      <tr key={idx} className={item.step === '중간검사' ? 'bg-yellow-50' : ''}>
                        <td className="border border-black font-medium">{item.step}</td>
                        <td className="border border-black">{item.material}</td>
                        <td className="border border-black font-mono">{item.inputLotNo}</td>
                        <td className="border border-black font-bold">{item.qty || ''}</td>
                        <td className="border border-black">{item.unit}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* 생산실적 */}
                <table className="mt-4">
                  <tbody>
                    <tr>
                      <td rowSpan="2" className="border border-black w-32 text-center bg-purple-100 font-bold">생산 실적</td>
                      <td className="border border-black text-center bg-green-50">양품</td>
                      <td className="border border-black text-center bg-red-50">불량</td>
                      <td className="border border-black text-center bg-yellow-50">총 중량(kg)</td>
                    </tr>
                    <tr>
                      <td className="border border-black text-center h-8 font-bold text-green-700">{data.productionResult?.goodQty || ''}</td>
                      <td className="border border-black text-center font-bold text-red-700">{data.productionResult?.defectQty || ''}</td>
                      <td className="border border-black text-center font-bold">{data.productionResult?.totalWeight || ''}</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?.map((item, idx) => (
                      <tr key={idx}>
                        <td className="border border-black text-left pl-2">
                          <span className="text-red-500">①</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">{item.qty || ''}</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>
              </>
            )}

            {/* 비고 (공통) */}
            <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 = [], onClose, onSubmit }) => {
  const [selectedMaterial, setSelectedMaterial] = useState(null);
  const [qty, setQty] = useState(0);
  const [lotNo, setLotNo] = useState('');
  const [inputBy, setInputBy] = useState(workOrder?.assignee || '');
  const [note, setNote] = useState('');

  // 공정별 필요 자재 매핑
  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'],
      '절곡': ['BND-MAT-001', 'BND-MAT-002', 'BND-MAT-003'],
    };
    const codes = mapping[workOrder?.processType] || [];
    return inventory.filter(m => codes.includes(m.materialCode));
  };

  const processMaterials = getProcessMaterials();

  const generateLotNo = () => {
    const dateCode = new Date().toISOString().slice(2, 10).replace(/-/g, '');
    return `MAT-${dateCode}-${String(Math.floor(Math.random() * 999) + 1).padStart(3, '0')}`;
  };

  const handleSubmit = () => {
    if (!selectedMaterial) {
      alert('자재를 선택해주세요.');
      return;
    }
    if (qty <= 0) {
      alert('투입 수량을 입력해주세요.');
      return;
    }
    if (qty > selectedMaterial.stock) {
      alert(`재고가 부족합니다.\n\n현재고: ${selectedMaterial.stock} ${selectedMaterial.unit}`);
      return;
    }
    if (!lotNo) {
      alert('LOT 번호를 입력하거나 자동생성해주세요.');
      return;
    }
    onSubmit?.(selectedMaterial.materialCode, qty, lotNo, inputBy, note);
  };

  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-2xl overflow-hidden max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-4 border-b sticky top-0 bg-white">
          <div className="flex items-center gap-2">
            <Box className="w-5 h-5 text-blue-600" />
            <h2 className="text-lg font-bold">투입자재 등록</h2>
          </div>
          <button onClick={onClose} className="p-1 hover:bg-gray-100 rounded">
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="p-6 space-y-6">
          {/* 작업지시 정보 */}
          <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">{workOrder?.processType}</p>
            </div>
            <div>
              <p className="text-gray-500">발주처</p>
              <p className="font-medium">{workOrder?.customerName}</p>
            </div>
            <div>
              <p className="text-gray-500">현장명</p>
              <p className="font-medium">{workOrder?.siteName}</p>
            </div>
          </div>

          {/* 자재 선택 */}
          <div className="space-y-4">
            <h3 className="font-medium text-gray-900">투입할 자재 선택</h3>
            <div className="grid grid-cols-1 gap-3 max-h-60 overflow-y-auto">
              {processMaterials.map(material => (
                <div 
                  key={material.id} 
                  onClick={() => {
                    setSelectedMaterial(material);
                    setQty(Math.min(10, material.stock)); // 기본값
                  }}
                  className={`p-4 border rounded-lg cursor-pointer transition-all ${
                    selectedMaterial?.id === material.id 
                      ? 'border-blue-500 bg-blue-50' 
                      : 'hover:border-blue-300'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium">{material.materialName}</p>
                      <p className="text-sm text-gray-500 font-mono">{material.materialCode}</p>
                    </div>
                    <div className="text-right">
                      <p className={`text-sm font-medium ${material.stock < material.minStock ? 'text-red-600' : 'text-green-600'}`}>
                        재고: {material.stock} {material.unit}
                      </p>
                      <p className="text-xs text-gray-500">위치: {material.location}</p>
                    </div>
                  </div>
                </div>
              ))}
              {processMaterials.length === 0 && (
                <div className="text-center py-8 text-gray-500">
                  해당 공정에 사용 가능한 자재가 없습니다.
                </div>
              )}
            </div>
          </div>

          {selectedMaterial && (
            <>
              {/* 투입 정보 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">투입 수량 *</label>
                  <div className="flex items-center gap-2">
                    <input 
                      type="number" 
                      value={qty}
                      onChange={(e) => setQty(Number(e.target.value))}
                      min={1}
                      max={selectedMaterial.stock}
                      className="flex-1 px-3 py-2 border rounded-lg"
                    />
                    <span className="text-sm text-gray-500">{selectedMaterial.unit}</span>
                  </div>
                  <p className="text-xs text-gray-500 mt-1">최대: {selectedMaterial.stock} {selectedMaterial.unit}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">투입 LOT *</label>
                  <div className="flex items-center gap-2">
                    <input 
                      type="text" 
                      value={lotNo}
                      onChange={(e) => setLotNo(e.target.value)}
                      className="flex-1 px-3 py-2 border rounded-lg font-mono"
                      placeholder="LOT 번호"
                    />
                    <Button variant="outline" size="sm" onClick={() => setLotNo(generateLotNo())}>
                      자동생성
                    </Button>
                  </div>
                </div>
              </div>

              {/* 투입자 정보 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">투입자</label>
                <input 
                  type="text" 
                  value={inputBy}
                  onChange={(e) => setInputBy(e.target.value)}
                  className="w-full px-3 py-2 border rounded-lg"
                  placeholder="투입자명"
                />
              </div>

              {/* 비고 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">비고</label>
                <textarea 
                  value={note}
                  onChange={(e) => setNote(e.target.value)}
                  className="w-full px-3 py-2 border rounded-lg"
                  rows={2}
                  placeholder="특이사항 입력"
                />
              </div>
            </>
          )}
        </div>

        <div className="flex gap-2 p-4 border-t bg-gray-50 sticky bottom-0">
          <Button variant="outline" className="flex-1" onClick={onClose}>
            취소
          </Button>
          <Button 
            variant="primary" 
            className="flex-1" 
            onClick={handleSubmit}
            disabled={!selectedMaterial}
          >
            <Check className="w-4 h-4" /> 투입 등록
          </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 WorkOrderList = ({ workOrders, onNavigate }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [processFilter, setProcessFilter] = useState('all');

  const tabs = [
    { id: 'all', label: '전체', count: workOrders.length },
    { id: 'waiting', label: '작업대기', count: workOrders.filter(w => w.status === '작업대기').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,
    waiting: (w) => w.status === '작업대기',
    working: (w) => w.status === '작업중',
    complete: (w) => w.status === '작업완료',
  };

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

  return (
    <div className="space-y-6">
      <PageHeader 
        icon={ClipboardList} 
        title="작업지시 목록"
        actions={
          <Button variant="primary" onClick={() => onNavigate('work-order-create')}>
            <Plus className="w-4 h-4" /> 작업지시 등록
          </Button>
        }
      />

      {/* 대시보드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <DashboardCard icon={ClipboardList} title="전체 작업지시" value={`${workOrders.length}건`} color="blue" />
        <DashboardCard icon={Clock} title="작업대기" value={`${workOrders.filter(w => w.status === '작업대기').length}건`} color="yellow" />
        <DashboardCard icon={Factory} title="작업중" value={`${workOrders.filter(w => w.status === '작업중').length}건`} color="purple" />
        <DashboardCard icon={CheckCircle} title="작업완료" value={`${workOrders.filter(w => w.status === '작업완료').length}건`} color="green" />
      </div>

      {/* 검색 + 공정 필터 */}
      <div className="flex gap-4">
        <div className="flex-1">
          <SearchInput 
            placeholder="작업지시번호, 발주처, 현장명 검색..." 
            value={search} 
            onChange={setSearch} 
          />
        </div>
        <select
          value={processFilter}
          onChange={(e) => setProcessFilter(e.target.value)}
          className="px-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          {processTypes.map(p => (
            <option key={p} value={p}>{p === '전체' ? '공정 전체' : p}</option>
          ))}
        </select>
      </div>

      <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">우선순위</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>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map((wo, idx) => (
              <tr 
                key={wo.id} 
                className="hover:bg-gray-50 cursor-pointer"
                onClick={() => onNavigate('work-order-detail', wo)}
              >
                <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-blue-600">{wo.workOrderNo}</td>
                <td className="px-4 py-3">
                  <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium
                    ${wo.processType === '스크린' ? 'bg-blue-100 text-blue-700' : ''}
                    ${wo.processType === '슬랫' ? 'bg-purple-100 text-purple-700' : ''}
                    ${wo.processType === '절곡' ? 'bg-orange-100 text-orange-700' : ''}
                  `}>
                    {wo.processType}
                  </span>
                </td>
                <td className="px-4 py-3 text-sm font-mono text-gray-600">{wo.orderNo}</td>
                <td className="px-4 py-3 text-sm text-gray-900">{wo.orderDate}</td>
                <td className="px-4 py-3"><StatusBadge status={wo.status} /></td>
                <td className="px-4 py-3"><StatusBadge status={wo.priority} /></td>
                <td className="px-4 py-3 text-sm text-gray-900">{wo.customerName}</td>
                <td className="px-4 py-3 text-sm text-gray-900">{wo.siteName}</td>
                <td className="px-4 py-3">
                  <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>
                </td>
                <td className="px-4 py-3 text-sm text-gray-900">{wo.dueDate}</td>
                <td className="px-4 py-3 text-sm text-gray-500">{wo.assignee || '-'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// 작업지시 등록
const WorkOrderCreate = ({ orders, onNavigate, onBack, onSave }) => {
  const [selectedOrder, setSelectedOrder] = useState(null);
  const [selectedSplit, setSelectedSplit] = useState(null);
  const [formData, setFormData] = useState({
    processType: '스크린',
    dueDate: '',
    priority: '일반',
    assignee: '',
    note: '',
  });

  // 생산지시 가능한 수주 (회계확인완료 상태)
  const availableOrders = orders.filter(o => 
    o.accountingStatus === '회계확인완료' || o.accountingStatus === '입금확인'
  );

  const processTypes = ['스크린', '슬랫', '절곡'];
  const priorities = ['긴급', '일반', '낮음'];
  const workers = ['김작업', '이작업', '박작업', '최작업', '정작업'];

  const handleOrderSelect = (order) => {
    setSelectedOrder(order);
    setSelectedSplit(null);
    setFormData(prev => ({
      ...prev,
      dueDate: order.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 (!selectedOrder) {
      alert('수주를 선택해주세요.');
      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 (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,
      }));
    }

    // 공정별 작업단계 설정
    const getStepStatus = (processType) => {
      const steps = {
        '스크린': ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'],
        '슬랫': ['코일절단', '중간검사', '미미작업', '포장'],
        '절곡': ['절단', '절곡', '중간검사', '포장'],
      };
      
      const stepStatus = {};
      (steps[processType] || steps['스크린']).forEach(step => {
        stepStatus[step] = { status: '대기' };
      });
      return stepStatus;
    };

    const newWorkOrder = {
      id: Date.now(),
      workOrderNo,
      orderNo: selectedOrder.orderNo,
      splitNo: selectedSplit?.splitNo || null,
      orderDate: new Date().toISOString().split('T')[0],
      processType: formData.processType,
      customerName: selectedOrder.customerName,
      siteName: selectedOrder.siteName,
      dueDate: formData.dueDate,
      status: '작업대기',
      priority: formData.priority,
      assignee: formData.assignee,
      totalQty: items.reduce((sum, item) => sum + item.qty, 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,
    };

    onSave?.(newWorkOrder);
    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>
          <Factory className="w-6 h-6 text-purple-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 lg:grid-cols-2 gap-6">
        {/* 수주 선택 */}
        <Card title="수주 선택">
          <div className="space-y-4">
            <p className="text-sm text-gray-500">생산지시할 수주를 선택합니다. (회계확인 완료된 수주만 표시)</p>
            
            {availableOrders.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <ClipboardList className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                <p>생산지시 가능한 수주가 없습니다.</p>
                <p className="text-sm mt-1">회계확인이 완료된 수주만 생산지시할 수 있습니다.</p>
              </div>
            ) : (
              <div className="space-y-3 max-h-80 overflow-y-auto">
                {availableOrders.map(order => (
                  <div
                    key={order.id}
                    onClick={() => handleOrderSelect(order)}
                    className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
                      selectedOrder?.id === order.id 
                        ? 'border-purple-500 bg-purple-50' 
                        : 'border-gray-200 hover:border-purple-300'
                    }`}
                  >
                    <div className="flex items-center justify-between mb-2">
                      <span className="font-mono text-purple-600 font-medium">{order.orderNo}</span>
                      <StatusBadge status={order.status} />
                    </div>
                    <div className="flex items-center justify-between text-sm text-gray-600">
                      <span>{order.customerName}</span>
                      <span>{order.siteName}</span>
                    </div>
                    <div className="text-sm text-gray-500 mt-1">
                      납기: {order.dueDate} / 품목: {order.items?.length || 0}건
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* 분할 선택 */}
            {selectedOrder && selectedOrder.splits?.length > 0 && (
              <div className="mt-4 pt-4 border-t">
                <p className="text-sm font-medium text-gray-700 mb-3">분할 선택 (선택사항)</p>
                <div className="space-y-2">
                  <div
                    onClick={() => handleSplitSelect(null)}
                    className={`p-3 border rounded-lg cursor-pointer ${
                      !selectedSplit ? 'border-purple-500 bg-purple-50' : 'border-gray-200 hover:border-purple-300'
                    }`}
                  >
                    <span className="text-sm">전체 (분할 없음)</span>
                  </div>
                  {selectedOrder.splits.map(split => (
                    <div
                      key={split.id}
                      onClick={() => handleSplitSelect(split)}
                      className={`p-3 border rounded-lg cursor-pointer ${
                        selectedSplit?.id === split.id 
                          ? 'border-purple-500 bg-purple-50' 
                          : 'border-gray-200 hover:border-purple-300'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <span className="font-mono text-sm text-purple-600">{split.splitNo}</span>
                        <StatusBadge status={split.productionStatus || '미지시'} />
                      </div>
                      <div className="text-xs text-gray-500 mt-1">
                        {split.splitType} / 품목 {split.itemIds?.length || 0}건 / 납기: {split.dueDate}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </Card>

        {/* 작업지시 정보 */}
        <Card title="작업지시 정보">
          <div className="space-y-4">
            {selectedOrder ? (
              <>
                <div className="p-4 bg-purple-50 rounded-lg mb-4">
                  <div className="flex items-center gap-2 mb-2">
                    <CheckCircle className="w-5 h-5 text-purple-600" />
                    <span className="font-medium text-purple-800">선택된 수주</span>
                  </div>
                  <p className="font-mono text-purple-600">{selectedOrder.orderNo}</p>
                  <p className="text-sm text-purple-700">{selectedOrder.customerName} / {selectedOrder.siteName}</p>
                  {selectedSplit && (
                    <p className="text-sm text-purple-600 mt-1">분할: {selectedSplit.splitNo}</p>
                  )}
                </div>

                <FormField label="공정구분" required>
                  <select
                    value={formData.processType}
                    onChange={(e) => handleChange('processType', 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>
                </FormField>

                <FormField label="납기일" required>
                  <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-purple-500"
                  />
                </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="담당자">
                  <select
                    value={formData.assignee}
                    onChange={(e) => handleChange('assignee', 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"
                  >
                    <option value="">담당자 선택</option>
                    {workers.map(w => (
                      <option key={w} value={w}>{w}</option>
                    ))}
                  </select>
                </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"
                    placeholder="특이사항이나 메모를 입력하세요"
                  />
                </FormField>
              </>
            ) : (
              <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>
        </Card>
      </div>
    </div>
  );
};

// 작업지시 수정
const WorkOrderEdit = ({ workOrder, onNavigate, onBack, onSave }) => {
  const [formData, setFormData] = useState({
    dueDate: workOrder?.dueDate || '',
    priority: workOrder?.priority || '일반',
    assignee: workOrder?.assignee || '',
    note: workOrder?.note || '',
  });

  const priorities = ['긴급', '일반', '낮음'];
  const workers = ['김작업', '이작업', '박작업', '최작업', '정작업'];

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleSubmit = () => {
    onSave?.({
      ...workOrder,
      ...formData,
    });
    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 lg:grid-cols-2 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>
              <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-purple-500"
              />
            </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="담당자">
              <select
                value={formData.assignee}
                onChange={(e) => handleChange('assignee', 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"
              >
                <option value="">담당자 선택</option>
                {workers.map(w => (
                  <option key={w} value={w}>{w}</option>
                ))}
              </select>
            </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="작업 품목" className="lg:col-span-2">
          <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>
    </div>
  );
};

// 작업지시 상세
const WorkOrderDetail = ({ workOrder, workResults, orders, inventory = [], onNavigate, onBack, onUpdate, onUpdateOrder, onUseMaterial }) => {
  const [activeTab, setActiveTab] = useState('basic');
  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 [workLogData, setWorkLogData] = useState(null);
  const [currentStep, setCurrentStep] = useState(null);
  const [assignee, setAssignee] = useState(workOrder.assignee || '');

  // 해당 작업지시의 수주 정보 찾기
  const relatedOrder = orders?.find(o => o.orderNo === workOrder.orderNo);

  const workers = ['김작업', '이작업', '박작업', '최작업', '정작업'];
  const inspectors = ['이검사', '최품질', '김검사'];

  // 모든 공정에 작업일지 탭 추가
  const tabs = [
    { id: 'basic', label: '기본정보', icon: FileText },
    { id: 'process', label: '공정진행', icon: ClipboardList },
    { id: 'items', label: '작업품목', icon: Package },
    { id: 'bom', label: 'BOM/자재', icon: Box },
    { id: 'worklog', label: '작업일지', icon: Clipboard },
    { id: 'results', label: '작업실적', icon: BarChart3 },
    { id: 'issues', label: '이슈보고', icon: AlertCircle },
  ];

  // 해당 작업지시의 실적 필터링
  const relatedResults = workResults.filter(r => r.workOrderNo === workOrder.workOrderNo);

  // 공정 단계 정보
  const getProcessSteps = () => {
    const steps = {
      '스크린': ['원단절단', '미싱', '앤드락작업', '중간검사', '포장'],
      '슬랫': ['코일절단', '중간검사', '미미작업', '포장'],
      '절곡': ['절단', '절곡', '중간검사', '포장'],
    };
    return steps[workOrder.processType] || [];
  };

  // 단계 상태 아이콘
  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 (!assignee) {
      alert('작업자를 선택해주세요.');
      return;
    }
    onUpdate?.({
      ...workOrder,
      assignee: assignee,
    });
    setShowAssignModal(false);
    alert(`✅ 작업자 "${assignee}"님이 배정되었습니다.`);
  };

  // 작업 시작 핸들러
  const handleStartWork = () => {
    if (!workOrder.assignee) {
      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[출하관리]에서 출하 진행이 가능합니다.`);
  };

  // 샘플 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="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>
          <ClipboardList className="w-6 h-6 text-blue-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>
          <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium
            ${workOrder.processType === '스크린' ? 'bg-blue-100 text-blue-700' : ''}
            ${workOrder.processType === '슬랫' ? 'bg-purple-100 text-purple-700' : ''}
            ${workOrder.processType === '절곡' ? 'bg-orange-100 text-orange-700' : ''}
          `}>
            {workOrder.processType}
          </span>
          <StatusBadge status={workOrder.status} />
          <StatusBadge status={workOrder.priority} />
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={() => setShowMaterialCheck(true)}>
            <Box className="w-4 h-4" /> 재고확인
          </Button>
          <Button variant="outline" onClick={() => setShowProductionSheet(true)}>
            <Printer className="w-4 h-4" /> 작업지시서
          </Button>
          
          {/* 작업자 배정 */}
          {!workOrder.assignee && workOrder.status === '작업대기' && (
            <Button variant="outline" onClick={() => setShowAssignModal(true)}>
              <User className="w-4 h-4" /> 작업자 배정
            </Button>
          )}
          
          {/* 작업 시작 */}
          {workOrder.status === '작업대기' && (
            <Button variant="primary" onClick={handleStartWork}>
              <Factory className="w-4 h-4" /> 작업시작
            </Button>
          )}
          
          {/* 공정 진행 */}
          {workOrder.status === '작업중' && getNextActionStep() && (
            <Button 
              variant="success" 
              onClick={() => {
                const next = getNextActionStep();
                setCurrentStep(next.step);
                setShowStepModal(true);
              }}
            >
              <CheckCircle className="w-4 h-4" /> {getNextActionStep().step} {getNextActionStep().action === 'complete' ? '완료' : '시작'}
            </Button>
          )}

          {/* 출고구역 이동 */}
          {workOrder.status === '작업완료' && !workOrder.movedToShippingArea && (
            <Button variant="primary" onClick={handleMoveToShipping}>
              <Truck className="w-4 h-4" /> 출고구역 이동
            </Button>
          )}
        </div>
      </div>

      {/* 이슈 경고 배너 */}
      {workOrder.issues?.length > 0 && workOrder.issues.some(i => i.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>미처리 이슈 {workOrder.issues.filter(i => i.status !== '처리완료').length}건</strong> - 확인이 필요합니다.</span>
        </div>
      )}

      {/* 출고구역 이동 완료 배너 */}
      {workOrder.movedToShippingArea && (
        <div className="flex items-center gap-2 p-4 bg-green-50 border border-green-200 rounded-lg text-sm text-green-700">
          <CheckCircle className="w-5 h-5" />
          <span><strong>출고구역 이동 완료</strong> - {workOrder.movedToShippingAreaAt}</span>
        </div>
      )}

      <DetailTabs tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />

      {/* 기본정보 탭 */}
      {activeTab === 'basic' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <Card title="작업지시 정보">
            <div className="grid grid-cols-2 gap-4">
              <InfoRow label="작업지시번호" value={workOrder.workOrderNo} />
              <InfoRow label="지시일자" value={workOrder.orderDate} />
              <InfoRow label="공정 구분" value={workOrder.processType} />
              <InfoRow label="작업상태" value={<StatusBadge status={workOrder.status} />} />
              <InfoRow label="우선순위" value={<StatusBadge status={workOrder.priority} />} />
              <InfoRow label="납기일" value={workOrder.dueDate} />
              <InfoRow label="작업자" value={
                workOrder.assignee ? (
                  <span className="font-medium text-blue-600">{workOrder.assignee}</span>
                ) : (
                  <button 
                    onClick={() => setShowAssignModal(true)}
                    className="text-sm text-orange-600 hover:underline"
                  >
                    + 배정하기
                  </button>
                )
              } />
              <InfoRow label="등록자" value={workOrder.createdBy} />
              {workOrder.startedAt && <InfoRow label="작업시작" value={workOrder.startedAt} />}
              {workOrder.completedAt && <InfoRow label="작업완료" value={workOrder.completedAt} />}
            </div>
          </Card>

          <Card title="수주 정보">
            <div className="grid grid-cols-2 gap-4">
              <InfoRow label="로트번호" value={
                <button className="text-blue-600 hover:underline font-mono">{workOrder.orderNo}</button>
              } />
              <InfoRow label="분할번호" value={workOrder.splitNo || '전체'} />
              <InfoRow label="발주처" value={workOrder.customerName} />
              <InfoRow label="현장명" value={workOrder.siteName} />
            </div>
          </Card>

          <Card title="진행 현황" className="lg:col-span-2">
            <div className="grid grid-cols-5 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">{workOrder.totalQty}</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">{workOrder.completedQty}</p>
              </div>
              <div className="bg-yellow-50 rounded-lg p-4 text-center">
                <p className="text-sm text-gray-500 mb-1">잔여수량</p>
                <p className="text-2xl font-bold text-yellow-600">{workOrder.totalQty - workOrder.completedQty}</p>
              </div>
              <div className={`rounded-lg p-4 text-center ${workOrder.currentStep ? 'bg-purple-50' : 'bg-gray-50'}`}>
                <p className="text-sm text-gray-500 mb-1">현재 공정</p>
                <p className={`text-lg font-bold ${workOrder.currentStep ? 'text-purple-600' : 'text-gray-400'}`}>
                  {workOrder.currentStep || '대기'}
                </p>
              </div>
              <div className={`rounded-lg p-4 text-center ${workOrder.movedToShippingArea ? 'bg-green-50' : 'bg-gray-50'}`}>
                <p className="text-sm text-gray-500 mb-1">출고구역</p>
                <p className={`text-lg font-bold ${workOrder.movedToShippingArea ? 'text-green-600' : 'text-gray-400'}`}>
                  {workOrder.movedToShippingArea ? '이동완료' : '대기'}
                </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">
                  {workOrder.totalQty > 0 ? Math.round((workOrder.completedQty / workOrder.totalQty) * 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: `${workOrder.totalQty > 0 ? (workOrder.completedQty / workOrder.totalQty) * 100 : 0}%` }}
                />
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* 공정진행 탭 */}
      {activeTab === 'process' && (
        <div className="space-y-6">
          <Card title={`${workOrder.processType} 공정 진행 현황`}>
            <div className="space-y-4">
              {/* 공정 단계 타임라인 */}
              <div className="relative">
                {getProcessSteps().map((step, idx) => {
                  const stepStatus = workOrder.stepStatus?.[step] || { status: '대기' };
                  const isLast = idx === getProcessSteps().length - 1;
                  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 gap-4 pb-6 relative">
                      {/* 연결선 */}
                      {!isLast && (
                        <div className={`absolute left-2.5 top-7 w-0.5 h-full -translate-x-1/2
                          ${stepStatus.status === '완료' ? 'bg-green-300' : 'bg-gray-200'}
                        `} />
                      )}
                      
                      {/* 아이콘 */}
                      <div className="flex-shrink-0 z-10">
                        {getStepIcon(stepStatus.status)}
                      </div>
                      
                      {/* 내용 */}
                      <div className={`flex-1 p-4 rounded-lg ${
                        stepStatus.status === '완료' ? 'bg-green-50 border border-green-200' :
                        stepStatus.status === '진행중' ? 'bg-blue-50 border border-blue-200' :
                        'bg-gray-50 border border-gray-200'
                      }`}>
                        <div className="flex items-center justify-between mb-2">
                          <span className="font-medium">{step}</span>
                          <div className="flex items-center gap-2">
                            <span className={`text-xs px-2 py-0.5 rounded ${
                              stepStatus.status === '완료' ? 'bg-green-100 text-green-700' :
                              stepStatus.status === '진행중' ? 'bg-blue-100 text-blue-700' :
                              'bg-gray-100 text-gray-500'
                            }`}>
                              {stepStatus.status}
                            </span>
                            
                            {/* 공정 시작 버튼 */}
                            {canStart && (
                              <Button size="sm" variant="outline" onClick={() => handleStepStart(step)}>
                                시작
                              </Button>
                            )}
                            
                            {/* 공정 완료 버튼 */}
                            {canComplete && (
                              <Button 
                                size="sm" 
                                variant="primary" 
                                onClick={() => {
                                  setCurrentStep(step);
                                  setShowStepModal(true);
                                }}
                              >
                                완료
                              </Button>
                            )}
                          </div>
                        </div>
                        
                        {stepStatus.status !== '대기' && (
                          <div className="text-sm text-gray-600 space-y-1">
                            {stepStatus.worker && <p>작업자: {stepStatus.worker}</p>}
                            {stepStatus.inspector && <p>검사자: {stepStatus.inspector}</p>}
                            {stepStatus.startedAt && <p>시작: {stepStatus.startedAt}</p>}
                            {stepStatus.completedAt && <p>완료: {stepStatus.completedAt}</p>}
                            {stepStatus.result && (
                              <p>결과: <span className={stepStatus.result === '합격' ? 'text-green-600 font-medium' : 'text-red-600 font-medium'}>{stepStatus.result}</span></p>
                            )}
                            {stepStatus.approvedBy && <p>승인: {stepStatus.approvedBy}</p>}
                            {stepStatus.labelInfo && (
                              <p className="mt-2 p-2 bg-white rounded text-xs">
                                <span className="text-gray-500">라벨정보:</span> {stepStatus.labelInfo}
                              </p>
                            )}
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </Card>

          {/* 중간검사 상세 */}
          {workOrder.stepStatus?.['중간검사']?.status !== '대기' && (
            <Card title="중간검사 상세">
              <div className="grid grid-cols-2 gap-4">
                <InfoRow label="검사자" value={workOrder.stepStatus?.['중간검사']?.inspector || '-'} />
                <InfoRow label="검사결과" value={
                  workOrder.stepStatus?.['중간검사']?.result ? (
                    <span className={`font-medium ${workOrder.stepStatus['중간검사'].result === '합격' ? 'text-green-600' : 'text-red-600'}`}>
                      {workOrder.stepStatus['중간검사'].result}
                    </span>
                  ) : '-'
                } />
                <InfoRow label="승인자" value={workOrder.stepStatus?.['중간검사']?.approvedBy || '-'} />
                <InfoRow label="완료일시" value={workOrder.stepStatus?.['중간검사']?.completedAt || '-'} />
              </div>
            </Card>
          )}

          {/* 포장 라벨 정보 */}
          {workOrder.stepStatus?.['포장']?.status === '완료' && (
            <Card title="포장 라벨 정보">
              <div className="p-4 bg-yellow-50 border-2 border-dashed border-yellow-300 rounded-lg">
                <div className="text-center">
                  <p className="text-lg font-bold">{workOrder.customerName}</p>
                  <p className="text-sm text-gray-600">{workOrder.siteName}</p>
                  <div className="mt-2 py-2 border-t border-yellow-300">
                    <p className="font-mono text-xl">{workOrder.stepStatus['포장'].labelInfo || '1층 A-01,A-02 / 1차분'}</p>
                  </div>
                  <p className="text-xs text-gray-500 mt-2">LOT: {workOrder.items?.[0]?.lotNo || 'LOT-XXXXXXXX-XXX'}</p>
                </div>
              </div>
            </Card>
          )}
        </div>
      )}

      {/* 작업품목 탭 */}
      {activeTab === 'items' && (
        <Card title={`작업 품목 (${workOrder.items.length}건)`}>
          <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">규격(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">제품LOT</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={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>
                  <td className="px-4 py-3 text-sm font-mono text-blue-600">{item.lotNo || '-'}</td>
                  <td className="px-4 py-3 text-sm font-mono text-gray-500">{item.materialLotNo || '-'}</td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="mt-4 p-4 bg-gray-50 rounded-lg text-sm text-gray-600">
            * 작업자는 작업 시작 시 투입되는 원자재의 LOT번호를 입력합니다.<br />
            * 제품 LOT번호는 작업 완료 시 자동 생성됩니다.
          </div>
        </Card>
      )}

      {/* 작업실적 탭 */}
      {activeTab === 'results' && (
        <div className="space-y-6">
          {/* 실적 요약 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="bg-blue-50 rounded-lg p-4 text-center">
              <p className="text-sm text-blue-600 mb-1">지시수량</p>
              <p className="text-2xl font-bold text-blue-700">{workOrder.totalQty}</p>
            </div>
            <div className="bg-green-50 rounded-lg p-4 text-center">
              <p className="text-sm text-green-600 mb-1">완료수량</p>
              <p className="text-2xl font-bold text-green-700">
                {relatedResults.reduce((sum, r) => sum + (r.goodQty || r.completedQty || 0), 0)}
              </p>
            </div>
            <div className="bg-red-50 rounded-lg p-4 text-center">
              <p className="text-sm text-red-600 mb-1">불량수량</p>
              <p className="text-2xl font-bold text-red-700">
                {relatedResults.reduce((sum, r) => sum + (r.defectQty || 0), 0)}
              </p>
            </div>
            <div className="bg-yellow-50 rounded-lg p-4 text-center">
              <p className="text-sm text-yellow-600 mb-1">잔여수량</p>
              <p className="text-2xl font-bold text-yellow-700">
                {workOrder.totalQty - relatedResults.reduce((sum, r) => sum + (r.goodQty || r.completedQty || 0), 0)}
              </p>
            </div>
          </div>

          <Card title={`작업일지 (${relatedResults.length}건)`}>
            <div className="flex justify-between items-center mb-4">
              <p className="text-sm text-gray-500">작업 실적을 등록하고 관리합니다.</p>
              {workOrder.status === '작업중' && (
                <Button variant="primary" onClick={() => onNavigate('work-result-input', workOrder)}>
                  <Plus className="w-4 h-4" /> 작업일지 등록
                </Button>
              )}
            </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">품목</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-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-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">
                  {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">{result.productName}</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-blue-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-sm font-mono text-blue-600">{result.lotNo}</td>
                      <td className="px-4 py-3 text-center">
                        {result.inspectionCompleted || result.inspectionPassed ? (
                          <CheckCircle className="w-5 h-5 text-green-500 mx-auto" />
                        ) : (
                          <XCircle className="w-5 h-5 text-gray-300 mx-auto" />
                        )}
                      </td>
                      <td className="px-4 py-3 text-center">
                        {result.packingCompleted ? (
                          <CheckCircle className="w-5 h-5 text-green-500 mx-auto" />
                        ) : (
                          <XCircle className="w-5 h-5 text-gray-300 mx-auto" />
                        )}
                      </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-100 rounded text-gray-500 hover:text-blue-600">
                            <Eye className="w-4 h-4" />
                          </button>
                          <button className="p-1 hover:bg-gray-100 rounded text-gray-500 hover:text-blue-600">
                            <Edit className="w-4 h-4" />
                          </button>
                        </div>
                      </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>
                {workOrder.status === '작업중' && (
                  <Button 
                    variant="outline" 
                    className="mt-4"
                    onClick={() => onNavigate('work-result-input', workOrder)}
                  >
                    <Plus className="w-4 h-4" /> 첫 작업일지 등록하기
                  </Button>
                )}
              </div>
            )}
          </Card>
        </div>
      )}

      {/* 이슈보고 탭 */}
      {activeTab === 'issues' && (
        <div className="space-y-6">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-medium">이슈 보고 현황</h3>
            <Button variant="outline">
              <Plus className="w-4 h-4" /> 이슈 등록
            </Button>
          </div>

          {workOrder.issues?.length > 0 ? (
            <div className="space-y-4">
              {workOrder.issues.map(issue => (
                <Card key={issue.id}>
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-3">
                      <div className={`p-2 rounded-lg ${
                        issue.issueType === '불량품발생' ? 'bg-red-100' :
                        issue.issueType === '재고없음' ? 'bg-orange-100' :
                        issue.issueType === '일정지연' ? 'bg-yellow-100' :
                        'bg-gray-100'
                      }`}>
                        <AlertCircle className={`w-5 h-5 ${
                          issue.issueType === '불량품발생' ? 'text-red-600' :
                          issue.issueType === '재고없음' ? 'text-orange-600' :
                          issue.issueType === '일정지연' ? 'text-yellow-600' :
                          'text-gray-600'
                        }`} />
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <StatusBadge status={issue.issueType} />
                          <span className={`text-xs px-2 py-0.5 rounded ${
                            issue.status === '처리완료' ? 'bg-green-100 text-green-700' :
                            issue.status === '처리중' ? 'bg-blue-100 text-blue-700' :
                            'bg-red-100 text-red-700'
                          }`}>
                            {issue.status}
                          </span>
                        </div>
                        <p className="mt-2 text-sm text-gray-700">{issue.description}</p>
                        <p className="mt-1 text-xs text-gray-500">
                          보고: {issue.reportedBy} | {issue.reportedAt}
                        </p>
                      </div>
                    </div>
                  </div>
                  
                  {issue.status === '처리완료' && (
                    <div className="mt-4 pt-4 border-t">
                      <p className="text-sm text-green-700">
                        <strong>처리내용:</strong> {issue.resolution}
                      </p>
                      <p className="text-xs text-gray-500 mt-1">
                        처리: {issue.resolvedBy} | {issue.resolvedAt}
                      </p>
                    </div>
                  )}
                </Card>
              ))}
            </div>
          ) : (
            <Card>
              <div className="text-center py-8 text-gray-500">
                <CheckCircle className="w-12 h-12 mx-auto mb-3 text-green-300" />
                <p>보고된 이슈가 없습니다.</p>
              </div>
            </Card>
          )}

          <Card title="이슈 유형 안내">
            <div className="grid grid-cols-3 gap-4 text-sm">
              <div className="p-3 bg-red-50 rounded-lg">
                <p className="font-medium text-red-700">불량품 발생</p>
                <p className="text-red-600 text-xs mt-1">작업 중 불량품이 발생한 경우</p>
              </div>
              <div className="p-3 bg-orange-50 rounded-lg">
                <p className="font-medium text-orange-700">재고 없음</p>
                <p className="text-orange-600 text-xs mt-1">필요 자재/부품 재고 부족</p>
              </div>
              <div className="p-3 bg-yellow-50 rounded-lg">
                <p className="font-medium text-yellow-700">일정 지연</p>
                <p className="text-yellow-600 text-xs mt-1">납기일 준수가 어려운 경우</p>
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* 작업일지 탭 (공정별) */}
      {activeTab === 'worklog' && (
        <div className="space-y-6">
          {/* 작업일지 헤더 */}
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-lg font-medium flex items-center gap-2">
                <span className={`px-2 py-1 rounded text-sm ${
                  workOrder.processType === '스크린' ? 'bg-blue-100 text-blue-700' :
                  workOrder.processType === '슬랫' ? 'bg-purple-100 text-purple-700' :
                  'bg-orange-100 text-orange-700'
                }`}>
                  {workOrder.processType}
                </span>
                작업일지
              </h3>
              <p className="text-sm text-gray-500 mt-1">
                {workOrder.processType === '스크린' && '원단 절단, 미싱, 앤드락 작업 등의 내역과 LOT 정보를 기록합니다.'}
                {workOrder.processType === '슬랫' && '코일 절단, 슬랫 성형, 미미 작업 등의 내역과 LOT 정보를 기록합니다.'}
                {workOrder.processType === '절곡' && '벽면형, 하단마감재, 케이스 등의 작업 내역과 LOT 정보를 기록합니다.'}
              </p>
            </div>
            <div className="flex gap-2">
              <Button variant="outline" onClick={() => setShowWorkLogEditor(true)}>
                <Edit className="w-4 h-4" /> {workLogData ? '수정' : '작성'}
              </Button>
              {workLogData && (
                <Button variant="primary" onClick={() => setShowWorkLogSheet(true)}>
                  <Printer className="w-4 h-4" /> 출력
                </Button>
              )}
            </div>
          </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 md:grid-cols-2 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 md:grid-cols-2 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 md:grid-cols-2 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>
        </div>
      )}

      {/* BOM/자재 탭 */}
      {activeTab === 'bom' && (
        <div className="space-y-6">
          {/* 자재 재고 현황 요약 */}
          <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)">
            <div className="flex justify-between items-center mb-4">
              <p className="text-sm text-gray-500">작업에 필요한 자재 목록입니다.</p>
              {workOrder.status === '작업중' && (
                <Button variant="primary" onClick={() => setShowMaterialInputModal(true)}>
                  <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">자재코드</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-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>
                </tr>
              </thead>
              <tbody className="divide-y">
                {bomData.map(item => (
                  <tr key={item.id} className={item.stock < item.required ? 'bg-red-50' : ''}>
                    <td className="px-4 py-3 text-sm font-mono text-gray-600">{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 text-right">{item.required} {item.unit}</td>
                    <td className="px-4 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-4 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>
                    <td className="px-4 py-3 text-sm font-mono text-blue-600">{item.inputLot || '-'}</td>
                    <td className="px-4 py-3 text-center">
                      {workOrder.status === '작업중' && item.stock >= item.required && !item.inputLot && (
                        <Button size="sm" variant="outline" onClick={() => {
                          const lotNo = `MAT-${new Date().toISOString().slice(2,10).replace(/-/g, '')}-${String(Math.floor(Math.random() * 100)).padStart(2, '0')}`;
                          alert(`투입 LOT: ${lotNo}`);
                        }}>
                          투입
                        </Button>
                      )}
                      {item.inputLot && (
                        <CheckCircle className="w-5 h-5 text-green-500 mx-auto" />
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>

          <Card title="자재 투입 이력">
            {workOrder.materialInputs?.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-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>
                  </tr>
                </thead>
                <tbody className="divide-y">
                  <tr>
                    <td className="px-4 py-3 text-sm">2024-12-04 09:00</td>
                    <td className="px-4 py-3 text-sm">스크린 원단 (W2400)</td>
                    <td className="px-4 py-3 text-sm font-mono text-blue-600">MAT-241204-01</td>
                    <td className="px-4 py-3 text-sm text-right">50 M</td>
                    <td className="px-4 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">작업 시작 후 자재 투입 시 기록됩니다.</p>
              </div>
            )}
          </Card>
        </div>
      )}

      {/* 재고 확인 모달 */}
      {showMaterialCheck && (
        <MaterialCheckModal 
          workOrder={workOrder} 
          onClose={() => setShowMaterialCheck(false)} 
        />
      )}

      {/* 투입자재 추가 모달 */}
      {showMaterialInputModal && (
        <MaterialInputModal 
          workOrder={workOrder}
          inventory={inventory}
          onClose={() => setShowMaterialInputModal(false)}
          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);
            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-md overflow-hidden">
            <div className="flex items-center justify-between p-4 border-b">
              <div className="flex items-center gap-2">
                <User 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">
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-6 space-y-4">
              <div className="p-4 bg-gray-50 rounded-lg">
                <p className="text-sm text-gray-500">작업지시번호</p>
                <p className="font-mono font-medium">{workOrder.workOrderNo}</p>
              </div>

              <FormField label="작업자 선택" required>
                <Select
                  options={workers.map(w => ({ value: w, label: w }))}
                  value={assignee}
                  onChange={setAssignee}
                  placeholder="작업자를 선택하세요"
                />
              </FormField>

              <div className="text-sm text-gray-500">
                * 배정된 작업자는 작업 시작 후 변경할 수 없습니다.
              </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}>
                <User className="w-4 h-4" /> 배정하기
              </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">
                <X className="w-5 h-5" />
              </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 && workLogData && (
        <WorkLogSheet
          workOrder={workOrder}
          order={relatedOrder}
          workLog={workLogData}
          onClose={() => setShowWorkLogSheet(false)}
        />
      )}
    </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 lg:grid-cols-2 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('');
  const [processFilter, setProcessFilter] = useState('all');
  const [inspectionFilter, setInspectionFilter] = useState('all');

  const processTypes = ['전체', '스크린', '슬랫', '절곡'];

  const filtered = workResults
    .filter(r => processFilter === 'all' || processFilter === '전체' || r.processType === processFilter)
    .filter(r => {
      if (inspectionFilter === 'inspected') return r.inspectionCompleted;
      if (inspectionFilter === 'notInspected') return !r.inspectionCompleted;
      return true;
    })
    .filter(r => 
      r.lotNo.toLowerCase().includes(search.toLowerCase()) ||
      r.workOrderNo.toLowerCase().includes(search.toLowerCase()) ||
      r.productName.includes(search)
    );

  // 통계
  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>

      {/* 필터 */}
      <div className="flex gap-4">
        <div className="flex-1">
          <SearchInput 
            placeholder="LOT번호, 작업지시번호, 품목명 검색..." 
            value={search} 
            onChange={setSearch} 
          />
        </div>
        <select
          value={processFilter}
          onChange={(e) => setProcessFilter(e.target.value)}
          className="px-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          {processTypes.map(p => (
            <option key={p} value={p}>{p === '전체' ? '공정 전체' : p}</option>
          ))}
        </select>
        <select
          value={inspectionFilter}
          onChange={(e) => setInspectionFilter(e.target.value)}
          className="px-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="all">검사 전체</option>
          <option value="inspected">검사완료</option>
          <option value="notInspected">검사미완료</option>
        </select>
      </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-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-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-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>
  );
};

// ============ 출하 관리 ============

// 배차유형 옵션
const dispatchTypes = ['직접배차', '상차', '택배', '화물', '직접배송'];
const vehicleTypes = ['1톤', '2.5톤', '5톤', '11톤', '25톤'];
const logisticsCompanies = ['한진물류', 'CJ대한통운', '롯데택배', '로젠택배', '우체국택배', '경동택배', '기타'];

// 출하 목록
const ShipmentList = ({ shipments, onNavigate }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [dispatchFilter, setDispatchFilter] = useState('all');

  const tabs = [
    { id: 'all', label: '전체', count: shipments.length },
    { id: 'ordered', label: '출고지시', count: shipments.filter(s => s.status === '출고지시').length },
    { id: 'ready', label: '출하준비', count: shipments.filter(s => s.status === '출하준비').length },
    { id: 'waiting', label: '출하대기', count: shipments.filter(s => s.status === '출하대기').length },
    { id: 'shipping', label: '배송중', count: shipments.filter(s => s.status === '배송중').length },
    { id: 'complete', label: '배송완료', count: shipments.filter(s => s.status === '배송완료').length },
  ];

  const statusFilter = {
    all: () => true,
    ordered: (s) => s.status === '출고지시',
    ready: (s) => s.status === '출하준비',
    waiting: (s) => s.status === '출하대기',
    shipping: (s) => s.status === '배송중',
    complete: (s) => s.status === '배송완료',
  };

  const filtered = shipments
    .filter(statusFilter[activeTab])
    .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())
    );

  // 통계
  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;

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

      <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
        <DashboardCard icon={ClipboardList} title="전체 출하" value={`${shipments.length}건`} color="blue" />
        <DashboardCard icon={Clock} title="출고지시" value={`${shipments.filter(s => s.status === '출고지시').length}건`} color="yellow" />
        <DashboardCard icon={Package} title="출하대기" value={`${shipments.filter(s => s.status === '출하대기').length}건`} color="purple" />
        <DashboardCard icon={Truck} title="배송중" value={`${shipments.filter(s => s.status === '배송중').length}건`} color="blue" />
        <DashboardCard icon={CheckCircle} title="배송완료" value={`${shipments.filter(s => s.status === '배송완료').length}건`} color="green" />
      </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 gap-4">
        <div className="flex-1">
          <SearchInput 
            placeholder="분할번호, 로트번호, 발주처, 현장명 검색..." 
            value={search} 
            onChange={setSearch} 
          />
        </div>
        <select
          value={dispatchFilter}
          onChange={(e) => setDispatchFilter(e.target.value)}
          className="px-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="all">배차유형 전체</option>
          {dispatchTypes.map(type => (
            <option key={type} value={type}>{type}</option>
          ))}
        </select>
      </div>

      <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-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-left text-xs font-medium text-gray-500">현장명</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map((shipment, idx) => {
              // 출하 가능 여부: 입금확인 + 세금계산서 발행 둘 다 완료
              const canShip = shipment.paymentConfirmed && shipment.taxInvoiceIssued;
              
              return (
                <tr 
                  key={shipment.id} 
                  className={`hover:bg-gray-50 cursor-pointer ${!canShip && shipment.status !== '배송완료' ? 'bg-red-50' : ''}`}
                  onClick={() => onNavigate('shipment-detail', shipment)}
                >
                  <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-blue-600">{shipment.splitNo}</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">
                    {shipment.paymentConfirmed 
                      ? <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-gray-100 text-gray-500">-</span>
                    }
                  </td>
                  <td className="px-4 py-3 text-center">
                    {shipment.taxInvoiceIssued 
                      ? <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-gray-100 text-gray-500">-</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">
                    <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>
                  </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>
                </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>
    </div>
  );
};

// 출하 등록
const ShipmentCreate = ({ orders, onNavigate, onBack, onSave }) => {
  const [formData, setFormData] = useState({
    orderNo: '',
    splitNo: '',
    shipmentDate: new Date().toISOString().split('T')[0],
    dispatchType: '상차',
    logisticsCompany: '',
    vehicleType: '',
    vehicleNo: '',
    driverName: '',
    driverPhone: '',
    scheduledArrival: '',
    shippingCost: 0,
    note: '',
  });

  const [selectedOrder, setSelectedOrder] = useState(null);
  const [selectedSplit, setSelectedSplit] = useState(null);

  // 수주 선택 시
  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 (!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 자동 부여

    const newShipment = {
      ...formData,
      id: Date.now(),
      splitNo, // 수주분할번호로 출하 식별
      customerName: selectedOrder?.customerName,
      siteName: selectedOrder?.siteName,
      creditGrade: selectedOrder?.creditGrade,
      deliveryAddress: selectedOrder?.deliveryAddress,
      receiverName: selectedOrder?.receiverName,
      receiverPhone: selectedOrder?.receiverPhone,
      status: '출고지시',
      paymentConfirmed: selectedOrder?.paymentStatus === '전액입금',
      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출하번호: ${splitNo}\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 lg:grid-cols-2 gap-6">
        {/* 수주 선택 */}
        <Card title="수주 선택">
          <div className="space-y-4">
            <FormField label="로트번호" required>
              <select
                value={formData.orderNo}
                onChange={(e) => handleOrderSelect(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>
                {orders.filter(o => 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">
            <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.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 === '상차' && (
              <>
                <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 === '상차' || formData.dispatchType === '직접배송') && (
              <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="비고">
              <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="출하 품목" className="lg:col-span-2">
            <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, onNavigate, onBack, onUpdate }) => {
  const [activeTab, setActiveTab] = useState('basic');

  const tabs = [
    { id: 'basic', label: '기본정보', icon: FileText },
    { id: 'dispatch', label: '배차정보', icon: Truck },
    { id: 'loading', label: '상차체크', icon: Box },
    { id: 'shipHistory', label: '출고이력', icon: Package },
    { id: 'history', label: '변경이력', icon: Clock },
  ];

  // 동일 로트의 다른 출하 조회
  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() } : {}),
    });
  };

  // 출하 가능 여부: 입금확인 + 세금계산서 발행 둘 다 완료
  const canShip = shipment.paymentConfirmed && shipment.taxInvoiceIssued;

  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} />
          {shipment.paymentConfirmed ? (
            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700">
              입금 ✓
            </span>
          ) : (
            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-500">
              입금 -
            </span>
          )}
          {shipment.taxInvoiceIssued ? (
            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700">
              세금계산서 ✓
            </span>
          ) : (
            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-500">
              세금계산서 -
            </span>
          )}
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline"><Printer className="w-4 h-4" /> 출고증</Button>
          <Button variant="outline"><FileText 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 === '출하준비' && shipment.loadingCompleted && canShip && (
            <Button variant="primary" onClick={() => handleStatusChange('출하대기')}>
              <Truck className="w-4 h-4" /> 출하대기
            </Button>
          )}
          {shipment.status === '출하대기' && 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>

      {/* 출하불가 경고 */}
      {!canShip && 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>
      )}

      <DetailTabs tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />

      {activeTab === 'basic' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <Card title="출하 정보">
            <div className="grid grid-cols-2 gap-4">
              <InfoRow label="분할번호" value={shipment.splitNo} />
              <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={
                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={shipment.createdAt} />
              <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="출하 품목" className="lg:col-span-2">
            <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>
      )}

      {activeTab === 'dispatch' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 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>

          <Card title="입차 시간" className="lg:col-span-2">
            <div className="grid grid-cols-2 gap-4">
              <div className="p-4 bg-gray-50 rounded-lg">
                <p className="text-sm text-gray-500 mb-1">입차예정시간</p>
                <p className="text-lg font-medium">
                  {shipment.scheduledArrival 
                    ? new Date(shipment.scheduledArrival).toLocaleString('ko-KR')
                    : '미정'
                  }
                </p>
              </div>
              <div className="p-4 bg-blue-50 rounded-lg">
                <p className="text-sm text-gray-500 mb-1">입차확정시간</p>
                <p className="text-lg font-medium text-blue-600">
                  {shipment.confirmedArrival 
                    ? new Date(shipment.confirmedArrival).toLocaleString('ko-KR')
                    : '미확정'
                  }
                </p>
              </div>
            </div>
            {!shipment.confirmedArrival && shipment.status !== '배송완료' && (
              <div className="mt-4 pt-4 border-t">
                <Button variant="outline" className="w-full justify-center">
                  <Clock className="w-4 h-4" /> 입차시간 확정
                </Button>
              </div>
            )}
          </Card>

          {shipment.note && (
            <Card title="비고" className="lg:col-span-2">
              <p className="text-sm text-gray-700 whitespace-pre-wrap">{shipment.note}</p>
            </Card>
          )}
        </div>
      )}

      {activeTab === 'loading' && (
        <Card title="상차 체크리스트">
          {shipment.loadingCompleted ? (
            <div className="mb-4 p-4 bg-green-50 border border-green-200 rounded-lg">
              <div className="flex items-center gap-2 text-green-700">
                <CheckCircle className="w-5 h-5" />
                <span className="font-medium">상차 완료</span>
              </div>
              <p className="text-sm text-green-600 mt-1">
                {shipment.loadingCompletedAt} / {shipment.loadingWorker}
              </p>
            </div>
          ) : (
            <div className="mb-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg text-sm text-yellow-700">
              <AlertCircle className="w-4 h-4 inline mr-2" />
              모든 품목의 출고구역 도착 확인 및 상차 체크를 완료해주세요.
            </div>
          )}

          <div className="space-y-4">
            {shipment.items.map((item, idx) => (
              <div key={item.id} className="p-4 bg-gray-50 rounded-lg">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-4">
                    <span className="text-sm font-bold text-gray-500">{idx + 1}</span>
                    <div>
                      <p className="font-medium">{item.productName}</p>
                      <p className="text-sm text-gray-500">{item.productCode} / {item.spec} / {item.qty}EA</p>
                      {item.lotNo && (
                        <p className="text-xs text-gray-400 font-mono mt-1">LOT: {item.lotNo}</p>
                      )}
                    </div>
                  </div>
                  <div className="flex flex-col gap-2">
                    <label className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={item.arrivedAtLoadingArea}
                        onChange={(e) => handleLoadingCheck(item.id, 'arrivedAtLoadingArea', e.target.checked)}
                        disabled={shipment.loadingCompleted}
                        className="w-5 h-5 rounded border-gray-300 text-blue-500 focus:ring-blue-500"
                      />
                      <span className="text-sm">출고구역 도착</span>
                    </label>
                    <label className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={item.loadingChecked}
                        onChange={(e) => handleLoadingCheck(item.id, 'loadingChecked', e.target.checked)}
                        disabled={shipment.loadingCompleted || !item.arrivedAtLoadingArea}
                        className="w-5 h-5 rounded border-gray-300 text-green-500 focus:ring-green-500"
                      />
                      <span className="text-sm">상차 완료</span>
                    </label>
                  </div>
                </div>
                {/* 부자재 LOT 입력 */}
                <div className="mt-3 pt-3 border-t">
                  <label className="text-xs text-gray-500">부자재 LOT번호</label>
                  <input
                    type="text"
                    value={item.accessoryLotNo || ''}
                    onChange={(e) => handleLoadingCheck(item.id, 'accessoryLotNo', e.target.value)}
                    disabled={shipment.loadingCompleted}
                    placeholder="부자재 LOT번호 입력"
                    className="mt-1 w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>
            ))}
          </div>

          {!shipment.loadingCompleted && (
            <div className="pt-4 mt-4 border-t">
              <Button 
                variant="success" 
                className="w-full justify-center"
                onClick={handleLoadingComplete}
                disabled={!shipment.items.every(item => item.loadingChecked)}
              >
                <CheckCircle className="w-4 h-4" /> 상차 완료 확인
              </Button>
            </div>
          )}
        </Card>
      )}

      {activeTab === 'shipHistory' && (
        <Card title={`출고 이력 - ${shipment.lotNo}`}>
          <div className="space-y-4">
            {relatedShipments.length > 0 ? (
              relatedShipments.map((sh, idx) => (
                <div 
                  key={sh.id} 
                  className={`p-4 rounded-lg border-2 ${sh.id === shipment.id ? 'border-blue-500 bg-blue-50' : 'border-gray-200 bg-gray-50'}`}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <span className="text-sm font-bold text-gray-500">{idx + 1}차</span>
                      <span className="font-mono text-blue-600">{sh.splitNo}</span>
                      <StatusBadge status={sh.status} />
                      {sh.id === shipment.id && (
                        <span className="text-xs text-blue-600 font-medium">← 현재</span>
                      )}
                    </div>
                    <div className="text-sm text-gray-500">
                      {sh.shipmentDate}
                    </div>
                  </div>
                  <div className="mt-2 text-sm text-gray-600">
                    품목 {sh.items.length}건 / {sh.dispatchType}
                    {sh.completedAt && (
                      <span className="ml-2 text-green-600">완료: {sh.completedAt}</span>
                    )}
                  </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>
              </div>
            )}
          </div>
        </Card>
      )}

      {activeTab === 'history' && (
        <Card title="변경 이력">
          {shipment.changeHistory?.length > 0 ? (
            <div className="space-y-4">
              {shipment.changeHistory.map(history => (
                <div key={history.id} className="flex gap-4 p-4 bg-gray-50 rounded-lg">
                  <div className="w-2 h-2 mt-2 bg-blue-500 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.beforeValue} → <span className="text-blue-600 font-medium">{history.afterValue}</span>
                    </p>
                    {history.reason && (
                      <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">
              <Clock className="w-12 h-12 mx-auto mb-3 text-gray-300" />
              <p>변경 이력이 없습니다.</p>
            </div>
          )}
        </Card>
      )}
    </div>
  );
};

// 출하 수정
const ShipmentEdit = ({ shipment, onNavigate, onBack, onSave }) => {
  const [formData, setFormData] = useState({
    shipmentDate: shipment.shipmentDate,
    dispatchType: shipment.dispatchType,
    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,
      });
    }

    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 lg:grid-cols-2 gap-6">
        {/* 기본 정보 (읽기 전용) */}
        <Card title="기본 정보">
          <div className="grid grid-cols-2 gap-4">
            <InfoRow label="분할번호" value={shipment.splitNo} />
            <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">
            <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.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 === '상차' && (
              <>
                <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 }) => {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('all');

  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>
            </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">{idx + 1}</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>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// 제품검사 상세
const ProductInspectionDetail = ({ inspection, onNavigate, onBack, onUpdate }) => {
  const [activeTab, setActiveTab] = useState('basic');
  const [inspectionData, setInspectionData] = useState(inspection);

  const tabs = [
    { id: 'basic', label: '기본정보', icon: FileText },
    { id: 'items', label: '개소별 검사', icon: ClipboardList },
    { id: 'history', label: '일정변경이력', icon: Clock },
  ];

  // 검사 결과 입력
  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="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>
          <ShieldCheck className="w-6 h-6 text-blue-500" />
          <div>
            <h1 className="text-xl font-bold text-gray-900">제품검사 상세</h1>
            <p className="text-sm text-gray-500 font-mono">{inspection.inspectionNo}</p>
          </div>
          <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 className="flex items-center gap-2">
          <Button variant="outline"><Printer className="w-4 h-4" /> 검사서 출력</Button>
          {inspection.status === '검사신청' && (
            <Button variant="primary"><Calendar className="w-4 h-4" /> 일정 확정</Button>
          )}
          {inspectionData.completedItems === inspectionData.totalItems && inspection.approvalStatus === '대기' && (
            <Button variant="success"><CheckCircle className="w-4 h-4" /> 결재 요청</Button>
          )}
        </div>
      </div>

      <DetailTabs tabs={tabs} activeTab={activeTab} onTabChange={setActiveTab} />

      {/* 기본정보 탭 */}
      {activeTab === 'basic' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 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="검사 진행 현황" className="lg:col-span-2">
            <div className="grid 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>
      )}

      {/* 개소별 검사 탭 */}
      {activeTab === 'items' && (
        <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>
      )}

      {/* 일정변경이력 탭 */}
      {activeTab === 'history' && (
        <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: 'process', label: '공정관리', icon: GitBranch },
        { id: 'item', label: '품목관리', icon: Package },
        { id: 'inspection-standard', label: '검사기준관리', icon: ShieldCheck },
        { id: 'number-rule', label: '번호기준관리', icon: ClipboardList },
        { id: 'code-rule', label: '코드기준관리', icon: Layers },
        { id: 'quote-formula', label: '견적수식관리', icon: Calculator },
      ],
    },
    {
      id: 'sales',
      label: '판매관리',
      icon: DollarSign,
      subMenus: [
        { id: 'customer', label: '거래처관리', icon: Users },
        { id: 'quote', label: '견적관리', icon: FileText },
        { id: 'order', label: '수주관리', icon: Package },
        { id: 'shipment', label: '출하관리', icon: Truck },
        { id: 'site', label: '현장관리', icon: Building },
        { id: 'price', label: '단가관리', icon: DollarSign },
      ],
    },
    {
      id: 'logistics',
      label: '물류관리',
      icon: Truck,
      subMenus: [
        { id: 'shipment', label: '출하관리', icon: Truck },
        { id: 'delivery', label: '배송현황', icon: MapPin },
      ],
    },
    {
      id: 'production',
      label: '생산관리',
      icon: Factory,
      subMenus: [
        { 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: 'incoming-inspection', label: '수입검사', icon: Clipboard },
        { id: 'process-inspection', label: '중간검사', icon: Clipboard },
        { id: 'product-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: Send },
      ],
    },
    {
      id: 'accounting',
      label: '회계관리',
      icon: CreditCard,
      subMenus: [
        // 매출
        { id: 'customer', label: '거래처관리', icon: Building },
        { id: 'sales-account', label: '판매관리', icon: BarChart3 },
        { id: 'invoice', label: '거래명세서/세금계산서', icon: FileText },
        { id: 'ledger', label: '원장발행', icon: Clipboard },
        { id: 'sales-batch', label: '판매일괄회계', icon: DollarSign },
        { id: 'receivable', label: '거래처별채권', icon: Users },
        // 매입
        { id: 'purchase-request', label: '품의서', icon: ClipboardList },
        { id: 'expense-report', label: '지출결의서', icon: FileText },
        { id: 'expense-plan', label: '지출예상내역', icon: Clock },
        // 수입/지출
        { id: 'cashbook', label: '금전출납부', icon: Clipboard },
        { id: 'collection', label: '수금관리', icon: DollarSign },
        { id: 'outstanding', label: '미수금관리', icon: AlertCircle },
        { id: 'bill', label: '어음관리', icon: CreditCard },
      ],
    },
  ];

  // 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 => (
                      <button
                        key={sub.id}
                        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>
        ))}
      </nav>

      {/* 설정 버튼 */}
      <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, shipment: true, site: true, price: true } },
        logistics: { enabled: false },
        production: { enabled: false },
        quality: { enabled: false },
        inventory: { enabled: false },
        accounting: { enabled: false },
      }
    },
    logistics: {
      label: '물류팀',
      config: {
        sales: { enabled: false },
        logistics: { enabled: true, subMenus: { shipment: true, delivery: 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, shipment: false } },
        logistics: { enabled: false },
        production: { enabled: true, subMenus: { 'production-dashboard': true, 'work-order': true, 'work-result': true, 'worker-task': true } },
        quality: { enabled: true, subMenus: { 'incoming-inspection': true, 'process-inspection': true, 'product-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, shipment: true } },
        logistics: { enabled: false },
        production: { enabled: false },
        quality: { enabled: false },
        inventory: { enabled: false },
        accounting: { enabled: true, subMenus: { customer: true, 'sales-account': true, invoice: true, ledger: true, 'sales-batch': true, receivable: true, 'purchase-request': true, 'expense-report': true, 'expense-plan': true, cashbook: true, collection: true, outstanding: true, bill: true } },
      }
    },
    admin: {
      label: '관리자 (전체)',
      config: {
        sales: { enabled: true, subMenus: { customer: true, quote: true, order: true, shipment: true, site: true, price: true } },
        logistics: { enabled: true, subMenus: { shipment: true, delivery: true } },
        production: { enabled: true, subMenus: { 'production-dashboard': true, 'work-order': true, 'work-result': true, 'worker-task': true } },
        quality: { enabled: true, subMenus: { 'incoming-inspection': true, 'process-inspection': true, 'product-inspection': true, defect: true } },
        inventory: { enabled: true, subMenus: { stock: true, inbound: true, outbound: true } },
        accounting: { enabled: true, subMenus: { customer: true, 'sales-account': true, invoice: true, ledger: true, 'sales-batch': true, receivable: true, 'purchase-request': true, 'expense-report': true, 'expense-plan': true, cashbook: true, collection: true, outstanding: true, bill: true } },
      }
    },
  };

  const menuDefinitions = [
    {
      id: 'master',
      label: '기준정보',
      icon: Settings,
      subMenus: [
        { id: 'process', label: '공정관리' },
        { id: 'item', label: '품목관리' },
        { id: 'inspection-standard', 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: 'shipment', label: '출하관리' },
        { id: 'site', label: '현장관리' },
        { id: 'price', label: '단가관리' },
      ],
    },
    {
      id: 'logistics',
      label: '물류관리',
      icon: Truck,
      subMenus: [
        { id: 'shipment', label: '출하관리' },
        { id: 'delivery', label: '배송현황' },
      ],
    },
    {
      id: 'production',
      label: '생산관리',
      icon: Factory,
      subMenus: [
        { id: 'production-dashboard', label: '생산 현황판' },
        { id: 'work-order', label: '작업지시 관리' },
        { id: 'work-result', label: '작업실적' },
        { id: 'worker-task', label: '작업자 화면' },
      ],
    },
    {
      id: 'quality',
      label: '품질관리',
      icon: ShieldCheck,
      subMenus: [
        { id: 'incoming-inspection', label: '수입검사' },
        { id: 'process-inspection', label: '중간검사' },
        { id: 'product-inspection', label: '제품검사' },
        { id: 'defect', label: '부적합품관리' },
      ],
    },
    {
      id: 'inventory',
      label: '자재관리',
      icon: Warehouse,
      subMenus: [
        { id: 'stock', label: '재고현황' },
        { id: 'inbound', label: '입고관리' },
        { id: 'outbound', label: '출고관리' },
      ],
    },
    {
      id: 'accounting',
      label: '회계관리',
      icon: CreditCard,
      subMenus: [
        { id: 'sales-account', label: '매출관리' },
        { id: 'purchase-account', label: '매입관리' },
        { id: 'credit', label: '거래처신용관리' },
        { id: 'collection', label: '수금관리' },
        { id: 'cashbook', label: '금전출납부' },
        { id: 'cost', 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 [showSettings, setShowSettings] = useState(false);
  const [showMobileMenu, setShowMobileMenu] = useState(false);
  
  // 현재 사용자 상태 (역할별 로그인)
  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: '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 [workOrders, setWorkOrders] = useState(initialWorkOrders);
  const [workResults, setWorkResults] = useState(initialWorkResults);
  const [shipments, setShipments] = useState(initialShipments);
  const [productInspections, setProductInspections] = useState(initialProductInspections);
  
  // 품목유형 정의 (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' },
  ];

  // 재고 데이터 (확장: itemType, category 필드 추가)
  const [inventory, setInventory] = useState([
    // ═══════════════════════════════════════════
    // 원자재 (Raw Material)
    // ═══════════════════════════════════════════
    { id: 1, materialCode: 'SCR-MAT-001', materialName: '스크린 원단 (백색)', unit: '㎡', stock: 500, minStock: 100, location: 'A-01', lastUpdated: '2025-03-01',
      itemType: '원자재', category: '원단', subCategory: '스크린용' },
    { id: 6, materialCode: 'SLT-MAT-001', materialName: '슬랫 코일', unit: 'KG', stock: 1500, minStock: 300, location: 'C-01', lastUpdated: '2025-03-01',
      itemType: '원자재', category: '코일', subCategory: '슬랫용' },
    { id: 8, materialCode: 'EGI1.55T', materialName: 'EGI 철판 1.55T', unit: '매', stock: 200, minStock: 50, location: 'D-01', lastUpdated: '2025-03-01',
      itemType: '원자재', category: '철판', subCategory: 'EGI' },
    { id: 9, materialCode: 'SUS1.2T', materialName: 'SUS 철판 1.2T', unit: '매', stock: 80, minStock: 20, location: 'D-02', lastUpdated: '2025-03-01',
      itemType: '원자재', category: '철판', subCategory: 'SUS' },
    
    // ═══════════════════════════════════════════
    // 부자재 (Sub Material)
    // ═══════════════════════════════════════════
    { id: 2, materialCode: 'SCR-MAT-002', materialName: '앤드락', unit: 'EA', stock: 800, minStock: 200, location: 'A-02', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '체결류' },
    { id: 3, materialCode: 'SCR-MAT-003', materialName: '하단바', unit: 'EA', stock: 120, minStock: 30, location: 'A-03', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '프레임류' },
    { id: 4, materialCode: 'SCR-MAT-004', materialName: '미싱실', unit: 'M', stock: 5000, minStock: 1000, location: 'A-04', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '봉제류' },
    { id: 7, materialCode: 'SLT-MAT-002', materialName: '미미자재', unit: 'EA', stock: 600, minStock: 150, location: 'C-02', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '마감류' },
    { id: 50, materialCode: 'SM-RIVET-01', materialName: '리벳', unit: 'EA', stock: 5000, minStock: 1000, location: 'B-01', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '체결류' },
    { id: 51, materialCode: 'SM-BOLT-01', materialName: '육각볼트 M8', unit: 'EA', stock: 3000, minStock: 500, location: 'B-02', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '체결류' },
    { id: 52, materialCode: 'SM-SILICON-01', materialName: '실리콘', unit: 'EA', stock: 200, minStock: 50, location: 'B-03', lastUpdated: '2025-03-01',
      itemType: '부자재', category: '접착류' },
    
    // ═══════════════════════════════════════════
    // 소모품 (Consumables)
    // ═══════════════════════════════════════════
    { id: 5, materialCode: 'SCR-MAT-005', materialName: '포장박스', unit: 'EA', stock: 200, minStock: 50, location: 'B-01', lastUpdated: '2025-03-01',
      itemType: '소모품', category: '포장' },
    { id: 53, materialCode: 'CS-TAPE-01', materialName: '포장테이프', unit: 'EA', stock: 100, minStock: 30, location: 'B-04', lastUpdated: '2025-03-01',
      itemType: '소모품', category: '포장' },
    
    // ═══════════════════════════════════════════
    // 절곡부품 - 가이드레일 (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: 'E-150K220V-W', materialName: '전동개폐기 150KG 220V 유선', unit: 'EA', stock: 300, minStock: 50, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '150KG/220V/유선', supplier: '대한' },
    { id: 502, materialCode: 'E-300K220V-W', materialName: '전동개폐기 300KG 220V 유선', unit: 'EA', stock: 508, minStock: 80, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '300KG/220V/유선', supplier: '대한' },
    { id: 503, materialCode: 'E-400K220V-W', materialName: '전동개폐기 400KG 220V 유선', unit: 'EA', stock: 136, minStock: 30, location: 'I-01', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '전동개폐기', spec: '400KG/220V/유선', supplier: '대한' },
    { id: 504, materialCode: 'CTL-EMBED-W', materialName: '연동제어기 매립형 유선', unit: 'EA', stock: 500, minStock: 80, location: 'I-02', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '연동제어기', spec: '매립/유선', supplier: '대한' },
    { id: 505, materialCode: 'CTL-EXPOSE-W', materialName: '연동제어기 노출형 유선', unit: 'EA', stock: 500, minStock: 80, location: 'I-02', lastUpdated: '2025-03-01',
      itemType: '구매부품', category: '연동제어기', spec: '노출/유선', supplier: '대한' },
    { id: 506, materialCode: 'SHAFT-114-45', 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 },
    { id: 507, materialCode: 'SHAFT-139-45', 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 },
  ]);
  
  // 자재 투입 이력
  const [materialUsage, setMaterialUsage] = useState([]);

  // 메뉴 설정 (기본값: 관리자 - 전체 메뉴)
  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, shipment: true, site: true, price: true } },
    logistics: { enabled: false, subMenus: { shipment: true, delivery: true } },
    production: { enabled: true, subMenus: { 'production-dashboard': true, 'work-order': true, 'work-result': true, 'worker-task': true } },
    quality: { enabled: true, subMenus: { 'incoming-inspection': true, 'process-inspection': true, 'product-inspection': true, defect: true } },
    inventory: { enabled: true, subMenus: { stock: true, inbound: true, outbound: true } },
    accounting: { enabled: true, subMenus: { customer: true, 'sales-account': true, invoice: true, ledger: true, 'sales-batch': true, receivable: true, 'purchase-request': true, 'expense-report': true, 'expense-plan': true, cashbook: true, collection: true, outstanding: true, bill: true } },
  });

  const navigate = (viewName, item = null) => {
    setView(viewName);
    setSelectedItem(item);
  };

  const handleMenuChange = (menuId) => {
    setActiveMenu(menuId);
    // 메뉴에 따라 기본 뷰 설정
    switch(menuId) {
      case 'dashboard':
        setView('dashboard');
        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 'quote':
        setView('quote-list');
        break;
      case 'order':
        setView('order-list');
        break;
      case 'price':
        setView('price-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 'shipment':
        setView('shipment-list');
        break;
      case 'product-inspection':
        setView('product-inspection-list');
        break;
      case 'defect':
        setView('defect-list');
        break;
      case 'stock':
        setView('stock-list');
        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 handleSaveWorkOrder = (newWorkOrder) => {
    const workOrder = {
      ...newWorkOrder,
      id: workOrders.length + 1,
    };
    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 }
                : s
            ),
          };
        }
        return o;
      }));
    }
  };

  // 작업지시 업데이트
  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 = (updatedShipment) => {
    setShipments(prev => prev.map(s => 
      s.id === updatedShipment.id ? updatedShipment : s
    ));
    setSelectedItem(updatedShipment);
  };

  const renderContent = () => {
    switch(view) {
      // 대시보드
      case 'dashboard':
      case 'ceo-dashboard':
        return <CEODashboard userRole={currentUser.role} onNavigate={navigate} />;
      case 'sales-dashboard':
        return <SalesDashboard onNavigate={navigate} />;
      case 'production-dashboard':
        return <ProductionDashboard onNavigate={navigate} />;
      case 'quality-dashboard':
        return <QualityDashboard onNavigate={navigate} />;
      case 'accounting-dashboard':
        return <AccountingDashboard onNavigate={navigate} />;
      case 'worker-dashboard':
        return <WorkerDashboard 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 'inspection-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 'quote-list':
        return <QuoteList quotes={quotes} onNavigate={navigate} />;
      case 'quote-create':
        return <QuoteCreate onNavigate={navigate} onBack={() => navigate('quote-list')} onSave={handleSaveQuote} />;
      case 'quote-detail':
        return <QuoteDetail 
          quote={selectedItem} 
          orders={orders}
          onNavigate={navigate} 
          onBack={() => navigate('quote-list')} 
          onConvertToOrder={(quote) => {
            setQuotes(prev => prev.map(q => q.id === quote.id ? { ...q, status: '수주전환' } : q));
          }}
          onUpdateQuote={(updatedQuote) => {
            setQuotes(prev => prev.map(q => q.id === updatedQuote.id ? updatedQuote : q));
            setSelectedItem(updatedQuote);
          }}
        />;
      // 수주관리
      case 'order-list':
        return <OrderList orders={orders} shipments={shipments} onNavigate={navigate} />;
      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} 
          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]);
          }}
        />;
      case 'order-edit':
        return <OrderEdit order={selectedItem} onNavigate={navigate} onBack={() => navigate('order-detail', selectedItem)} onSave={handleUpdateOrder} />;
      // 생산관리 - 현황판
      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: '작업중' } : wo
            ));
          }}
          onReportIssue={(task, issue) => {
            console.log('Issue reported:', task.workOrderNo, issue);
            alert(`이슈가 보고되었습니다.\n작업: ${task.workOrderNo}\n유형: ${issue.type}`);
          }}
        />;
      case 'work-order-list':
        return <WorkOrderList workOrders={workOrders} onNavigate={navigate} />;
      case 'work-order-create':
        return <WorkOrderCreate orders={orders} onNavigate={navigate} onBack={() => navigate('work-order-list')} onSave={handleSaveWorkOrder} />;
      case 'work-order-detail':
        return <WorkOrderDetail 
          workOrder={selectedItem} 
          workResults={workResults}
          orders={orders}
          inventory={inventory}
          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),
            }]);
          }}
        />;
      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 'product-inspection-list':
        return <ProductInspectionList inspections={productInspections} onNavigate={navigate} />;
      case 'product-inspection-detail':
        return <ProductInspectionDetail inspection={selectedItem} onNavigate={navigate} onBack={() => navigate('product-inspection-list')} onUpdate={(updated) => setProductInspections(prev => prev.map(i => i.id === updated.id ? updated : i))} />;
      // 거래처 관리
      case 'customer-list':
        return <CustomerList customers={initialCustomers} onNavigate={navigate} />;
      // 현장 관리
      case 'site-list':
        return <SiteList sites={initialSites} onNavigate={navigate} />;
      // 단가 관리
      case 'price-list':
        return <PriceList prices={initialPrices} onNavigate={navigate} />;
      // 자재관리 - 재고현황
      case 'stock-list':
        return <StockList inventory={inventory} onNavigate={navigate} />;
      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>
        );
    }
  };

  return (
    <div className="flex h-screen bg-gray-50">
      {/* 데스크탑/태블릿: 사이드바 */}
      {!isMobile && (
        <Sidebar 
          activeMenu={activeMenu} 
          onMenuChange={handleMenuChange}
          menuConfig={menuConfig}
          onOpenSettings={() => setShowSettings(true)}
        />
      )}
      
      {/* 메인 컨텐츠 */}
      <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}
          />
        )}
        
        {/* 메인 컨텐츠 영역 */}
        <main className="flex-1 overflow-y-auto">
          <div className={`${isMobile ? 'p-4' : 'p-6'}`}>
            {renderContent()}
          </div>
        </main>
      </div>
      
      {/* 모바일 메뉴 */}
      {isMobile && (
        <MobileMenu
          isOpen={showMobileMenu}
          onClose={() => setShowMobileMenu(false)}
          activeMenu={activeMenu}
          onMenuChange={handleMenuChange}
          menuConfig={menuConfig}
        />
      )}
      
      {/* 메뉴 설정 모달 */}
      {showSettings && (
        <MenuSettings
          menuConfig={menuConfig}
          onSave={setMenuConfig}
          onClose={() => setShowSettings(false)}
        />
      )}
    </div>
  );
}
