// 유저플로우 패널 - 20가지 플로우 패턴 + 메뉴별/화면별 플로우차트
// 그레이스케일 와이어프레임 스타일 적용
import React, { useState } from 'react';
import {
  X, ChevronDown, ChevronRight, ArrowRight, ArrowDown, ExternalLink,
  GitBranch, Circle, Diamond, Square, CheckCircle2, Play, Eye, Search,
  Filter, Package, Truck, Factory, Users, DollarSign, ShieldCheck,
  Box, CreditCard, ClipboardList, FileText, Settings, AlertTriangle
} from 'lucide-react';
import {
  mainUserFlows,
  menuFlows,
  screenFlows,
  flowCategories,
  getFlowsByCategory,
  allScreens,
  findFlowPath,
  getScreensByGroup,
} from '../configs/userFlowPatterns';

// 아이콘 매핑
const iconMap = {
  DollarSign, Factory, ShieldCheck, CreditCard, Box, Package, Truck,
  Users, FileText, ClipboardList, Settings
};

const getIcon = (iconName) => iconMap[iconName] || FileText;

// 그레이스케일 카테고리 스타일 (기존 색상 대신 음영 구분)
const categoryStyles = {
  sales: { bg: 'bg-gray-100', border: 'border-gray-400', text: 'text-gray-800', fill: 'bg-gray-700' },
  production: { bg: 'bg-gray-50', border: 'border-gray-300', text: 'text-gray-700', fill: 'bg-gray-600' },
  quality: { bg: 'bg-gray-100', border: 'border-gray-400', text: 'text-gray-800', fill: 'bg-gray-800' },
  accounting: { bg: 'bg-gray-50', border: 'border-gray-300', text: 'text-gray-700', fill: 'bg-gray-500' },
  inventory: { bg: 'bg-gray-100', border: 'border-gray-400', text: 'text-gray-800', fill: 'bg-gray-600' },
};

// 플로우 스텝 미니 컴포넌트
const MiniFlowStep = ({ step, index, isLast, category, onClick }) => {
  const styles = categoryStyles[category] || categoryStyles.sales;
  const isDecision = step.type === 'decision';

  return (
    <div className="flex items-center">
      <div
        onClick={() => onClick && onClick(step)}
        className={`
          cursor-pointer transition-all hover:scale-105
          ${isDecision ? 'w-6 h-6 rotate-45' : 'px-2 py-1 rounded'}
          bg-white border border-gray-400 text-xs text-gray-800
        `}
      >
        <span className={isDecision ? '-rotate-45 block text-center' : ''}>
          {isDecision ? '?' : step.label}
        </span>
      </div>
      {!isLast && (
        <ArrowRight className="w-3 h-3 mx-1 text-gray-500" />
      )}
    </div>
  );
};

// 플로우 카드 컴포넌트
const FlowCard = ({ flow, isExpanded, onToggle, onNavigate, onStepClick }) => {
  const styles = categoryStyles[flow.category] || categoryStyles.sales;
  const category = flowCategories.find(c => c.id === flow.category);
  const CategoryIcon = getIcon(category?.icon);

  return (
    <div className="bg-white border border-gray-300 rounded-lg overflow-hidden mb-2">
      {/* 헤더 */}
      <div
        onClick={onToggle}
        className="flex items-center justify-between p-3 cursor-pointer hover:bg-gray-50"
      >
        <div className="flex items-center gap-2 flex-1 min-w-0">
          <div className="w-7 h-7 bg-gray-700 rounded flex items-center justify-center flex-shrink-0">
            <CategoryIcon className="w-4 h-4 text-white" />
          </div>
          <div className="min-w-0">
            <h4 className="font-medium text-sm text-gray-800 truncate">{flow.name}</h4>
            <p className="text-xs text-gray-500 truncate">{flow.description}</p>
          </div>
        </div>
        <div className="flex items-center gap-1 flex-shrink-0">
          <span className="px-2 py-0.5 rounded text-xs bg-gray-200 text-gray-700">
            {flow.steps.length}단계
          </span>
          {isExpanded ? <ChevronDown className="w-4 h-4 text-gray-600" /> : <ChevronRight className="w-4 h-4 text-gray-600" />}
        </div>
      </div>

      {/* 확장된 내용 */}
      {isExpanded && (
        <div className="p-3 bg-gray-50 border-t border-gray-200 space-y-3">
          {/* 미니 플로우 다이어그램 */}
          <div className="flex flex-wrap items-center gap-1 pb-2 border-b border-gray-200">
            {flow.steps.slice(0, 5).map((step, idx) => (
              <MiniFlowStep
                key={step.id}
                step={step}
                index={idx}
                isLast={idx === Math.min(flow.steps.length - 1, 4)}
                category={flow.category}
                onClick={onStepClick}
              />
            ))}
            {flow.steps.length > 5 && (
              <span className="text-xs text-gray-400">+{flow.steps.length - 5}단계</span>
            )}
          </div>

          {/* 스텝 상세 목록 */}
          <div className="space-y-2">
            {flow.steps.map((step, idx) => (
              <div
                key={step.id}
                className="flex items-start gap-2 text-xs p-2 bg-white border border-gray-200 rounded hover:bg-gray-100 cursor-pointer"
                onClick={() => onNavigate && onNavigate(step.screen)}
              >
                <span className="w-5 h-5 bg-gray-700 text-white rounded-full flex items-center justify-center flex-shrink-0 text-xs">
                  {idx + 1}
                </span>
                <div className="flex-1 min-w-0">
                  <div className="font-medium text-gray-800">{step.label}</div>
                  <div className="text-gray-500 truncate">{step.menu}</div>
                  <div className="text-gray-400">{step.action}</div>
                </div>
                {step.screen && (
                  <ExternalLink className="w-3 h-3 text-gray-400 flex-shrink-0" />
                )}
              </div>
            ))}
          </div>

          {/* 분기 조건 */}
          {flow.branches && flow.branches.length > 0 && (
            <div className="pt-2 border-t border-gray-200">
              <div className="text-xs font-medium text-gray-600 mb-1">분기 조건</div>
              {flow.branches.map((branch, idx) => (
                <div key={idx} className="flex items-center gap-1 text-xs text-gray-500">
                  <Diamond className="w-3 h-3 text-gray-500" />
                  <span>{branch.condition}</span>
                  <ArrowRight className="w-3 h-3" />
                  <span className="text-gray-700">{branch.label}</span>
                </div>
              ))}
            </div>
          )}

          {/* 테스트 버튼 - 검정색 배경 + 흰색 텍스트 (프로젝트 룰) */}
          <button
            onClick={() => onNavigate && flow.steps[0] && onNavigate(flow.steps[0].screen)}
            className="w-full py-2 bg-black text-white rounded text-xs font-medium flex items-center justify-center gap-1 hover:bg-gray-800"
          >
            <Play className="w-3 h-3" />
            플로우 테스트 시작
          </button>
        </div>
      )}
    </div>
  );
};

