/**
 * ComprehensiveFlowPanel - 종합 메뉴별 워크플로우 플로우차트
 * 모든 메뉴 > 페이지 > 섹션 > 항목 > 속성 > 상태값 연결 플로우
 * 담당부서별 유저플로우 다이어그램 추가
 * 와이어프레임 스타일 (그레이스케일, 아이콘 없음)
 */
import React, { useState } from 'react';
import { STATE_TRANSITIONS, COMPREHENSIVE_MENU_FEATURES, FULL_WORKFLOW } from '../configs/comprehensiveMenuFeatures';
import { departmentFlows, departmentList, dataRegistrationFlow } from '../configs/userFlowPatterns';

// 상태 전이 다이어그램 컴포넌트
const StateTransitionDiagram = ({ entity, transitions }) => {
  const { states, transitions: trans } = transitions;

  return (
    <div className="bg-white border border-gray-300 rounded-lg p-4 mb-4">
      <h4 className="font-semibold text-black mb-3">
        {entity} 상태 전이 다이어그램
      </h4>

      {/* 상태 목록 */}
      <div className="flex flex-wrap gap-2 mb-4">
        {states.map((state, idx) => (
          <span
            key={idx}
            className="px-2 py-1 border border-gray-400 rounded text-xs font-medium text-black bg-white"
          >
            {state}
          </span>
        ))}
      </div>

      {/* 전이 다이어그램 */}
      <div className="space-y-2">
        {trans.map((t, idx) => {
          const fromStates = Array.isArray(t.from) ? t.from : [t.from];
          return (
            <div key={idx} className="flex items-center gap-2 text-sm bg-gray-50 border border-gray-200 p-2 rounded">
              <div className="flex flex-wrap gap-1">
                {fromStates.map((f, fi) => (
                  <span key={fi} className="px-2 py-0.5 border border-gray-400 rounded text-xs text-black bg-white">
                    {f}
                  </span>
                ))}
              </div>
              <span className="text-black flex-shrink-0">→</span>
              <span className="px-2 py-0.5 border border-gray-400 rounded text-xs text-black bg-white">
                {t.to}
              </span>
              <span className="text-gray-500 mx-2">|</span>
              <span className="text-black font-medium">{t.trigger}</span>
              <span className="text-gray-500">→</span>
              <span className="text-gray-700 text-xs">{t.action}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// 섹션 항목 상세 컴포넌트
const SectionItemDetail = ({ item, badgeNumber }) => {
  return (
    <div className="flex items-start gap-2 py-1 text-sm border-b border-gray-100 last:border-b-0">
      <span className="w-5 h-5 rounded-full border border-gray-400 bg-white text-black text-xs flex items-center justify-center flex-shrink-0 font-medium">
        {badgeNumber}
      </span>
      <span className="px-1.5 py-0.5 border border-gray-300 rounded text-xs text-black bg-white">
        {item.type}
      </span>
      <span className="font-medium text-black">{item.label}</span>
      {item.required && <span className="text-black text-xs border border-gray-400 px-1 rounded">필수</span>}
      {item.autoGenerate && <span className="text-black text-xs border border-gray-400 px-1 rounded">자동</span>}
      {item.action && <span className="text-gray-600 text-xs">→ {item.action}</span>}
      {item.pattern && <span className="text-gray-600 text-xs">[{item.pattern}]</span>}
    </div>
  );
};

// 화면 섹션 컴포넌트
const ScreenSection = ({ section, startBadge }) => {
  const [expanded, setExpanded] = useState(true);

  return (
    <div className="border-l-2 border-gray-300 pl-3 mb-2">
      <button
        onClick={() => setExpanded(!expanded)}
        className="flex items-center gap-2 text-sm font-medium text-black hover:underline w-full text-left"
      >
        <span className="text-black">{expanded ? '▼' : '▶'}</span>
        <span className="text-black">{section.title}</span>
        <span className="text-xs text-gray-600">({section.items?.length || 0}개 항목)</span>
      </button>
      {expanded && section.items && (
        <div className="mt-1 ml-4 space-y-0.5">
          {section.items.map((item, idx) => (
            <SectionItemDetail key={item.id} item={item} badgeNumber={startBadge + idx} />
          ))}
        </div>
      )}
    </div>
  );
};

// 화면 컴포넌트
const ScreenView = ({ screenKey, screen }) => {
  const [expanded, setExpanded] = useState(false);

  let badgeCounter = 1;

  return (
    <div className="bg-white border border-gray-300 rounded p-2 mb-2">
      <button
        onClick={() => setExpanded(!expanded)}
        className="flex items-center gap-2 text-sm font-semibold text-black hover:underline w-full text-left"
      >
        <span className="text-black">{expanded ? '▼' : '▶'}</span>
        <span className="text-black">{screen.title}</span>
        {screen.stateTransitions && (
          <span className="text-xs border border-gray-400 px-1.5 py-0.5 rounded ml-2 text-black">
            상태관리
          </span>
        )}
      </button>
      {expanded && (
        <div className="mt-2 ml-4">
          {/* 상태 전이가 있는 경우 표시 */}
          {screen.stateTransitions && (
            <div className="mb-3 p-2 bg-gray-50 border border-gray-200 rounded text-xs">
              <span className="font-medium text-black">상태값: </span>
              {screen.stateTransitions.states.map((s, i) => (
                <span key={i} className="inline-block px-1.5 py-0.5 border border-gray-400 rounded mr-1 mb-1 text-black bg-white">
                  {s}
                </span>
              ))}
            </div>
          )}

          {/* 섹션별 항목 */}
          {screen.sections?.map((section) => {
            const currentStart = badgeCounter;
            badgeCounter += section.items?.length || 0;
            return (
              <ScreenSection
                key={section.id}
                section={section}
                startBadge={currentStart}
              />
            );
          })}
        </div>
      )}
    </div>
  );
};

// 페이지 컴포넌트
const PageView = ({ page }) => {
  const [expanded, setExpanded] = useState(false);

  return (
    <div className="border border-gray-300 rounded-lg mb-3 overflow-hidden">
      <button
        onClick={() => setExpanded(!expanded)}
        className="flex items-center gap-2 p-3 bg-white hover:bg-gray-50 w-full text-left"
      >
        <span className="text-black">{expanded ? '▼' : '▶'}</span>
        <span className="font-semibold text-black">{page.label}</span>
        <span className="text-xs text-gray-600 ml-2">{page.description}</span>
      </button>
      {expanded && (
        <div className="p-3 border-t border-gray-300 bg-white">
          {/* 워크플로우 정보 */}
          {page.workflow && (
            <div className="mb-3 p-2 bg-gray-50 border border-gray-200 rounded text-sm">
              <div className="font-medium text-black mb-1">워크플로우</div>
              <div className="flex flex-wrap gap-1 mb-2">
                {page.workflow.steps?.map((step, i) => (
                  <React.Fragment key={i}>
                    <span className="px-2 py-0.5 bg-white border border-gray-300 rounded text-xs text-black">{step}</span>
                    {i < page.workflow.steps.length - 1 && (
                      <span className="text-gray-500 self-center">→</span>
                    )}
                  </React.Fragment>
                ))}
              </div>
              {page.workflow.dataFlow && (
                <div className="text-xs text-gray-700">
                  <div><span className="font-medium text-black">입력:</span> {page.workflow.dataFlow.input?.join(', ')}</div>
                  <div><span className="font-medium text-black">출력:</span> {page.workflow.dataFlow.output?.join(', ')}</div>
                  <div><span className="font-medium text-black">연계:</span> {page.workflow.dataFlow.linkedTo?.join(', ')}</div>
                </div>
              )}
            </div>
          )}

          {/* 화면별 상세 */}
          {page.screens && Object.entries(page.screens).map(([key, screen]) => (
            <ScreenView key={key} screenKey={key} screen={screen} />
          ))}
        </div>
      )}
    </div>
  );
};

// 메뉴 그룹 컴포넌트
const MenuGroup = ({ menuKey, menu }) => {
  const [expanded, setExpanded] = useState(false);

  return (
    <div className="mb-4">
      <button
        onClick={() => setExpanded(!expanded)}
        className="flex items-center gap-3 p-3 bg-black text-white rounded-t-lg w-full text-left hover:bg-gray-800"
      >
        <span className="text-white">{expanded ? '▼' : '▶'}</span>
        <span className="font-bold text-white">{menu.label}</span>
        <span className="text-xs text-gray-300 ml-2">{menu.description}</span>
      </button>
      {expanded && (
        <div className="border border-t-0 border-gray-300 rounded-b-lg p-3 bg-gray-50">
          {menu.pages && Object.entries(menu.pages).map(([pageKey, page]) => (
            <PageView key={pageKey} page={page} />
          ))}
        </div>
      )}
    </div>
  );
};

// 플로우차트 노드 컴포넌트 (가운데 정렬)
const FlowNode = ({ step, index }) => {
  // 노드 타입별 스타일
  const getNodeStyle = () => {
    switch (step.type) {
      case 'start':
      case 'end':
        return 'rounded-full bg-gray-200 border-2 border-gray-500 px-6 py-2';
      case 'decision':
        return 'bg-white border-2 border-gray-500';
      case 'screen':
        return 'rounded bg-gray-100 border-2 border-gray-600 px-4 py-2';
      case 'action':
      default:
        return 'rounded bg-white border-2 border-gray-400 px-4 py-2';
    }
  };

  // 분기 노드 (마름모)
  if (step.type === 'decision') {
    return (
      <div className="flex flex-col items-center">
        {/* 마름모 노드 */}
        <div className="relative w-32 h-32 flex items-center justify-center">
          <div
            className="absolute w-24 h-24 bg-white border-2 border-gray-500"
            style={{ transform: 'rotate(45deg)' }}
          />
          <div className="relative z-10 text-center px-2">
            <div className="text-xs text-gray-500 mb-0.5">[{index}]</div>
            <div className="font-medium text-black text-sm">{step.label}</div>
          </div>
        </div>
        {/* 분기 옵션 표시 */}
        {step.options && (
          <div className="flex gap-4 mt-1 text-xs">
            {step.options.map((opt, idx) => (
              <span key={idx} className="px-2 py-0.5 border border-gray-400 rounded bg-white text-black">
                {opt}
              </span>
            ))}
          </div>
        )}
      </div>
    );
  }

  // 시작/종료 노드 (타원)
  if (step.type === 'start' || step.type === 'end') {
    return (
      <div className={`inline-flex items-center justify-center ${getNodeStyle()}`}>
        <span className="text-xs text-gray-500 mr-1">[{index}]</span>
        <span className="font-medium text-black text-sm">{step.label}</span>
      </div>
    );
  }

  // 일반 노드 (화면, 액션)
  return (
    <div className={`inline-block text-center max-w-xs ${getNodeStyle()}`}>
      <div className="flex items-center justify-center gap-1 mb-1">
        <span className="text-xs text-gray-500">[{index}]</span>
        <span className={`px-1.5 py-0.5 text-xs rounded ${
          step.type === 'screen' ? 'bg-gray-200 text-gray-700' : 'bg-gray-100 text-gray-600'
        }`}>
          {step.type === 'screen' ? '화면' : '액션'}
        </span>
        {step.required && (
          <span className="px-1 py-0.5 text-xs bg-gray-300 text-black rounded">필수</span>
        )}
      </div>
      <div className="font-medium text-black text-sm">{step.label}</div>
      {step.ui && (
        <div className="text-xs text-gray-600 mt-1 border-t border-gray-200 pt-1">
          {step.ui}
        </div>
      )}
      {step.menu && (
        <div className="text-xs text-gray-500 mt-0.5">{step.menu}</div>
      )}
      {step.condition && (
        <div className="text-xs text-black mt-1 font-medium bg-gray-100 px-1 rounded inline-block">
          조건: {step.condition}
        </div>
      )}
    </div>
  );
};

// 연결선 컴포넌트
const FlowConnector = ({ isLast }) => {
  if (isLast) return null;
  return (
    <div className="flex flex-col items-center py-1">
      <div className="w-0.5 h-6 bg-gray-400" />
      <div className="text-gray-500 text-lg leading-none">▼</div>
    </div>
  );
};

// 시나리오 플로우차트 컴포넌트 (가운데 정렬)
const ScenarioFlowChart = ({ scenario }) => {
  const [expanded, setExpanded] = useState(false);

  return (
    <div className="border border-gray-300 rounded-lg mb-3 overflow-hidden">
      <button
        onClick={() => setExpanded(!expanded)}
        className="flex items-center gap-2 p-3 bg-white hover:bg-gray-50 w-full text-left"
      >
        <span className="text-black">{expanded ? '▼' : '▶'}</span>
        <span className="font-semibold text-black">{scenario.name}</span>
        <span className="text-xs text-gray-600 ml-2">{scenario.description}</span>
        <span className="text-xs px-2 py-0.5 border border-gray-400 rounded ml-auto text-black">
          {scenario.steps.length}단계
        </span>
      </button>

      {expanded && (
        <div className="p-4 border-t border-gray-300 bg-white">
          {/* 플로우차트 - 가운데 정렬 */}
          <div className="flex flex-col items-center py-4 bg-gray-50 rounded-lg border border-gray-200">
            {scenario.steps.map((step, idx) => (
              <React.Fragment key={step.id}>
                <FlowNode step={step} index={idx + 1} />
                <FlowConnector isLast={idx === scenario.steps.length - 1} />
              </React.Fragment>
            ))}
          </div>

          {/* 분기 정보 테이블 */}
          {scenario.branches && scenario.branches.length > 0 && (
            <div className="mt-4 p-3 bg-gray-50 border border-gray-300 rounded">
              <h5 className="font-medium text-black mb-2 text-sm">분기 조건 매핑</h5>
              <table className="w-full text-xs border-collapse">
                <thead>
                  <tr className="bg-gray-100">
                    <th className="p-2 text-left border border-gray-300 text-black">From</th>
                    <th className="p-2 text-center border border-gray-300 text-black">→</th>
                    <th className="p-2 text-left border border-gray-300 text-black">To</th>
                    <th className="p-2 text-left border border-gray-300 text-black">조건</th>
                  </tr>
                </thead>
                <tbody>
                  {scenario.branches.map((branch, idx) => (
                    <tr key={idx} className={idx % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                      <td className="p-2 border border-gray-300 text-black font-mono">{branch.from}</td>
                      <td className="p-2 border border-gray-300 text-center text-gray-500">→</td>
                      <td className="p-2 border border-gray-300 text-black font-mono">{branch.to}</td>
                      <td className="p-2 border border-gray-300 text-black font-medium">
                        {branch.condition || '-'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// 담당부서별 플로우 다이어그램 컴포넌트
const DepartmentFlowDiagram = ({ department }) => {
  const [expanded, setExpanded] = useState(false);
  const deptData = departmentFlows[department.id];

  if (!deptData) return null;

  return (
    <div className="mb-4">
      <button
        onClick={() => setExpanded(!expanded)}
        className="flex items-center gap-3 p-3 bg-black text-white rounded-t-lg w-full text-left hover:bg-gray-800"
      >
        <span className="text-white">{expanded ? '▼' : '▶'}</span>
        <span className="font-bold text-white">{deptData.name}</span>
        <span className="text-xs text-gray-300 ml-2">{deptData.description}</span>
        <span className="text-xs px-2 py-0.5 border border-gray-400 rounded ml-auto text-white">
          {deptData.scenarios.length}개 시나리오
        </span>
      </button>

      {expanded && (
        <div className="border border-t-0 border-gray-300 rounded-b-lg p-3 bg-gray-50">
          {deptData.scenarios.map((scenario) => (
            <ScenarioFlowChart key={scenario.id} scenario={scenario} />
          ))}
        </div>
      )}
    </div>
  );
};

// 전체 업무 플로우 다이어그램
const FullWorkflowDiagram = () => {
  const [expanded, setExpanded] = useState(true);

  return (
    <div className="bg-gray-50 border border-gray-300 rounded-lg p-4 mb-6">
      <button
        onClick={() => setExpanded(!expanded)}
        className="flex items-center gap-2 font-bold text-black mb-3"
      >
        <span className="text-black">{expanded ? '▼' : '▶'}</span>
        <span className="text-black">전체 업무 플로우 (견적 → 수주 → 생산 → 검사 → 출하 → 정산)</span>
      </button>

      {expanded && (
        <div className="space-y-3">
          {FULL_WORKFLOW?.stages?.map((stage, idx) => (
            <div key={stage.id} className="flex items-start gap-3">
              <div className="flex-shrink-0 w-8 h-8 rounded-full border-2 border-black bg-white text-black flex items-center justify-center font-bold">
                {idx + 1}
              </div>
              <div className="flex-1 bg-white border border-gray-300 rounded-lg p-3">
                <div className="font-semibold text-black">{stage.name}</div>
                <div className="text-sm text-gray-700">{stage.description}</div>
                <div className="mt-2 flex flex-wrap gap-2">
                  {stage.screens?.map((screen, si) => (
                    <span key={si} className="px-2 py-1 bg-gray-100 border border-gray-300 rounded text-xs text-black">
                      {screen}
                    </span>
                  ))}
                </div>
                {stage.outputs && (
                  <div className="mt-2 text-xs text-gray-700">
                    <span className="font-medium text-black">출력: </span>
                    {stage.outputs.join(', ')}
                  </div>
                )}
                {stage.dataConnections && (
                  <div className="mt-1 text-xs text-gray-700">
                    <span className="font-medium text-black">연계: </span>
                    {stage.dataConnections.join(' → ')}
                  </div>
                )}
              </div>
              {idx < FULL_WORKFLOW.stages.length - 1 && (
                <span className="text-gray-500 mt-3 text-xl">↓</span>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// 데이터 등록 순서 플로우 컴포넌트
const DataRegistrationFlowDiagram = () => {
  const [expandedPhases, setExpandedPhases] = useState({});
  const [expandedSteps, setExpandedSteps] = useState({});

  const togglePhase = (phaseId) => {
    setExpandedPhases(prev => ({ ...prev, [phaseId]: !prev[phaseId] }));
  };

  const toggleStep = (stepId) => {
    setExpandedSteps(prev => ({ ...prev, [stepId]: !prev[stepId] }));
  };

  if (!dataRegistrationFlow) {
    return <div className="text-gray-500 p-4">데이터 등록 플로우 정보가 없습니다.</div>;
  }

  return (
    <div className="space-y-4">
      {/* 설명 */}
      <div className="bg-gray-100 border border-gray-300 rounded-lg p-3">
        <h3 className="font-bold text-black mb-2 text-sm">{dataRegistrationFlow.name}</h3>
        <p className="text-xs text-gray-700">{dataRegistrationFlow.description}</p>
      </div>

      {/* 의존성 다이어그램 요약 */}
      {dataRegistrationFlow.dependencyDiagram && (
        <div className="bg-white border border-gray-300 rounded-lg p-3">
          <h4 className="font-semibold text-black mb-2 text-sm">데이터 계층 구조</h4>
          <div className="space-y-2">
            {dataRegistrationFlow.dependencyDiagram.layers?.map((layer, idx) => (
              <div key={idx} className="flex items-start gap-2">
                <div className="flex-shrink-0 w-6 h-6 rounded-full border-2 border-black bg-white text-black flex items-center justify-center text-xs font-bold">
                  {layer.layer}
                </div>
                <div className="flex-1">
                  <div className="font-medium text-black text-xs">{layer.name}</div>
                  <div className="flex flex-wrap gap-1 mt-1">
                    {layer.items?.map((item, i) => (
                      <span key={i} className="px-1.5 py-0.5 bg-gray-100 border border-gray-300 rounded text-xs text-black">
                        {item}
                      </span>
                    ))}
                  </div>
                  <div className="text-xs text-gray-600 mt-1">{layer.note}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 페이즈별 등록 순서 */}
      {dataRegistrationFlow.phases?.map((phase, phaseIdx) => (
        <div key={phase.id} className="border border-gray-300 rounded-lg overflow-hidden">
          <button
            onClick={() => togglePhase(phase.id)}
            className="flex items-center gap-2 w-full p-3 bg-black text-white text-left hover:bg-gray-800"
          >
            <span className="text-white">{expandedPhases[phase.id] ? '▼' : '▶'}</span>
            <span className="font-bold text-white text-sm">{phase.name}</span>
            <span className="text-xs text-gray-300 ml-auto">
              {phase.steps?.length || 0}단계
            </span>
          </button>

          {expandedPhases[phase.id] && (
            <div className="p-3 bg-gray-50 space-y-2">
              {phase.description && (
                <p className="text-xs text-gray-700 mb-2 p-2 bg-white border border-gray-200 rounded">
                  {phase.description}
                </p>
              )}

              {phase.steps?.map((step, stepIdx) => (
                <div key={step.id} className="border border-gray-300 rounded bg-white">
                  <button
                    onClick={() => toggleStep(step.id)}
                    className="flex items-center gap-2 w-full p-2 text-left hover:bg-gray-50"
                  >
                    <span className="w-5 h-5 rounded-full bg-gray-200 border border-gray-400 text-black text-xs flex items-center justify-center font-bold">
                      {stepIdx + 1}
                    </span>
                    <span className="text-black">{expandedSteps[step.id] ? '▼' : '▶'}</span>
                    <span className="font-medium text-black text-sm">{step.name}</span>
                    <span className="text-xs text-gray-500 ml-auto">{step.menu}</span>
                  </button>

                  {expandedSteps[step.id] && (
                    <div className="p-3 border-t border-gray-200 space-y-3">
                      {/* 메뉴/화면 정보 */}
                      <div className="grid grid-cols-2 gap-2 text-xs">
                        <div>
                          <span className="font-medium text-black">메뉴: </span>
                          <span className="text-gray-700">{step.menu}</span>
                        </div>
                        <div>
                          <span className="font-medium text-black">화면: </span>
                          <span className="text-gray-700">{step.screen}</span>
                        </div>
                      </div>

                      {/* 선행 조건 */}
                      {step.requiredBefore && step.requiredBefore.length > 0 && (
                        <div className="text-xs">
                          <span className="font-medium text-black">선행 필수: </span>
                          <span className="text-gray-700">{step.requiredBefore.join(', ')}</span>
                        </div>
                      )}

                      {/* 사용처 */}
                      {step.usedBy && step.usedBy.length > 0 && (
                        <div className="text-xs">
                          <span className="font-medium text-black">사용처: </span>
                          <span className="text-gray-700">{step.usedBy.join(', ')}</span>
                        </div>
                      )}

                      {/* 출력 데이터 */}
                      {step.outputData && (
                        <div className="text-xs p-2 bg-gray-50 border border-gray-200 rounded">
                          <span className="font-medium text-black">출력: </span>
                          <span className="text-gray-700">{step.outputData}</span>
                        </div>
                      )}

                      {/* 필드 상세 */}
                      {step.fields && step.fields.length > 0 && (
                        <div className="space-y-2">
                          <div className="font-medium text-black text-xs">필드 상세:</div>
                          {step.fields.map((section, secIdx) => (
                            <div key={secIdx} className="border-l-2 border-gray-300 pl-2">
                              <div className="font-medium text-black text-xs mb-1">{section.section}</div>
                              <div className="space-y-1">
                                {section.items?.map((item, itemIdx) => (
                                  <div key={itemIdx} className="flex items-center gap-2 text-xs bg-gray-50 p-1 rounded">
                                    <span className="text-black font-medium">{item.field}</span>
                                    <span className="px-1 py-0.5 border border-gray-300 rounded text-xs text-gray-600">{item.type}</span>
                                    {item.required && (
                                      <span className="px-1 py-0.5 bg-gray-200 rounded text-xs text-black">필수</span>
                                    )}
                                    {item.format && (
                                      <span className="text-gray-500">[{item.format}]</span>
                                    )}
                                    {item.example && (
                                      <span className="text-gray-500 italic">예: {item.example}</span>
                                    )}
                                  </div>
                                ))}
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      ))}

      {/* 최소 필수 데이터 체크리스트 */}
      {dataRegistrationFlow.minimumRequiredData && (
        <div className="bg-white border border-gray-300 rounded-lg p-3">
          <h4 className="font-semibold text-black mb-2 text-sm">최소 필수 데이터 체크리스트</h4>
          <p className="text-xs text-gray-600 mb-2">{dataRegistrationFlow.minimumRequiredData.description}</p>
          <div className="overflow-x-auto">
            <table className="w-full text-xs border-collapse">
              <thead>
                <tr className="bg-gray-100">
                  <th className="p-1.5 text-left border border-gray-300 text-black">순서</th>
                  <th className="p-1.5 text-left border border-gray-300 text-black">분류</th>
                  <th className="p-1.5 text-left border border-gray-300 text-black">항목</th>
                  <th className="p-1.5 text-left border border-gray-300 text-black">최소 수량</th>
                  <th className="p-1.5 text-left border border-gray-300 text-black">예시</th>
                </tr>
              </thead>
              <tbody>
                {dataRegistrationFlow.minimumRequiredData.checklist?.map((item, idx) => (
                  <tr key={idx} className={idx % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                    <td className="p-1.5 border border-gray-300 text-black text-center">{item.order}</td>
                    <td className="p-1.5 border border-gray-300 text-black">{item.category}</td>
                    <td className="p-1.5 border border-gray-300 text-black font-medium">{item.item}</td>
                    <td className="p-1.5 border border-gray-300 text-gray-700">{item.minCount}</td>
                    <td className="p-1.5 border border-gray-300 text-gray-600">{item.example}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
};

// 메인 컴포넌트
const ComprehensiveFlowPanel = ({ isOpen, onClose, width = 600, onWidthChange, isInline = false }) => {
  const [activeTab, setActiveTab] = useState('departments'); // departments, workflow, states, menus
  const [isDragging, setIsDragging] = useState(false);

  // 드래그 시작
  const handleMouseDown = (e) => {
    e.preventDefault();
    setIsDragging(true);

    const startX = e.clientX;
    const startWidth = width;

    const handleMouseMove = (e) => {
      const delta = startX - e.clientX;
      const newWidth = Math.max(400, Math.min(1200, startWidth + delta));
      if (onWidthChange) {
        onWidthChange(newWidth);
      }
    };

    const handleMouseUp = () => {
      setIsDragging(false);
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
  };

  if (!isOpen) return null;

  // 인라인 모드 (푸시 패널)
  if (isInline) {
    return (
      <div className="flex h-full bg-white border-l border-gray-300 flex-shrink-0" style={{ width: `${width}px` }}>
        {/* 드래그 핸들 - 왼쪽 */}
        <div
          className={`w-1 bg-gray-200 hover:bg-blue-400 cursor-col-resize flex-shrink-0 transition-colors ${isDragging ? 'bg-blue-500' : ''}`}
          onMouseDown={handleMouseDown}
          title="드래그하여 너비 조절"
        />

        <div className="flex-1 flex flex-col overflow-hidden">
          {/* 헤더 */}
          <div className="flex items-center justify-between p-3 border-b border-gray-300 bg-gray-100 flex-shrink-0">
            <div className="min-w-0 flex-1">
              <h2 className="text-base font-bold text-black truncate">종합 워크플로우</h2>
              <p className="text-xs text-gray-600 truncate">메뉴별 &gt; 페이지별 &gt; 섹션별 플로우</p>
            </div>
            <button onClick={onClose} className="p-1.5 hover:bg-gray-200 rounded border border-gray-300 ml-2 flex-shrink-0">
              <span className="text-black font-bold text-sm">✕</span>
            </button>
          </div>

          {/* 탭 */}
          <div className="flex border-b border-gray-300 overflow-x-auto flex-shrink-0">
            <button
              onClick={() => setActiveTab('departments')}
              className={`px-3 py-1.5 text-xs font-medium whitespace-nowrap ${activeTab === 'departments' ? 'border-b-2 border-black text-black bg-gray-100' : 'text-gray-600'}`}
            >
              부서별 플로우
            </button>
            <button
              onClick={() => setActiveTab('workflow')}
              className={`px-3 py-1.5 text-xs font-medium whitespace-nowrap ${activeTab === 'workflow' ? 'border-b-2 border-black text-black bg-gray-100' : 'text-gray-600'}`}
            >
              업무 플로우
            </button>
            <button
              onClick={() => setActiveTab('states')}
              className={`px-3 py-1.5 text-xs font-medium whitespace-nowrap ${activeTab === 'states' ? 'border-b-2 border-black text-black bg-gray-100' : 'text-gray-600'}`}
            >
              상태 전이
            </button>
            <button
              onClick={() => setActiveTab('menus')}
              className={`px-3 py-1.5 text-xs font-medium whitespace-nowrap ${activeTab === 'menus' ? 'border-b-2 border-black text-black bg-gray-100' : 'text-gray-600'}`}
            >
              메뉴별 상세
            </button>
            <button
              onClick={() => setActiveTab('registration')}
              className={`px-3 py-1.5 text-xs font-medium whitespace-nowrap ${activeTab === 'registration' ? 'border-b-2 border-black text-black bg-gray-100' : 'text-gray-600'}`}
            >
              데이터 등록 순서
            </button>
          </div>

          {/* 컨텐츠 */}
          <div className="flex-1 overflow-y-auto p-3">
            {activeTab === 'departments' && (
              <div>
                <div className="mb-3 p-2 bg-gray-100 border border-gray-300 rounded-lg">
                  <h3 className="font-bold text-black mb-1 text-sm">담당부서별 유저플로우</h3>
                  <p className="text-xs text-gray-700">
                    각 담당부서별 시나리오와 UI 기능 상세 플로우차트
                  </p>
                </div>
                <div className="grid grid-cols-2 gap-1 mb-3">
                  {departmentList.map((dept) => {
                    const deptData = departmentFlows[dept.id];
                    return (
                      <div key={dept.id} className="p-1.5 bg-white border border-gray-300 rounded text-xs">
                        <span className="font-medium text-black">{dept.name}</span>
                        <span className="text-gray-600 ml-1">({deptData?.scenarios?.length || 0})</span>
                      </div>
                    );
                  })}
                </div>
                {departmentList.map((dept) => (
                  <DepartmentFlowDiagram key={dept.id} department={dept} />
                ))}
              </div>
            )}

            {activeTab === 'workflow' && (
              <div>
                <FullWorkflowDiagram />
                <div className="bg-white border border-gray-300 rounded-lg p-3">
                  <h3 className="font-bold text-black mb-2 text-sm">메뉴간 데이터 연결</h3>
                  <div className="overflow-x-auto">
                    <table className="w-full text-xs border-collapse">
                      <thead>
                        <tr className="bg-gray-100">
                          <th className="p-1.5 text-left border border-gray-300 text-black">소스</th>
                          <th className="p-1.5 text-left border border-gray-300 text-black">대상</th>
                          <th className="p-1.5 text-left border border-gray-300 text-black">전달 데이터</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr><td className="p-1.5 border border-gray-300 text-black">견적관리</td><td className="p-1.5 border border-gray-300 text-black">수주관리</td><td className="p-1.5 border border-gray-300 text-black">견적정보, 제품목록</td></tr>
                        <tr className="bg-gray-50"><td className="p-1.5 border border-gray-300 text-black">수주관리</td><td className="p-1.5 border border-gray-300 text-black">작업지시</td><td className="p-1.5 border border-gray-300 text-black">수주정보, BOM</td></tr>
                        <tr><td className="p-1.5 border border-gray-300 text-black">작업지시</td><td className="p-1.5 border border-gray-300 text-black">품질검사</td><td className="p-1.5 border border-gray-300 text-black">공정결과</td></tr>
                        <tr className="bg-gray-50"><td className="p-1.5 border border-gray-300 text-black">품질검사</td><td className="p-1.5 border border-gray-300 text-black">출하관리</td><td className="p-1.5 border border-gray-300 text-black">검사결과</td></tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            )}

            {activeTab === 'states' && (
              <div>
                <h3 className="font-bold text-black mb-3 text-sm">상태 전이 다이어그램</h3>
                {Object.entries(STATE_TRANSITIONS).map(([entity, trans]) => (
                  <StateTransitionDiagram
                    key={entity}
                    entity={{ quote: '견적', order: '수주', workOrder: '작업지시', inspection: '검사', shipment: '출하' }[entity] || entity}
                    transitions={trans}
                  />
                ))}
              </div>
            )}

            {activeTab === 'menus' && (
              <div>
                <h3 className="font-bold text-black mb-3 text-sm">메뉴별 상세 플로우</h3>
                {Object.entries(COMPREHENSIVE_MENU_FEATURES).map(([menuKey, menu]) => (
                  <MenuGroup key={menuKey} menuKey={menuKey} menu={menu} />
                ))}
              </div>
            )}

            {activeTab === 'registration' && (
              <DataRegistrationFlowDiagram />
            )}
          </div>

          {/* 푸터 */}
          <div className="p-2 border-t border-gray-300 bg-gray-100 text-xs text-gray-600 flex-shrink-0">
            {departmentList.length}개 부서 | {Object.keys(COMPREHENSIVE_MENU_FEATURES).length}개 메뉴 | {dataRegistrationFlow?.phases?.length || 0}개 등록 단계
          </div>
        </div>
      </div>
    );
  }

  // 기존 모달 모드 (폴백)
  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 z-[100] flex justify-end">
      <div className="w-[800px] bg-white h-full shadow-xl flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-300 bg-gray-100">
          <div>
            <h2 className="text-lg font-bold text-black">종합 워크플로우 플로우차트</h2>
            <p className="text-xs text-gray-600">메뉴별 &gt; 페이지별 &gt; 섹션별 &gt; 항목별 &gt; 속성별 &gt; 상태값 연결</p>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-gray-200 rounded border border-gray-300">
            <span className="text-black font-bold">✕</span>
          </button>
        </div>

        {/* 탭 */}
        <div className="flex border-b border-gray-300 overflow-x-auto">
          <button
            onClick={() => setActiveTab('departments')}
            className={`px-4 py-2 text-sm font-medium whitespace-nowrap ${activeTab === 'departments' ? 'border-b-2 border-black text-black bg-gray-100' : 'text-gray-600'}`}
          >
            담당부서별 플로우
          </button>
          <button
            onClick={() => setActiveTab('workflow')}
            className={`px-4 py-2 text-sm font-medium whitespace-nowrap ${activeTab === 'workflow' ? 'border-b-2 border-black text-black bg-gray-100' : 'text-gray-600'}`}
          >
            전체 업무 플로우
          </button>
          <button
            onClick={() => setActiveTab('states')}
            className={`px-4 py-2 text-sm font-medium whitespace-nowrap ${activeTab === 'states' ? 'border-b-2 border-black text-black bg-gray-100' : 'text-gray-600'}`}
          >
            상태 전이 다이어그램
          </button>
          <button
            onClick={() => setActiveTab('menus')}
            className={`px-4 py-2 text-sm font-medium whitespace-nowrap ${activeTab === 'menus' ? 'border-b-2 border-black text-black bg-gray-100' : 'text-gray-600'}`}
          >
            메뉴별 상세 플로우
          </button>
          <button
            onClick={() => setActiveTab('registration')}
            className={`px-4 py-2 text-sm font-medium whitespace-nowrap ${activeTab === 'registration' ? 'border-b-2 border-black text-black bg-gray-100' : 'text-gray-600'}`}
          >
            데이터 등록 순서
          </button>
        </div>

        {/* 컨텐츠 */}
        <div className="flex-1 overflow-y-auto p-4">
          {activeTab === 'departments' && (
            <div>
              <div className="mb-4 p-3 bg-gray-100 border border-gray-300 rounded-lg">
                <h3 className="font-bold text-black mb-2">담당부서별 유저플로우</h3>
                <p className="text-sm text-gray-700">
                  각 담당부서별 담당자들이 수행해야 하는 모든 시나리오와 UI 기능 상세를 플로우차트로 표시합니다.
                  분기(Y/N) 조건과 필수 액션을 포함합니다.
                </p>
              </div>

              {/* 부서 요약 */}
              <div className="grid grid-cols-2 gap-2 mb-4">
                {departmentList.map((dept) => {
                  const deptData = departmentFlows[dept.id];
                  return (
                    <div key={dept.id} className="p-2 bg-white border border-gray-300 rounded text-sm">
                      <span className="font-medium text-black">{dept.name}</span>
                      <span className="text-gray-600 ml-2">
                        ({deptData?.scenarios?.length || 0}개 시나리오)
                      </span>
                    </div>
                  );
                })}
              </div>

              {/* 부서별 플로우차트 */}
              {departmentList.map((dept) => (
                <DepartmentFlowDiagram key={dept.id} department={dept} />
              ))}
            </div>
          )}

          {activeTab === 'workflow' && (
            <div>
              <FullWorkflowDiagram />

              {/* 데이터 연결 매트릭스 */}
              <div className="bg-white border border-gray-300 rounded-lg p-4">
                <h3 className="font-bold text-black mb-3">
                  메뉴간 데이터 연결 매트릭스
                </h3>
                <div className="overflow-x-auto">
                  <table className="w-full text-xs border-collapse">
                    <thead>
                      <tr className="bg-gray-100">
                        <th className="p-2 text-left border border-gray-300 text-black">소스</th>
                        <th className="p-2 text-left border border-gray-300 text-black">대상</th>
                        <th className="p-2 text-left border border-gray-300 text-black">전달 데이터</th>
                        <th className="p-2 text-left border border-gray-300 text-black">트리거</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td className="p-2 border border-gray-300 text-black">견적관리</td>
                        <td className="p-2 border border-gray-300 text-black">수주관리</td>
                        <td className="p-2 border border-gray-300 text-black">견적정보, 제품목록, 금액</td>
                        <td className="p-2 border border-gray-300 text-black">수주전환 버튼</td>
                      </tr>
                      <tr className="bg-gray-50">
                        <td className="p-2 border border-gray-300 text-black">수주관리</td>
                        <td className="p-2 border border-gray-300 text-black">작업지시</td>
                        <td className="p-2 border border-gray-300 text-black">수주정보, 제품/BOM, 납기</td>
                        <td className="p-2 border border-gray-300 text-black">작업지시 생성</td>
                      </tr>
                      <tr>
                        <td className="p-2 border border-gray-300 text-black">작업지시</td>
                        <td className="p-2 border border-gray-300 text-black">품질검사</td>
                        <td className="p-2 border border-gray-300 text-black">작업지시정보, 공정결과</td>
                        <td className="p-2 border border-gray-300 text-black">검사 요청</td>
                      </tr>
                      <tr className="bg-gray-50">
                        <td className="p-2 border border-gray-300 text-black">품질검사</td>
                        <td className="p-2 border border-gray-300 text-black">출하관리</td>
                        <td className="p-2 border border-gray-300 text-black">검사결과, 합격판정</td>
                        <td className="p-2 border border-gray-300 text-black">출하 등록</td>
                      </tr>
                      <tr>
                        <td className="p-2 border border-gray-300 text-black">출하관리</td>
                        <td className="p-2 border border-gray-300 text-black">수금관리</td>
                        <td className="p-2 border border-gray-300 text-black">출하정보, 금액</td>
                        <td className="p-2 border border-gray-300 text-black">배송완료</td>
                      </tr>
                      <tr className="bg-gray-50">
                        <td className="p-2 border border-gray-300 text-black">품목기준</td>
                        <td className="p-2 border border-gray-300 text-black">전체 메뉴</td>
                        <td className="p-2 border border-gray-300 text-black">품목마스터, BOM</td>
                        <td className="p-2 border border-gray-300 text-gray-600">참조 데이터</td>
                      </tr>
                      <tr>
                        <td className="p-2 border border-gray-300 text-black">거래처관리</td>
                        <td className="p-2 border border-gray-300 text-black">견적/수주/출하</td>
                        <td className="p-2 border border-gray-300 text-black">거래처정보, 신용등급</td>
                        <td className="p-2 border border-gray-300 text-gray-600">참조 데이터</td>
                      </tr>
                      <tr className="bg-gray-50">
                        <td className="p-2 border border-gray-300 text-black">현장관리</td>
                        <td className="p-2 border border-gray-300 text-black">견적/수주/출하</td>
                        <td className="p-2 border border-gray-300 text-black">현장정보, 주소</td>
                        <td className="p-2 border border-gray-300 text-gray-600">참조 데이터</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'states' && (
            <div>
              <h3 className="font-bold text-black mb-4">
                엔티티별 상태 전이 다이어그램
              </h3>

              {Object.entries(STATE_TRANSITIONS).map(([entity, trans]) => (
                <StateTransitionDiagram
                  key={entity}
                  entity={{
                    quote: '견적',
                    order: '수주',
                    workOrder: '작업지시',
                    inspection: '검사',
                    shipment: '출하',
                  }[entity] || entity}
                  transitions={trans}
                />
              ))}

              {/* 상태간 연결 관계 */}
              <div className="bg-white border border-gray-300 rounded-lg p-4 mt-4">
                <h4 className="font-semibold text-black mb-3">엔티티간 상태 연결</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center gap-2 p-2 bg-gray-50 border border-gray-200 rounded">
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">견적:확정</span>
                    <span className="text-black">→</span>
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">수주:수주등록</span>
                    <span className="text-gray-600 ml-2">수주전환 시 자동 생성</span>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-gray-50 border border-gray-200 rounded">
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">수주:수주등록</span>
                    <span className="text-black">→</span>
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">작업지시:지시대기</span>
                    <span className="text-gray-600 ml-2">작업지시 생성 시</span>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-gray-50 border border-gray-200 rounded">
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">작업지시:작업중</span>
                    <span className="text-black">→</span>
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">검사:검사대기</span>
                    <span className="text-gray-600 ml-2">작업 완료 시 PQC 자동 생성</span>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-gray-50 border border-gray-200 rounded">
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">검사:합격</span>
                    <span className="text-black">→</span>
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">수주:출하대기</span>
                    <span className="text-gray-600 ml-2">FQC 합격 시 수주상태 변경</span>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-gray-50 border border-gray-200 rounded">
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">수주:출하대기</span>
                    <span className="text-black">→</span>
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">출하:출고대기</span>
                    <span className="text-gray-600 ml-2">출하등록 가능 상태</span>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-gray-50 border border-gray-200 rounded">
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">출하:배송완료</span>
                    <span className="text-black">→</span>
                    <span className="px-2 py-1 border border-gray-400 rounded text-xs text-black bg-white">수주:출하완료</span>
                    <span className="text-gray-600 ml-2">납품 완료 시 수주상태 최종 변경</span>
                  </div>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'menus' && (
            <div>
              <h3 className="font-bold text-black mb-4">
                메뉴별 페이지 &gt; 화면 &gt; 섹션 &gt; 항목 상세
              </h3>

              {Object.entries(COMPREHENSIVE_MENU_FEATURES).map(([menuKey, menu]) => (
                <MenuGroup key={menuKey} menuKey={menuKey} menu={menu} />
              ))}
            </div>
          )}

          {activeTab === 'registration' && (
            <DataRegistrationFlowDiagram />
          )}
        </div>

        {/* 푸터 */}
        <div className="p-3 border-t border-gray-300 bg-gray-100 text-xs text-gray-600">
          담당부서 {departmentList.length}개 |
          전체 시나리오 {Object.values(departmentFlows).reduce((sum, d) => sum + (d?.scenarios?.length || 0), 0)}개 |
          전체 {Object.keys(COMPREHENSIVE_MENU_FEATURES).length}개 메뉴 |
          상태 전이 {Object.keys(STATE_TRANSITIONS).length}개 엔티티 |
          데이터 등록 {dataRegistrationFlow?.phases?.length || 0}단계
        </div>
      </div>
    </div>
  );
};

export default ComprehensiveFlowPanel;