// 메뉴별 플로우 카드
const MenuFlowCard = ({ menuId, menuData, isExpanded, onToggle, onNavigate }) => {
  return (
    <div className="bg-white border border-gray-300 rounded-lg overflow-hidden mb-2">
      <div
        onClick={onToggle}
        className="flex items-center justify-between p-3 cursor-pointer hover:bg-gray-50"
      >
        <div>
          <h4 className="font-medium text-sm text-gray-800">{menuData.name}</h4>
          <p className="text-xs text-gray-500">{menuData.description}</p>
        </div>
        <div className="flex items-center gap-1">
          <span className="px-2 py-0.5 rounded text-xs bg-gray-200 text-gray-700">
            {menuData.flows.length}
          </span>
          {isExpanded ? <ChevronDown className="w-4 h-4 text-gray-600" /> : <ChevronRight className="w-4 h-4 text-gray-600" />}
        </div>
      </div>

      {isExpanded && (
        <div className="p-3 bg-gray-50 border-t border-gray-200 space-y-2">
          {menuData.flows.map((flow) => (
            <div key={flow.id} className="bg-white p-2 rounded border border-gray-200 text-xs">
              <h5 className="font-medium text-gray-800 mb-1">{flow.name}</h5>
              <div className="flex items-center gap-1 flex-wrap">
                {flow.flow.split(' → ').map((step, idx, arr) => (
                  <React.Fragment key={idx}>
                    <span
                      className="px-1.5 py-0.5 bg-gray-100 text-gray-700 border border-gray-300 rounded cursor-pointer hover:bg-gray-200"
                      onClick={() => onNavigate && onNavigate(flow.screens[idx])}
                    >
                      {step}
                    </span>
                    {idx < arr.length - 1 && <ArrowRight className="w-3 h-3 text-gray-400" />}
                  </React.Fragment>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// 화면별 액션 카드
const ScreenActionCard = ({ screenId, screenData, onNavigate }) => {
  return (
    <div className="bg-white border border-gray-300 rounded-lg p-2 mb-2">
      <h5 className="font-medium text-xs text-gray-800 mb-2">{screenData.name}</h5>
      <div className="space-y-1">
        {screenData.actions.slice(0, 4).map((action, idx) => (
          <div
            key={idx}
            className="flex items-center gap-1 text-xs p-1 bg-gray-50 border border-gray-200 rounded cursor-pointer hover:bg-gray-100"
            onClick={() => action.next && onNavigate && onNavigate(action.next)}
          >
            <span className="text-gray-700 flex-1">{action.action}</span>
            {action.next && (
              <>
                <ArrowRight className="w-3 h-3 text-gray-400" />
                <span className="text-gray-600 text-xs font-mono">{action.next}</span>
              </>
            )}
          </div>
        ))}
        {screenData.actions.length > 4 && (
          <div className="text-xs text-gray-400 text-center">
            +{screenData.actions.length - 4}개 더보기
          </div>
        )}
      </div>
    </div>
  );
};

// 상세 프로세스 플로우 데이터 (견적 → 출하까지 전체 흐름)
const detailedProcessFlow = {
  stages: [
    {
      id: 'quote',
      name: '견적',
      description: '고객 요청에 대한 견적서 작성',
      screens: ['quote-register', 'quote-detail'],
      documents: [
        { name: '견적서', type: '출력', timing: '견적 등록 완료 시', data: ['고객정보', '품목', '단가', '수량', '납기일'], templateRef: '문서양식관리 > 견적서 양식' }
      ],
      dataFlow: { input: ['고객 요청', '품목 정보'], output: ['견적서', '견적 데이터'], next: 'order' },
      masterRef: ['품목기준관리', '거래처관리', '견적수식관리']
    },
    {
      id: 'order',
      name: '수주',
      description: '견적 승인 후 수주 확정',
      screens: ['order-register', 'order-detail'],
      documents: [
        { name: '수주확인서', type: '출력', timing: '수주 등록 완료 시', data: ['수주번호', '고객정보', '품목', '수량', '납기일'], templateRef: '문서양식관리 > 수주확인서 양식' },
        { name: '발주서', type: '출력', timing: '자재 발주 시', data: ['공급업체', '품목', '수량', '납기요청일'], templateRef: '문서양식관리 > 발주서 양식' }
      ],
      dataFlow: { input: ['견적 데이터', '승인 정보'], output: ['수주 데이터', '발주 데이터'], next: 'production' },
      masterRef: ['수주기준관리', '거래처관리'],
      accountingRef: { type: '매입예정', target: '발주 시 매입관리에 품의서 자동 생성' }
    },
    {
      id: 'production',
      name: '생산지시',
      description: '수주 기반 생산 계획 수립 및 지시',
      screens: ['production-order-list', 'production-order-create'],
      documents: [
        { name: '생산지시서', type: '출력', timing: '생산지시 등록 시', data: ['지시번호', '품목', '수량', '납기일', '우선순위'], templateRef: '문서양식관리 > 생산지시서 양식' }
      ],
      dataFlow: { input: ['수주 데이터'], output: ['생산지시 데이터', '공정별 품목 분류'], next: 'work-order' },
      masterRef: ['공정기준관리', '품목기준관리'],
      processClassification: {
        description: '공정관리 기반 자동 분류',
        rules: [
          { process: '슬랫', condition: '품목코드 SL- 또는 명칭에 슬랫/루버 포함' },
          { process: '스크린', condition: '품목코드 SC- 또는 명칭에 스크린/망/메쉬 포함' },
          { process: '절곡', condition: '품목코드 BD- 또는 명칭에 절곡/벤딩/곡면 포함' },
          { process: '구매품', condition: '품목코드 PU- 또는 자가생산 아닌 품목' }
        ]
      }
    },
    {
      id: 'work-order',
      name: '작업지시',
      description: '공정별 작업지시 생성 및 배정',
      screens: ['work-order-list', 'work-order-register', 'work-order-detail'],
      documents: [
        { name: '작업지시서', type: '출력', timing: '작업지시 등록 시', data: ['지시번호', '공정', '품목', '수량', '작업자', '설비'], templateRef: '문서양식관리 > 작업지시서 양식' },
        { name: '작업표준서', type: '참조', timing: '작업 시작 전', data: ['작업 절차', '품질 기준', '안전 사항'], templateRef: '문서양식관리 > 작업표준서 양식' }
      ],
      dataFlow: { input: ['생산지시 데이터', '공정 정보'], output: ['작업지시 데이터', '작업자 배정'], next: 'worker' },
      masterRef: ['공정기준관리', '품질기준관리']
    },
    {
      id: 'worker',
      name: '작업자 작업',
      description: '작업자 실제 작업 수행 및 실적 등록',
      screens: ['worker-task-view', 'work-result-register'],
      documents: [
        { name: '작업일지(공정별)', type: '출력', timing: '작업 완료 시', data: ['작업지시번호', '공정', '작업내용', '실적수량', '불량수량', '작업자'], templateRef: '문서양식관리 > 작업일지 양식' }
      ],
      dataFlow: { input: ['작업지시', '자재'], output: ['작업실적', '생산품'], next: 'quality' },
      masterRef: ['공정기준관리']
    },
    {
      id: 'quality',
      name: '품질검사',
      description: '3단계 품질검사 (IQC/PQC/FQC)',
      screens: ['iqc-list', 'pqc-list', 'fqc-list', 'defect-list'],
      documents: [
        { name: '수입검사성적서', type: '출력', timing: 'IQC 완료 시', data: ['자재', '검사항목', '결과', '판정'], templateRef: '문서양식관리 > 수입검사성적서 양식' },
        { name: '중간검사성적서', type: '출력', timing: 'PQC 완료 시', data: ['공정', '검사항목', '결과', '판정'], templateRef: '문서양식관리 > 중간검사성적서 양식' },
        { name: '제품검사성적서', type: '출력', timing: 'FQC 완료 시', data: ['제품', '검사항목', '결과', '판정'], templateRef: '문서양식관리 > 제품검사성적서 양식' },
        { name: '부적합품보고서', type: '출력', timing: '불량 발생 시', data: ['불량내용', '원인', '처리방안'], templateRef: '문서양식관리 > 부적합품보고서 양식' }
      ],
      dataFlow: { input: ['생산품', '검사기준'], output: ['합격품', '검사성적서'], next: 'shipment' },
      masterRef: ['품질기준관리'],
      inspectionStandards: {
        description: '품질기준관리 연동',
        types: [
          { type: 'IQC', name: '수입검사', standardRef: '품목별 수입검사 기준', criteria: ['외관검사', '치수검사', '성분분석'] },
          { type: 'PQC', name: '중간검사', standardRef: '공정별 중간검사 기준', criteria: ['공정품질', '작업표준 준수', '중간측정'] },
          { type: 'FQC', name: '제품검사', standardRef: '제품별 출하검사 기준', criteria: ['최종검사', '기능테스트', '포장검사'] }
        ]
      }
    },
    {
      id: 'shipment',
      name: '출하',
      description: '최종 제품 출하 및 납품',
      screens: ['shipment-list', 'shipment-register', 'shipment-detail'],
      documents: [
        { name: '출하지시서', type: '출력', timing: '출하 등록 시', data: ['출하번호', '고객', '품목', '수량', '납품일'], templateRef: '문서양식관리 > 출하지시서 양식' },
        { name: '납품서', type: '출력', timing: '납품 시', data: ['납품번호', '품목', '수량', '인수자'], templateRef: '문서양식관리 > 납품서 양식' },
        { name: '거래명세서', type: '출력', timing: '거래 완료 시', data: ['거래내역', '금액', '세금'], templateRef: '문서양식관리 > 거래명세서 양식' },
        { name: '세금계산서', type: '출력', timing: '정산 시', data: ['공급가액', '세액', '합계'], templateRef: '문서양식관리 > 세금계산서 양식' }
      ],
      dataFlow: { input: ['합격품', '출하요청'], output: ['납품완료', '매출데이터'], next: null },
      masterRef: ['거래처관리', '현장기준관리'],
      accountingRef: { type: '매출', target: '출하 완료 시 회계관리 > 매출관리에 자동 연동' }
    }
  ],
  // 데이터 연동 매트릭스
  dataMatrix: [
    { from: '견적', to: '수주', data: '견적정보(고객, 품목, 단가, 수량)' },
    { from: '수주', to: '생산지시', data: '수주정보(품목, 수량, 납기)' },
    { from: '수주', to: '매입관리', data: '발주정보(품의서 자동생성)', type: 'accounting' },
    { from: '생산지시', to: '작업지시', data: '생산지시(품목별 공정분류)' },
    { from: '작업지시', to: '작업자', data: '작업지시(공정, 품목, 수량)' },
    { from: '작업자', to: '품질검사', data: '작업실적(생산품)' },
    { from: '품질검사', to: '출하', data: '합격품(검사완료 제품)' },
    { from: '출하', to: '매출관리', data: '매출정보(거래명세, 세금계산서)', type: 'accounting' },
    { from: '출하', to: '수금관리', data: '수금대상(채권정보)', type: 'accounting' }
  ],
  // 기준정보 연동 매트릭스
  masterDataMatrix: [
    { master: '품목기준관리', usage: ['견적', '수주', '생산지시'], data: '품목정보(규격, 단가, 공정분류)' },
    { master: '공정기준관리', usage: ['생산지시', '작업지시', '작업자'], data: '공정정보(작업순서, 설비, 표준시간)' },
    { master: '품질기준관리', usage: ['품질검사'], data: '검사기준(항목, 기준값, 판정기준)' },
    { master: '거래처관리', usage: ['견적', '수주', '출하'], data: '거래처정보(연락처, 배송지, 신용등급)' },
    { master: '현장기준관리', usage: ['수주', '출하'], data: '현장정보(납품장소, 담당자)' },
    { master: '문서양식관리', usage: ['전 단계'], data: '문서양식(출력 템플릿, 레이아웃)' }
  ],
  // 회계 연동 정보
  accountingIntegration: {
    매출: {
      trigger: '출하 완료',
      targetMenu: '회계관리 > 매출관리',
      autoCreate: '거래명세서, 세금계산서 발행 대상',
      data: ['출하번호', '고객', '품목', '금액', '세액']
    },
    매입: {
      trigger: '발주/입고 완료',
      targetMenu: '회계관리 > 매입관리',
      autoCreate: '품의서 자동 생성',
      data: ['발주번호', '공급업체', '품목', '금액']
    },
    수금: {
      trigger: '세금계산서 발행',
      targetMenu: '회계관리 > 수금관리',
      autoCreate: '수금 대상 자동 등록',
      data: ['거래처', '채권금액', '입금예정일']
    },
    원가: {
      trigger: '작업 완료',
      targetMenu: '회계관리 > 원가관리',
      autoCreate: '수주별 원가 집계',
      data: ['자재비', '노무비', '경비', '제조원가']
    }
  }
};

// 메인 패널 컴포넌트
const UserFlowPanel = ({ isOpen, onClose, onNavigate }) => {
  const [activeTab, setActiveTab] = useState('detailed'); // detailed, patterns, menu, screen, path
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [expandedFlows, setExpandedFlows] = useState([]);
  const [expandedMenus, setExpandedMenus] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedStep, setSelectedStep] = useState(null);
  // 시작-끝 지정 기능용 상태
  const [startScreen, setStartScreen] = useState('');
  const [endScreen, setEndScreen] = useState('');
  const [foundPaths, setFoundPaths] = useState([]);

  // 화면 ID → 실제 뷰 매핑
  const screenToViewMap = {
    'quote-list': 'quote-list', 'quote-register': 'quote-register', 'quote-detail': 'quote-detail',
    'order-list': 'order-list', 'order-register': 'order-register', 'order-detail': 'order-detail',
    'shipment-list': 'shipment-list', 'shipment-register': 'shipment-register', 'shipment-detail': 'shipment-detail',
    'work-order-list': 'work-order-list', 'work-order-register': 'work-order-register', 'work-order-detail': 'work-order-detail',
    'worker-task-view': 'worker-task-view', 'work-result-list': 'work-result-list', 'work-result-register': 'work-result-register',
    'production-dashboard': 'production-status-board',
    'inspection-iqc': 'iqc-list', 'inspection-pqc': 'pqc-list', 'inspection-fqc': 'fqc-list',
    'defect-list': 'defect-list', 'defect-register': 'defect-register',
    'inbound-list': 'inbound-list', 'inbound-register': 'inbound-register',
    'stock-list': 'stock-list',
    'sales-list': 'sales-list', 'sales-statement': 'sales-statement', 'sales-tax-invoice': 'sales-tax-invoice',
    'collection-list': 'collection-list', 'collection-register': 'collection-register',
    'receivable-list': 'receivable-list', 'bill-list': 'bill-list',
    'purchase-list': 'purchase-list', 'purchase-register': 'purchase-register',
    'expense-list': 'expense-list', 'expense-register': 'expense-register',
    'cashbook-list': 'cashbook-list', 'cashbook-register': 'cashbook-register',
    'cost-list': 'cost-list', 'cost-detail': 'cost-detail',
    'acc-customer-list': 'acc-customer-list', 'acc-customer-register': 'acc-customer-register',
    'customer-list': 'customer-list', 'customer-register': 'customer-register',
    'site-list': 'site-list', 'site-register': 'site-register',
  };

  const handleNavigateToScreen = (screenId) => {
    if (!screenId || !onNavigate) return;
    const view = screenToViewMap[screenId] || screenId;
    onNavigate(null, view);
  };

  // 필터링된 플로우
  const filteredFlows = mainUserFlows.filter(flow => {
    const matchCategory = selectedCategory === 'all' || flow.category === selectedCategory;
    const matchSearch = !searchQuery ||
      flow.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      flow.description.toLowerCase().includes(searchQuery.toLowerCase());
    return matchCategory && matchSearch;
  });

  const toggleFlow = (flowId) => {
    setExpandedFlows(prev =>
      prev.includes(flowId) ? prev.filter(id => id !== flowId) : [...prev, flowId]
    );
  };

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

  // 경로 찾기 함수
  const handleFindPath = () => {
    if (startScreen && endScreen) {
      const paths = findFlowPath(startScreen, endScreen);
      setFoundPaths(paths);
    }
  };

  // 시작/끝 화면 초기화
  const handleResetPath = () => {
    setStartScreen('');
    setEndScreen('');
    setFoundPaths([]);
  };

  // 그룹별 화면 목록 (드롭다운용)
  const screenGroups = [
    { id: 'sales', name: '판매관리' },
    { id: 'production', name: '생산관리' },
    { id: 'quality', name: '품질관리' },
    { id: 'inventory', name: '자재관리' },
    { id: 'accounting', name: '회계관리' },
  ];

  if (!isOpen) return null;

  return (
    <div className="h-full w-full bg-white flex flex-col relative">
      {/* 헤더 - 그레이스케일 */}
      <div className="p-4 border-b border-gray-300 bg-gray-800 text-white">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-lg font-bold flex items-center gap-2">
            <GitBranch className="w-5 h-5" />
            업무 플로우
          </h2>
          <button onClick={onClose} className="p-1 hover:bg-gray-700 rounded">
            <X className="w-5 h-5" />
          </button>
        </div>
        <p className="text-sm text-gray-300">20가지 주요 패턴 및 화면별 플로우</p>
      </div>

      {/* 탭 - 그레이스케일 */}
      <div className="flex border-b border-gray-300 bg-gray-100">
        <button
          onClick={() => setActiveTab('detailed')}
          className={`flex-1 py-2 text-xs font-medium transition-colors ${
            activeTab === 'detailed'
              ? 'bg-white text-gray-800 border-b-2 border-gray-800'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          상세 플로우
        </button>
        <button
          onClick={() => setActiveTab('patterns')}
          className={`flex-1 py-2 text-xs font-medium transition-colors ${
            activeTab === 'patterns'
              ? 'bg-white text-gray-800 border-b-2 border-gray-800'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          주요 패턴
        </button>
        <button
          onClick={() => setActiveTab('menu')}
          className={`flex-1 py-2 text-xs font-medium transition-colors ${
            activeTab === 'menu'
              ? 'bg-white text-gray-800 border-b-2 border-gray-800'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          메뉴별
        </button>
        <button
          onClick={() => setActiveTab('screen')}
          className={`flex-1 py-2 text-xs font-medium transition-colors ${
            activeTab === 'screen'
              ? 'bg-white text-gray-800 border-b-2 border-gray-800'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          화면별
        </button>
        <button
          onClick={() => setActiveTab('path')}
          className={`flex-1 py-2 text-xs font-medium transition-colors ${
            activeTab === 'path'
              ? 'bg-white text-gray-800 border-b-2 border-gray-800'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          경로
        </button>
      </div>

      {/* 상세 플로우 탭 - 견적~출하 전체 프로세스 */}
      {activeTab === 'detailed' && (
        <div className="flex-1 overflow-y-auto">
          {/* 전체 플로우 다이어그램 */}
          <div className="p-3 border-b border-gray-200 bg-gray-50">
            <h3 className="text-sm font-bold text-gray-800 mb-2">견적 → 출하 전체 프로세스</h3>
            <div className="flex items-center justify-between gap-1 overflow-x-auto pb-2">
              {detailedProcessFlow.stages.map((stage, idx) => (
                <React.Fragment key={stage.id}>
                  <div className="flex flex-col items-center min-w-[50px]">
                    <div className="w-8 h-8 bg-gray-700 rounded-full flex items-center justify-center text-white text-xs font-bold">
                      {idx + 1}
                    </div>
                    <span className="text-xs text-gray-700 mt-1 text-center whitespace-nowrap">{stage.name}</span>
                  </div>
                  {idx < detailedProcessFlow.stages.length - 1 && (
                    <ArrowRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
                  )}
                </React.Fragment>
              ))}
            </div>
          </div>

          {/* 단계별 상세 정보 */}
          <div className="p-3 space-y-3">
            {detailedProcessFlow.stages.map((stage, idx) => (
              <div key={stage.id} className="bg-white border border-gray-300 rounded-lg overflow-hidden">
                {/* 단계 헤더 */}
                <div className="flex items-center gap-2 p-2 bg-gray-100 border-b border-gray-200">
                  <span className="w-6 h-6 bg-gray-700 text-white rounded-full flex items-center justify-center text-xs font-bold">
                    {idx + 1}
                  </span>
                  <div className="flex-1">
                    <h4 className="font-bold text-sm text-gray-800">{stage.name}</h4>
                    <p className="text-xs text-gray-500">{stage.description}</p>
                  </div>
                </div>

                <div className="p-2 space-y-2">
                  {/* 관련 화면 */}
                  <div className="text-xs">
                    <span className="font-medium text-gray-600">관련 화면: </span>
                    <span className="text-gray-700">
                      {stage.screens.map((screen, sIdx) => (
                        <span
                          key={screen}
                          onClick={() => handleNavigateToScreen(screen)}
                          className="cursor-pointer hover:underline text-gray-800"
                        >
                          {screen}{sIdx < stage.screens.length - 1 ? ', ' : ''}
                        </span>
                      ))}
                    </span>
                  </div>

                  {/* 문서 출력 정보 - 핵심 */}
                  <div className="bg-gray-50 border border-gray-200 rounded p-2">
                    <div className="text-xs font-bold text-gray-700 mb-1 flex items-center gap-1">
                      <FileText className="w-3 h-3" />
                      문서 출력
                    </div>
                    <div className="space-y-1">
                      {stage.documents.map((doc, dIdx) => (
                        <div key={dIdx} className="flex items-start gap-1 text-xs">
                          <span className={`px-1.5 py-0.5 rounded text-white text-xs ${
                            doc.type === '출력' ? 'bg-gray-700' : 'bg-gray-500'
                          }`}>
                            {doc.type}
                          </span>
                          <div className="flex-1">
                            <span className="font-medium text-gray-800">{doc.name}</span>
                            <span className="text-gray-500 ml-1">({doc.timing})</span>
                            <div className="text-gray-400 text-xs">
                              포함 데이터: {doc.data.join(', ')}
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* 데이터 흐름 */}
                  <div className="flex items-center gap-2 text-xs bg-white border border-gray-200 rounded p-2">
                    <div className="flex-1">
                      <div className="text-gray-500">입력</div>
                      <div className="text-gray-700">{stage.dataFlow.input.join(', ')}</div>
                    </div>
                    <ArrowRight className="w-4 h-4 text-gray-400" />
                    <div className="flex-1">
                      <div className="text-gray-500">출력</div>
                      <div className="text-gray-700">{stage.dataFlow.output.join(', ')}</div>
                    </div>
                  </div>

                  {/* 공정 분류 규칙 (생산지시 단계만) */}
                  {stage.processClassification && (
                    <div className="bg-gray-100 border border-gray-300 rounded p-2">
                      <div className="text-xs font-bold text-gray-700 mb-1">공정관리 기반 자동 분류</div>
                      <div className="space-y-1">
                        {stage.processClassification.rules.map((rule, rIdx) => (
                          <div key={rIdx} className="flex items-center gap-1 text-xs">
                            <span className="px-1.5 py-0.5 bg-gray-600 text-white rounded">{rule.process}</span>
                            <span className="text-gray-600">{rule.condition}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* 기준정보 연동 */}
                  {stage.masterRef && stage.masterRef.length > 0 && (
                    <div className="bg-gray-50 border border-gray-200 rounded p-2">
                      <div className="text-xs font-bold text-gray-700 mb-1">기준정보 연동</div>
                      <div className="flex flex-wrap gap-1">
                        {stage.masterRef.map((master, mIdx) => (
                          <span key={mIdx} className="px-1.5 py-0.5 bg-gray-200 text-gray-700 rounded text-xs">
                            {master}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* 품질기준관리 연동 (품질검사 단계만) */}
                  {stage.inspectionStandards && (
                    <div className="bg-gray-100 border border-gray-300 rounded p-2">
                      <div className="text-xs font-bold text-gray-700 mb-1">품질기준관리 연동</div>
                      <div className="space-y-1">
                        {stage.inspectionStandards.types.map((insp, iIdx) => (
                          <div key={iIdx} className="flex items-start gap-1 text-xs p-1 bg-white rounded border border-gray-200">
                            <span className="px-1.5 py-0.5 bg-gray-700 text-white rounded flex-shrink-0">{insp.type}</span>
                            <div className="flex-1">
                              <div className="font-medium text-gray-800">{insp.name}</div>
                              <div className="text-gray-500">{insp.standardRef}</div>
                              <div className="text-gray-400 text-xs">검사항목: {insp.criteria.join(', ')}</div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* 회계 연동 */}
                  {stage.accountingRef && (
                    <div className="bg-gray-50 border border-gray-300 rounded p-2">
                      <div className="text-xs font-bold text-gray-700 mb-1 flex items-center gap-1">
                        <CreditCard className="w-3 h-3" />
                        회계관리 연동
                      </div>
                      <div className="flex items-center gap-1 text-xs">
                        <span className="px-1.5 py-0.5 bg-gray-700 text-white rounded">{stage.accountingRef.type}</span>
                        <span className="text-gray-600">{stage.accountingRef.target}</span>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            ))}

            {/* 데이터 연동 매트릭스 */}
            <div className="bg-white border border-gray-300 rounded-lg overflow-hidden mt-4">
              <div className="p-2 bg-gray-700 text-white">
                <h4 className="font-bold text-sm">데이터 연동 흐름</h4>
              </div>
              <div className="p-2">
                <div className="space-y-1">
                  {detailedProcessFlow.dataMatrix.map((flow, idx) => (
                    <div key={idx} className={`flex items-center gap-1 text-xs p-1.5 rounded border ${
                      flow.type === 'accounting' ? 'bg-gray-100 border-gray-300' : 'bg-gray-50 border-gray-200'
                    }`}>
                      <span className="px-1.5 py-0.5 bg-gray-200 text-gray-700 rounded font-medium">{flow.from}</span>
                      <ArrowRight className="w-3 h-3 text-gray-400" />
                      <span className={`px-1.5 py-0.5 rounded font-medium ${
                        flow.type === 'accounting' ? 'bg-gray-600 text-white' : 'bg-gray-200 text-gray-700'
                      }`}>{flow.to}</span>
                      <span className="text-gray-500 ml-1 flex-1 truncate">{flow.data}</span>
                      {flow.type === 'accounting' && (
                        <span className="px-1 py-0.5 bg-gray-500 text-white rounded text-xs">회계</span>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* 기준정보 연동 매트릭스 */}
            <div className="bg-white border border-gray-300 rounded-lg overflow-hidden mt-4">
              <div className="p-2 bg-gray-700 text-white">
                <h4 className="font-bold text-sm">기준정보 연동 매트릭스</h4>
              </div>
              <div className="p-2">
                <div className="space-y-1">
                  {detailedProcessFlow.masterDataMatrix.map((master, idx) => (
                    <div key={idx} className="flex items-start gap-1 text-xs p-1.5 bg-gray-50 rounded border border-gray-200">
                      <span className="px-1.5 py-0.5 bg-gray-600 text-white rounded font-medium flex-shrink-0">{master.master}</span>
                      <div className="flex-1">
                        <div className="flex flex-wrap gap-1 mb-1">
                          {master.usage.map((stage, sIdx) => (
                            <span key={sIdx} className="px-1 py-0.5 bg-gray-200 text-gray-700 rounded text-xs">{stage}</span>
                          ))}
                        </div>
                        <div className="text-gray-500">{master.data}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* 회계관리 연동 상세 */}
            <div className="bg-white border border-gray-300 rounded-lg overflow-hidden mt-4">
              <div className="p-2 bg-gray-700 text-white flex items-center gap-1">
                <CreditCard className="w-4 h-4" />
                <h4 className="font-bold text-sm">회계관리 연동 상세</h4>
              </div>
              <div className="p-2 space-y-2">
                {Object.entries(detailedProcessFlow.accountingIntegration).map(([key, value]) => (
                  <div key={key} className="bg-gray-50 border border-gray-200 rounded p-2">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="px-1.5 py-0.5 bg-gray-700 text-white rounded text-xs font-medium">{key}</span>
                      <span className="text-xs text-gray-600">{value.targetMenu}</span>
                    </div>
                    <div className="text-xs space-y-1">
                      <div className="flex items-center gap-1">
                        <span className="text-gray-500">트리거:</span>
                        <span className="text-gray-700">{value.trigger}</span>
                      </div>
                      <div className="flex items-center gap-1">
                        <span className="text-gray-500">자동생성:</span>
                        <span className="text-gray-700">{value.autoCreate}</span>
                      </div>
                      <div className="flex items-start gap-1">
                        <span className="text-gray-500 flex-shrink-0">연동데이터:</span>
                        <span className="text-gray-700">{value.data.join(', ')}</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* 문서 출력 요약 테이블 */}
            <div className="bg-white border border-gray-300 rounded-lg overflow-hidden mt-4">
              <div className="p-2 bg-gray-700 text-white">
                <h4 className="font-bold text-sm">문서 출력 시점 요약</h4>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-xs">
                  <thead className="bg-gray-100">
                    <tr>
                      <th className="p-2 text-left text-gray-700 border-b border-gray-200">단계</th>
                      <th className="p-2 text-left text-gray-700 border-b border-gray-200">문서명</th>
                      <th className="p-2 text-left text-gray-700 border-b border-gray-200">출력 시점</th>
                    </tr>
                  </thead>
                  <tbody>
                    {detailedProcessFlow.stages.flatMap((stage) =>
                      stage.documents.filter(doc => doc.type === '출력').map((doc, dIdx) => (
                        <tr key={`${stage.id}-${dIdx}`} className="border-b border-gray-100 hover:bg-gray-50">
                          <td className="p-2 text-gray-700 font-medium">{stage.name}</td>
                          <td className="p-2 text-gray-800">{doc.name}</td>
                          <td className="p-2 text-gray-600">{doc.timing}</td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 주요 패턴 탭 */}
      {activeTab === 'patterns' && (
        <>
          {/* 검색 및 필터 */}
          <div className="p-3 border-b border-gray-200 space-y-2">
            <div className="relative">
              <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder="플로우 검색..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-8 pr-3 py-1.5 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-gray-400 focus:border-gray-400"
              />
            </div>
            <div className="flex flex-wrap gap-1">
              <button
                onClick={() => setSelectedCategory('all')}
                className={`px-2 py-1 rounded text-xs transition-colors ${
                  selectedCategory === 'all' ? 'bg-black text-white' : 'bg-gray-100 text-gray-600 border border-gray-300 hover:bg-gray-200'
                }`}
              >
                전체
              </button>
              {flowCategories.map((cat) => (
                <button
                  key={cat.id}
                  onClick={() => setSelectedCategory(cat.id)}
                  className={`px-2 py-1 rounded text-xs transition-colors ${
                    selectedCategory === cat.id
                      ? 'bg-black text-white'
                      : 'bg-gray-100 text-gray-600 border border-gray-300 hover:bg-gray-200'
                  }`}
                >
                  {cat.name}
                </button>
              ))}
            </div>
          </div>

          {/* 카테고리별 통계 - 그레이스케일 */}
          <div className="p-3 border-b border-gray-200 bg-gray-50">
            <div className="grid grid-cols-5 gap-1">
              {flowCategories.map((cat) => {
                const count = mainUserFlows.filter(f => f.category === cat.id).length;
                return (
                  <div
                    key={cat.id}
                    className={`bg-white border border-gray-300 rounded p-1.5 text-center cursor-pointer hover:bg-gray-100 ${
                      selectedCategory === cat.id ? 'ring-2 ring-gray-800' : ''
                    }`}
                    onClick={() => setSelectedCategory(cat.id)}
                  >
                    <div className="text-lg font-bold text-gray-800">{count}</div>
                    <div className="text-xs text-gray-500 truncate">{cat.name}</div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* 플로우 목록 */}
          <div className="flex-1 overflow-y-auto p-3">
            {filteredFlows.length === 0 ? (
              <div className="text-center text-gray-500 py-8">
                검색 결과가 없습니다
              </div>
            ) : (
              filteredFlows.map((flow) => (
                <FlowCard
                  key={flow.id}
                  flow={flow}
                  isExpanded={expandedFlows.includes(flow.id)}
                  onToggle={() => toggleFlow(flow.id)}
                  onNavigate={handleNavigateToScreen}
                  onStepClick={setSelectedStep}
                />
              ))
            )}
          </div>
        </>
      )}

      {/* 메뉴별 탭 */}
      {activeTab === 'menu' && (
        <div className="flex-1 overflow-y-auto p-3">
          {Object.entries(menuFlows).map(([menuId, menuData]) => (
            <MenuFlowCard
              key={menuId}
              menuId={menuId}
              menuData={menuData}
              isExpanded={expandedMenus.includes(menuId)}
              onToggle={() => toggleMenu(menuId)}
              onNavigate={handleNavigateToScreen}
            />
          ))}
        </div>
      )}

      {/* 화면별 탭 */}
      {activeTab === 'screen' && (
        <div className="flex-1 overflow-y-auto p-3">
          <div className="grid grid-cols-1 gap-2">
            {Object.entries(screenFlows).map(([screenId, screenData]) => (
              <ScreenActionCard
                key={screenId}
                screenId={screenId}
                screenData={screenData}
                onNavigate={handleNavigateToScreen}
              />
            ))}
          </div>
        </div>
      )}

      {/* 경로 찾기 탭 */}
      {activeTab === 'path' && (
        <div className="flex-1 overflow-y-auto">
          {/* 시작/끝 선택 영역 */}
          <div className="p-3 border-b border-gray-200 space-y-3 bg-gray-50">
            <div className="text-xs font-medium text-gray-700 mb-2">시작 → 끝 화면을 선택하여 플로우 경로를 찾습니다</div>

            {/* 시작 화면 선택 */}
            <div>
              <label className="block text-xs text-gray-600 mb-1">시작 화면</label>
              <select
                value={startScreen}
                onChange={(e) => setStartScreen(e.target.value)}
                className="w-full px-2 py-1.5 border border-gray-300 rounded text-xs focus:ring-1 focus:ring-gray-400"
              >
                <option value="">화면 선택...</option>
                {screenGroups.map(group => (
                  <optgroup key={group.id} label={group.name}>
                    {allScreens.filter(s => s.group === group.id).map(screen => (
                      <option key={screen.id} value={screen.id}>{screen.name}</option>
                    ))}
                  </optgroup>
                ))}
              </select>
            </div>

            {/* 끝 화면 선택 */}
            <div>
              <label className="block text-xs text-gray-600 mb-1">끝 화면</label>
              <select
                value={endScreen}
                onChange={(e) => setEndScreen(e.target.value)}
                className="w-full px-2 py-1.5 border border-gray-300 rounded text-xs focus:ring-1 focus:ring-gray-400"
              >
                <option value="">화면 선택...</option>
                {screenGroups.map(group => (
                  <optgroup key={group.id} label={group.name}>
                    {allScreens.filter(s => s.group === group.id).map(screen => (
                      <option key={screen.id} value={screen.id}>{screen.name}</option>
                    ))}
                  </optgroup>
                ))}
              </select>
            </div>

            {/* 버튼 */}
            <div className="flex gap-2">
              <button
                onClick={handleFindPath}
                disabled={!startScreen || !endScreen}
                className={`flex-1 py-2 rounded text-xs font-medium flex items-center justify-center gap-1 ${
                  startScreen && endScreen
                    ? 'bg-black text-white hover:bg-gray-800'
                    : 'bg-gray-200 text-gray-400 cursor-not-allowed'
                }`}
              >
                <Search className="w-3 h-3" />
                경로 찾기
              </button>
              <button
                onClick={handleResetPath}
                className="px-3 py-2 bg-white border border-gray-300 rounded text-xs text-gray-700 hover:bg-gray-100"
              >
                초기화
              </button>
            </div>
          </div>

          {/* 검색 결과 */}
          <div className="p-3">
            {foundPaths.length === 0 && startScreen && endScreen && (
              <div className="text-center text-gray-500 py-8 text-sm">
                해당 경로를 포함하는 플로우가 없습니다
              </div>
            )}
            {foundPaths.length === 0 && (!startScreen || !endScreen) && (
              <div className="text-center text-gray-400 py-8 text-sm">
                시작과 끝 화면을 선택하세요
              </div>
            )}
            {foundPaths.length > 0 && (
              <div className="space-y-3">
                <div className="text-xs text-gray-600 font-medium">
                  {foundPaths.length}개의 플로우 경로를 찾았습니다
                </div>
                {foundPaths.map((path, idx) => (
                  <div key={idx} className="bg-white border border-gray-300 rounded-lg p-3">
                    <div className="flex items-center gap-2 mb-2">
                      <span className="w-5 h-5 bg-gray-700 text-white rounded-full flex items-center justify-center text-xs">
                        {idx + 1}
                      </span>
                      <span className="font-medium text-sm text-gray-800">{path.flowName}</span>
                      <span className="px-2 py-0.5 bg-gray-100 text-gray-600 rounded text-xs">
                        {flowCategories.find(c => c.id === path.category)?.name || path.category}
                      </span>
                    </div>
                    {/* 스텝 표시 */}
                    <div className="flex flex-wrap items-center gap-1 text-xs">
                      {path.steps.map((step, stepIdx) => (
                        <React.Fragment key={step.id}>
                          <span
                            className="px-2 py-1 bg-gray-100 text-gray-700 border border-gray-300 rounded cursor-pointer hover:bg-gray-200"
                            onClick={() => handleNavigateToScreen(step.screen)}
                          >
                            {step.label}
                          </span>
                          {stepIdx < path.steps.length - 1 && (
                            <ArrowRight className="w-3 h-3 text-gray-400" />
                          )}
                        </React.Fragment>
                      ))}
                    </div>
                    {/* 분기 조건 */}
                    {path.branches && path.branches.length > 0 && (
                      <div className="mt-2 pt-2 border-t border-gray-200">
                        <div className="text-xs text-gray-500">분기 조건:</div>
                        {path.branches.map((branch, bIdx) => (
                          <div key={bIdx} className="flex items-center gap-1 text-xs text-gray-600 mt-1">
                            <Diamond className="w-3 h-3 text-gray-400" />
                            <span>{branch.condition}</span>
                            <ArrowRight className="w-3 h-3" />
                            <span>{branch.label}</span>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {/* 선택된 스텝 상세 - 그레이스케일, 패널 내부 오버레이 */}
      {selectedStep && (
        <div className="absolute inset-0 bg-black/50 flex items-center justify-center p-3 z-10" onClick={() => setSelectedStep(null)}>
          <div className="bg-white rounded-lg border border-gray-300 p-3 w-full max-w-[280px]" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-3">
              <h3 className="font-bold text-gray-800">{selectedStep.label}</h3>
              <button onClick={() => setSelectedStep(null)} className="p-1 hover:bg-gray-100 rounded">
                <X className="w-4 h-4" />
              </button>
            </div>
            <div className="space-y-2 text-sm">
              <div>
                <span className="text-gray-500">메뉴: </span>
                <span className="text-gray-800">{selectedStep.menu}</span>
              </div>
              <div>
                <span className="text-gray-500">작업: </span>
                <span className="text-gray-800">{selectedStep.action}</span>
              </div>
              {selectedStep.screen && (
                <div>
                  <span className="text-gray-500">화면: </span>
                  <span className="text-gray-700 font-mono">{selectedStep.screen}</span>
                </div>
              )}
            </div>
            {selectedStep.screen && (
              <button
                onClick={() => {
                  handleNavigateToScreen(selectedStep.screen);
                  setSelectedStep(null);
                }}
                className="w-full mt-3 py-2 bg-black text-white rounded text-sm font-medium hover:bg-gray-800 flex items-center justify-center gap-1"
              >
                <Eye className="w-4 h-4" />
                화면으로 이동
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default UserFlowPanel;
