import React, { useState, useMemo } from 'react';
import {
  Book, FileText, GitBranch, Package, DollarSign, Code, Shield, MessageSquare, Bell,
  ChevronRight, ChevronDown, Search, RefreshCw, ArrowRight, Circle, CheckCircle,
  AlertCircle, XCircle, Clock, Layers, Users, Truck, ClipboardList, Settings
} from 'lucide-react';

import {
  documentStatusPolicy,
  documentLinkagePolicy,
  processFlowPolicy,
  materialPolicy,
  pricingPolicy,
  itemCodePolicy,
  authorizationPolicy,
  terminologyPolicy,
  notificationPolicy,
} from '../configs/policyConfig';

// ============ 정책서 메인 컴포넌트 ============
const PolicyGuide = ({ onNavigate }) => {
  const [activeCategory, setActiveCategory] = useState('overview');
  const [searchTerm, setSearchTerm] = useState('');
  const [expandedSections, setExpandedSections] = useState({});

  // 카테고리 목록
  const categories = [
    { id: 'overview', label: '개요', icon: Book },
    { id: 'documentStatus', label: '문서 상태 정책', icon: FileText },
    { id: 'documentLinkage', label: '문서 연동 정책', icon: GitBranch },
    { id: 'processFlow', label: '공정 흐름 정책', icon: Layers },
    { id: 'material', label: '자재 정책', icon: Package },
    { id: 'pricing', label: '단가 정책', icon: DollarSign },
    { id: 'itemCode', label: '품목코드 정책', icon: Code },
    { id: 'authorization', label: '권한 정책', icon: Shield },
    { id: 'terminology', label: '용어 정의', icon: MessageSquare },
    { id: 'notification', label: '알림 정책', icon: Bell },
  ];

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

  // 현재 시간 표시 (동적 업데이트 표시용)
  const lastUpdated = useMemo(() => {
    return new Date().toLocaleString('ko-KR');
  }, []);

  return (
    <div className="space-y-4">
      {/* 헤더 */}
      <div className="flex justify-between items-center">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-indigo-100 rounded-lg flex items-center justify-center">
            <Book className="w-5 h-5 text-indigo-600" />
          </div>
          <div>
            <h2 className="text-xl font-bold text-gray-900">시스템 정책서</h2>
            <p className="text-sm text-gray-500">업무 규칙, 상태값, 연동 정책 통합 가이드</p>
          </div>
        </div>
        <div className="flex items-center gap-2 text-sm text-gray-500">
          <RefreshCw className="w-4 h-4" />
          <span>마지막 업데이트: {lastUpdated}</span>
        </div>
      </div>

      {/* 검색 */}
      <div className="bg-white rounded-xl border p-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <input
            type="text"
            placeholder="정책 검색... (예: 수주, 상태, 코드규칙)"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border-0 text-sm focus:ring-0"
          />
        </div>
      </div>

      <div className="flex gap-4">
        {/* 사이드바 - 카테고리 목록 */}
        <div className="w-64 bg-white rounded-xl border p-4">
          <h3 className="text-sm font-medium text-gray-700 mb-3">정책 카테고리</h3>
          <div className="space-y-1">
            {categories.map(cat => {
              const Icon = cat.icon;
              return (
                <button
                  key={cat.id}
                  onClick={() => setActiveCategory(cat.id)}
                  className={`w-full flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${
                    activeCategory === cat.id
                      ? 'bg-indigo-50 text-indigo-700 font-medium'
                      : 'text-gray-600 hover:bg-gray-50'
                  }`}
                >
                  <Icon className="w-4 h-4" />
                  {cat.label}
                </button>
              );
            })}
          </div>
        </div>

        {/* 메인 콘텐츠 */}
        <div className="flex-1 bg-white rounded-xl border p-6 overflow-auto" style={{ maxHeight: 'calc(100vh - 250px)' }}>
          {activeCategory === 'overview' && <OverviewSection />}
          {activeCategory === 'documentStatus' && (
            <DocumentStatusSection
              policy={documentStatusPolicy}
              expanded={expandedSections}
              toggleSection={toggleSection}
              searchTerm={searchTerm}
            />
          )}
          {activeCategory === 'documentLinkage' && (
            <DocumentLinkageSection policy={documentLinkagePolicy} />
          )}
          {activeCategory === 'processFlow' && (
            <ProcessFlowSection policy={processFlowPolicy} />
          )}
          {activeCategory === 'material' && (
            <MaterialSection policy={materialPolicy} />
          )}
          {activeCategory === 'pricing' && (
            <PricingSection policy={pricingPolicy} />
          )}
          {activeCategory === 'itemCode' && (
            <ItemCodeSection policy={itemCodePolicy} />
          )}
          {activeCategory === 'authorization' && (
            <AuthorizationSection policy={authorizationPolicy} />
          )}
          {activeCategory === 'terminology' && (
            <TerminologySection policy={terminologyPolicy} searchTerm={searchTerm} />
          )}
          {activeCategory === 'notification' && (
            <NotificationSection policy={notificationPolicy} />
          )}
        </div>
      </div>
    </div>
  );
};

// ============ 개요 섹션 ============
const OverviewSection = () => (
  <div className="space-y-6">
    <div>
      <h3 className="text-lg font-bold text-gray-900 mb-2">시스템 정책서 개요</h3>
      <p className="text-sm text-gray-600">
        이 문서는 SAM MES 시스템의 모든 업무 규칙, 상태값, 연동 정책을 통합 관리합니다.
        데이터가 변경될 때마다 이 정책서는 자동으로 업데이트됩니다.
      </p>
    </div>

    <div className="grid grid-cols-3 gap-4">
      <div className="bg-blue-50 rounded-lg p-4">
        <div className="flex items-center gap-2 mb-2">
          <FileText className="w-5 h-5 text-blue-600" />
          <span className="font-medium text-blue-900">문서 상태 관리</span>
        </div>
        <p className="text-sm text-blue-700">
          견적, 수주, 생산지시, 작업지시, 출하, 검사 등 모든 문서의 상태 흐름과 전환 조건
        </p>
      </div>
      <div className="bg-green-50 rounded-lg p-4">
        <div className="flex items-center gap-2 mb-2">
          <GitBranch className="w-5 h-5 text-green-600" />
          <span className="font-medium text-green-900">문서 연동</span>
        </div>
        <p className="text-sm text-green-700">
          문서 간 연결 관계, 자동 생성 규칙, 상태 동기화 정책
        </p>
      </div>
      <div className="bg-purple-50 rounded-lg p-4">
        <div className="flex items-center gap-2 mb-2">
          <Layers className="w-5 h-5 text-purple-600" />
          <span className="font-medium text-purple-900">공정 흐름</span>
        </div>
        <p className="text-sm text-purple-700">
          스크린, 슬랫, 절곡, 샤프트 공정의 단계별 흐름과 합류점 관리
        </p>
      </div>
    </div>

    <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
      <div className="flex items-start gap-2">
        <AlertCircle className="w-5 h-5 text-yellow-600 mt-0.5" />
        <div>
          <p className="font-medium text-yellow-800">동적 정책 관리</p>
          <p className="text-sm text-yellow-700 mt-1">
            이 정책서는 설정 파일(policyConfig.js)에서 데이터를 직접 읽어옵니다.
            설정이 변경되면 정책서 내용도 자동으로 반영됩니다.
          </p>
        </div>
      </div>
    </div>
  </div>
);

// ============ 문서 상태 정책 섹션 ============
const DocumentStatusSection = ({ policy, expanded, toggleSection, searchTerm }) => {
  const statusColorMap = {
    gray: 'bg-gray-100 text-gray-700',
    blue: 'bg-blue-100 text-blue-700',
    green: 'bg-green-100 text-green-700',
    red: 'bg-red-100 text-red-700',
    orange: 'bg-orange-100 text-orange-700',
    yellow: 'bg-yellow-100 text-yellow-700',
    purple: 'bg-purple-100 text-purple-700',
  };

  const filteredDocs = Object.entries(policy).filter(([key, doc]) => {
    if (!searchTerm) return true;
    const term = searchTerm.toLowerCase();
    return key.includes(term) || doc.name.includes(term) ||
      doc.statuses?.some(s => s.label.includes(term) || s.description.includes(term));
  });

  return (
    <div className="space-y-6">
      <div>
        <h3 className="text-lg font-bold text-gray-900 mb-2">문서 상태 정책</h3>
        <p className="text-sm text-gray-600">각 문서 유형별 상태값과 상태 전환 규칙을 정의합니다.</p>
      </div>

      {filteredDocs.map(([docKey, docPolicy]) => (
        <div key={docKey} className="border rounded-lg overflow-hidden">
          <button
            onClick={() => toggleSection(docKey)}
            className="w-full flex items-center justify-between p-4 bg-gray-50 hover:bg-gray-100"
          >
            <div className="flex items-center gap-2">
              <FileText className="w-5 h-5 text-gray-600" />
              <span className="font-medium text-gray-900">{docPolicy.name}</span>
              {docPolicy.numberingRule && (
                <span className="text-xs text-gray-500 font-mono bg-gray-200 px-2 py-0.5 rounded">
                  {docPolicy.numberingRule}
                </span>
              )}
            </div>
            {expanded[docKey] ? (
              <ChevronDown className="w-5 h-5 text-gray-500" />
            ) : (
              <ChevronRight className="w-5 h-5 text-gray-500" />
            )}
          </button>

          {expanded[docKey] && (
            <div className="p-4 space-y-4">
              {/* 상태값 목록 */}
              {docPolicy.statuses && (
                <div>
                  <h4 className="text-sm font-medium text-gray-700 mb-2">상태값</h4>
                  <div className="flex flex-wrap gap-2">
                    {docPolicy.statuses.map(status => (
                      <div key={status.code} className="flex items-center gap-1">
                        <span className={`px-2 py-1 rounded text-xs font-medium ${statusColorMap[status.color]}`}>
                          {status.label}
                        </span>
                        <span className="text-xs text-gray-500">({status.code})</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 상태 전환 흐름도 */}
              {docPolicy.transitions && (
                <div>
                  <h4 className="text-sm font-medium text-gray-700 mb-2">상태 전환 규칙</h4>
                  <div className="space-y-2">
                    {docPolicy.transitions.map((trans, idx) => (
                      <div key={idx} className="flex items-center gap-2 text-sm bg-gray-50 p-2 rounded">
                        <span className="font-mono text-gray-700">{trans.from}</span>
                        <ArrowRight className="w-4 h-4 text-gray-400" />
                        <span className="font-mono text-gray-700">{trans.to}</span>
                        <span className="text-gray-500">|</span>
                        <span className="text-blue-600">{trans.action}</span>
                        {trans.createsDocument && (
                          <span className="text-xs bg-green-100 text-green-700 px-1 rounded">
                            + {trans.createsDocument}
                          </span>
                        )}
                        {trans.requiredFields?.length > 0 && (
                          <span className="text-xs text-orange-600">
                            필수: {trans.requiredFields.join(', ')}
                          </span>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 검사 유형 (inspection인 경우) */}
              {docPolicy.types && (
                <div>
                  <h4 className="text-sm font-medium text-gray-700 mb-2">검사 유형</h4>
                  <div className="grid grid-cols-3 gap-2">
                    {Object.entries(docPolicy.types).map(([typeCode, typeInfo]) => (
                      <div key={typeCode} className="bg-gray-50 p-3 rounded">
                        <div className="font-medium text-gray-900">{typeInfo.name} ({typeCode})</div>
                        <div className="text-xs text-gray-500 mt-1">{typeInfo.description}</div>
                        <div className="text-xs text-blue-600 mt-1">타이밍: {typeInfo.timing}</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      ))}
    </div>
  );
};

// ============ 문서 연동 정책 섹션 ============
const DocumentLinkageSection = ({ policy }) => (
  <div className="space-y-6">
    <div>
      <h3 className="text-lg font-bold text-gray-900 mb-2">문서 연동 정책</h3>
      <p className="text-sm text-gray-600">문서 간 연결 관계와 자동 상태 동기화 규칙을 정의합니다.</p>
    </div>

    {/* 문서 관계 */}
    <div>
      <h4 className="text-sm font-medium text-gray-700 mb-3">문서 간 연결 관계</h4>
      <div className="space-y-3">
        {policy.relationships.map((rel, idx) => (
          <div key={idx} className="border rounded-lg p-4 bg-gray-50">
            <div className="flex items-center gap-3 mb-2">
              <span className="font-mono bg-blue-100 text-blue-700 px-2 py-1 rounded">{rel.parent}</span>
              <ArrowRight className="w-4 h-4 text-gray-400" />
              <span className="font-mono bg-green-100 text-green-700 px-2 py-1 rounded">{rel.child}</span>
              <span className="text-xs bg-gray-200 text-gray-600 px-2 py-0.5 rounded">{rel.relationship}</span>
            </div>
            <p className="text-sm text-gray-600 mb-2">{rel.description}</p>
            <div className="text-xs text-gray-500">
              <span className="font-medium">연결필드:</span> {rel.linkField} |
              <span className="font-medium ml-2">상속필드:</span> {rel.inheritFields.join(', ')}
            </div>
          </div>
        ))}
      </div>
    </div>

    {/* 상태 동기화 */}
    <div>
      <h4 className="text-sm font-medium text-gray-700 mb-3">상태 자동 동기화</h4>
      <div className="space-y-2">
        {policy.statusSync.map((sync, idx) => (
          <div key={idx} className="border rounded-lg p-3">
            <div className="flex items-center gap-2 text-sm">
              <span className="font-medium text-orange-600">트리거:</span>
              <span className="font-mono">{sync.trigger.document}.{sync.trigger.status}</span>
            </div>
            <div className="mt-2 pl-4">
              {sync.updates.map((update, uidx) => (
                <div key={uidx} className="flex items-center gap-2 text-sm text-gray-600">
                  <ArrowRight className="w-3 h-3" />
                  <span className="font-mono">{update.document}</span>
                  {update.condition && <span className="text-xs text-gray-500">({update.condition})</span>}
                  <span className="text-green-600">→ {update.newStatus}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// ============ 공정 흐름 정책 섹션 ============
const ProcessFlowSection = ({ policy }) => (
  <div className="space-y-6">
    <div>
      <h3 className="text-lg font-bold text-gray-900 mb-2">공정 흐름 정책</h3>
      <p className="text-sm text-gray-600">제품별 생산 공정의 단계와 합류점을 정의합니다.</p>
    </div>

    {/* 공정 워크플로우 */}
    <div>
      <h4 className="text-sm font-medium text-gray-700 mb-3">공정 유형별 워크플로우</h4>
      <div className="grid grid-cols-2 gap-4">
        {Object.entries(policy.workflows).map(([code, wf]) => (
          <div key={code} className="border rounded-lg p-4">
            <div className="flex items-center gap-2 mb-2">
              <span className="font-mono bg-purple-100 text-purple-700 px-2 py-0.5 rounded">{code}</span>
              <span className="font-medium text-gray-900">{wf.name}</span>
            </div>
            <p className="text-sm text-gray-600 mb-2">{wf.description}</p>
            <div className="flex flex-wrap gap-1 mb-2">
              {wf.steps.map((step, idx) => (
                <React.Fragment key={step}>
                  <span className="text-xs font-mono bg-gray-100 text-gray-700 px-2 py-0.5 rounded">{step}</span>
                  {idx < wf.steps.length - 1 && <ArrowRight className="w-3 h-3 text-gray-400 self-center" />}
                </React.Fragment>
              ))}
            </div>
            <div className="text-xs text-gray-500">예상 소요: {wf.estimatedDays}일</div>
          </div>
        ))}
      </div>
    </div>

    {/* 합류점 */}
    <div>
      <h4 className="text-sm font-medium text-gray-700 mb-3">공정 합류점</h4>
      <div className="space-y-3">
        {Object.entries(policy.mergePoints).map(([code, mp]) => (
          <div key={code} className="border rounded-lg p-4 bg-yellow-50">
            <div className="flex items-center gap-2 mb-2">
              <GitBranch className="w-5 h-5 text-yellow-600" />
              <span className="font-medium text-gray-900">{mp.name}</span>
              <span className="text-xs font-mono bg-yellow-200 text-yellow-800 px-2 py-0.5 rounded">{code}</span>
            </div>
            <p className="text-sm text-gray-600 mb-2">{mp.description}</p>
            <div className="text-xs text-gray-500">
              필요 공정: {mp.requiredWorkflows.join(' + ')} → {mp.outputDocument}
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// ============ 자재 정책 섹션 ============
const MaterialSection = ({ policy }) => (
  <div className="space-y-6">
    <div>
      <h3 className="text-lg font-bold text-gray-900 mb-2">자재 정책</h3>
      <p className="text-sm text-gray-600">LOT 관리, 재고 정책, 입출고 규칙을 정의합니다.</p>
    </div>

    <div className="grid grid-cols-2 gap-4">
      {/* LOT 관리 */}
      <div className="border rounded-lg p-4">
        <h4 className="text-sm font-medium text-gray-700 mb-3">LOT 관리 정책</h4>
        <div className="space-y-2 text-sm">
          <div><span className="text-gray-500">대상 품목:</span> {policy.lotManagement.trackingRequired.join(', ')}</div>
          <div><span className="text-gray-500">번호 형식:</span> <code className="bg-gray-100 px-1">{policy.lotManagement.lotNumberFormat}</code></div>
          <div><span className="text-gray-500">유효기한 관리:</span> {policy.lotManagement.expiryManagement ? '사용' : '미사용'}</div>
          <div><span className="text-gray-500">FIFO 적용:</span> {policy.lotManagement.fifoEnforced ? '필수' : '선택'}</div>
        </div>
      </div>

      {/* 재고 정책 */}
      <div className="border rounded-lg p-4">
        <h4 className="text-sm font-medium text-gray-700 mb-3">재고 수준 정책</h4>
        <div className="space-y-2 text-sm">
          <div><span className="text-gray-500">안전재고:</span> <code className="bg-gray-100 px-1">{policy.inventoryPolicy.safetyStockLevel}</code></div>
          <div><span className="text-gray-500">재주문점:</span> <code className="bg-gray-100 px-1">{policy.inventoryPolicy.reorderPoint}</code></div>
          <div><span className="text-gray-500">최대재고:</span> <code className="bg-gray-100 px-1">{policy.inventoryPolicy.maxStockLevel}</code></div>
          <div><span className="text-gray-500">저장위치:</span> {policy.inventoryPolicy.stockLocations.join(', ')}</div>
        </div>
      </div>
    </div>

    {/* 입출고 정책 */}
    <div className="grid grid-cols-2 gap-4">
      <div className="border rounded-lg p-4 bg-green-50">
        <h4 className="text-sm font-medium text-green-800 mb-3">입고 정책</h4>
        <div className="space-y-2 text-sm">
          <div><span className="text-gray-600">유형:</span> {policy.transactionPolicy.inbound.types.join(', ')}</div>
          <div><span className="text-gray-600">검사 필수:</span> {policy.transactionPolicy.inbound.requiresInspection.join(', ')}</div>
          <div><span className="text-gray-600">LOT 부여:</span> {policy.transactionPolicy.inbound.requiresLotAssignment.join(', ')}</div>
        </div>
      </div>
      <div className="border rounded-lg p-4 bg-red-50">
        <h4 className="text-sm font-medium text-red-800 mb-3">출고 정책</h4>
        <div className="space-y-2 text-sm">
          <div><span className="text-gray-600">유형:</span> {policy.transactionPolicy.outbound.types.join(', ')}</div>
          <div><span className="text-gray-600">승인 필수:</span> {policy.transactionPolicy.outbound.requiresApproval.join(', ')}</div>
          <div><span className="text-gray-600">LOT 선택:</span> {policy.transactionPolicy.outbound.lotSelectionMethod}</div>
        </div>
      </div>
    </div>
  </div>
);

// ============ 단가 정책 섹션 ============
const PricingSection = ({ policy }) => (
  <div className="space-y-6">
    <div>
      <h3 className="text-lg font-bold text-gray-900 mb-2">단가 정책</h3>
      <p className="text-sm text-gray-600">단가 계산 공식, 거래처 할인, 이력 관리 규칙을 정의합니다.</p>
    </div>

    {/* 계산 공식 */}
    <div className="border rounded-lg p-4 bg-blue-50">
      <h4 className="text-sm font-medium text-blue-800 mb-3">단가 계산 공식</h4>
      <div className="space-y-2">
        {Object.entries(policy.calculation).map(([key, formula]) => (
          <div key={key} className="flex items-center gap-2 text-sm">
            <span className="font-medium text-gray-700 w-40">{key}:</span>
            <code className="bg-white px-2 py-1 rounded border">{formula}</code>
          </div>
        ))}
      </div>
    </div>

    {/* 거래처 그룹 할인 */}
    <div>
      <h4 className="text-sm font-medium text-gray-700 mb-3">거래처 그룹별 할인율</h4>
      <div className="grid grid-cols-4 gap-3">
        {Object.entries(policy.customerGroupDiscount).map(([group, info]) => (
          <div key={group} className="border rounded-lg p-3">
            <div className="flex justify-between items-center mb-1">
              <span className="font-medium text-gray-900">{group}</span>
              <span className="text-red-600 font-bold">-{info.discountRate}%</span>
            </div>
            <div className="text-xs text-gray-500">{info.criteria}</div>
          </div>
        ))}
      </div>
    </div>

    {/* 이력 정책 */}
    <div className="grid grid-cols-2 gap-4">
      <div className="border rounded-lg p-4">
        <h4 className="text-sm font-medium text-gray-700 mb-3">이력 관리 정책</h4>
        <div className="space-y-2 text-sm">
          <div><span className="text-gray-500">변경 추적:</span> {policy.historyPolicy.trackChanges ? '사용' : '미사용'}</div>
          <div><span className="text-gray-500">보관 기간:</span> {policy.historyPolicy.retentionPeriod}</div>
          <div><span className="text-gray-500">사유 필수:</span> {policy.historyPolicy.changeReasonRequired ? '예' : '아니오'}</div>
          <div><span className="text-gray-500">승인 조건:</span> {policy.historyPolicy.approvalRequired}</div>
        </div>
      </div>
      <div className="border rounded-lg p-4">
        <h4 className="text-sm font-medium text-gray-700 mb-3">자동 재계산 트리거</h4>
        <ul className="space-y-1 text-sm">
          {policy.autoRecalculation.triggers.map((trigger, idx) => (
            <li key={idx} className="flex items-center gap-2">
              <CheckCircle className="w-3 h-3 text-green-500" />
              {trigger}
            </li>
          ))}
        </ul>
      </div>
    </div>
  </div>
);

// ============ 품목코드 정책 섹션 ============
const ItemCodeSection = ({ policy }) => (
  <div className="space-y-6">
    <div>
      <h3 className="text-lg font-bold text-gray-900 mb-2">품목코드 정책</h3>
      <p className="text-sm text-gray-600">품목 유형별 코드 체계와 LOT 번호 규칙을 정의합니다.</p>
    </div>

    {/* 품목코드 패턴 */}
    <div>
      <h4 className="text-sm font-medium text-gray-700 mb-3">품목유형별 코드 체계</h4>
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-2 text-left text-gray-600">품목유형</th>
              <th className="px-4 py-2 text-left text-gray-600">형식</th>
              <th className="px-4 py-2 text-left text-gray-600">예시</th>
              <th className="px-4 py-2 text-left text-gray-600">설명</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {Object.entries(policy.patterns).map(([type, pattern]) => (
              <tr key={type}>
                <td className="px-4 py-2 font-medium">{type}</td>
                <td className="px-4 py-2 font-mono text-xs bg-gray-50">{pattern.format}</td>
                <td className="px-4 py-2 font-mono text-xs text-blue-600">{pattern.example}</td>
                <td className="px-4 py-2 text-gray-600">{pattern.description}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>

    {/* LOT 번호 체계 */}
    <div className="border rounded-lg p-4 bg-purple-50">
      <h4 className="text-sm font-medium text-purple-800 mb-3">LOT 번호 체계</h4>
      <div className="mb-3">
        <span className="text-sm text-gray-600">형식:</span>
        <code className="ml-2 bg-white px-2 py-1 rounded font-mono">{policy.lotNumberPattern.format}</code>
      </div>
      <div className="mb-3">
        <span className="text-sm text-gray-600">예시:</span>
        <code className="ml-2 bg-white px-2 py-1 rounded font-mono text-blue-600">{policy.lotNumberPattern.example}</code>
      </div>
      <div className="grid grid-cols-2 gap-2 text-sm">
        {Object.entries(policy.lotNumberPattern.components).map(([key, desc]) => (
          <div key={key} className="flex gap-2">
            <span className="font-mono text-purple-700">{key}:</span>
            <span className="text-gray-600">{desc}</span>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// ============ 권한 정책 섹션 ============
const AuthorizationSection = ({ policy }) => (
  <div className="space-y-6">
    <div>
      <h3 className="text-lg font-bold text-gray-900 mb-2">권한 정책</h3>
      <p className="text-sm text-gray-600">사용자 역할과 문서별 결재 규칙을 정의합니다.</p>
    </div>

    {/* 역할 정의 */}
    <div>
      <h4 className="text-sm font-medium text-gray-700 mb-3">역할별 권한</h4>
      <div className="space-y-3">
        {Object.entries(policy.roles).map(([roleCode, role]) => (
          <div key={roleCode} className="border rounded-lg p-3">
            <div className="flex items-center gap-2 mb-2">
              <Shield className="w-4 h-4 text-gray-500" />
              <span className="font-medium text-gray-900">{role.name}</span>
              <span className="text-xs font-mono bg-gray-100 px-2 py-0.5 rounded">{roleCode}</span>
            </div>
            <p className="text-sm text-gray-600 mb-2">{role.description}</p>
            <div className="flex flex-wrap gap-1">
              {role.permissions.map((perm, idx) => (
                <span key={idx} className="text-xs bg-blue-50 text-blue-600 px-2 py-0.5 rounded">
                  {perm}
                </span>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>

    {/* 결재 정책 */}
    <div>
      <h4 className="text-sm font-medium text-gray-700 mb-3">문서별 결재 정책</h4>
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-2 text-left text-gray-600">문서</th>
              <th className="px-4 py-2 text-left text-gray-600">조건</th>
              <th className="px-4 py-2 text-left text-gray-600">결재자</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {Object.entries(policy.approvalPolicy).map(([doc, rule]) => (
              <tr key={doc}>
                <td className="px-4 py-2 font-medium">{doc}</td>
                <td className="px-4 py-2 text-gray-600">
                  {rule.amount ? `금액 ≥ ${rule.amount.toLocaleString()}원` :
                   rule.marginBelow ? `마진율 < ${rule.marginBelow}%` :
                   rule.always ? '항상 필요' : '-'}
                </td>
                <td className="px-4 py-2">{rule.approvers.join(' → ')}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  </div>
);

// ============ 용어 정의 섹션 ============
const TerminologySection = ({ policy, searchTerm }) => {
  const filterTerms = (terms) => {
    if (!searchTerm) return Object.entries(terms);
    const term = searchTerm.toLowerCase();
    return Object.entries(terms).filter(([key, val]) =>
      key.includes(term) || val.korean.includes(term) || val.description?.includes(term)
    );
  };

  return (
    <div className="space-y-6">
      <div>
        <h3 className="text-lg font-bold text-gray-900 mb-2">용어 정의</h3>
        <p className="text-sm text-gray-600">시스템에서 사용하는 표준 용어와 약어를 정의합니다.</p>
      </div>

      {/* 문서 용어 */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 mb-3">문서 용어</h4>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-2 text-left text-gray-600">코드</th>
                <th className="px-4 py-2 text-left text-gray-600">한글명</th>
                <th className="px-4 py-2 text-left text-gray-600">약어</th>
                <th className="px-4 py-2 text-left text-gray-600">설명</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {filterTerms(policy.documents).map(([code, term]) => (
                <tr key={code}>
                  <td className="px-4 py-2 font-mono">{code}</td>
                  <td className="px-4 py-2 font-medium">{term.korean}</td>
                  <td className="px-4 py-2 font-mono text-blue-600">{term.abbreviation}</td>
                  <td className="px-4 py-2 text-gray-600">{term.description}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 품목유형 용어 */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 mb-3">품목유형 용어</h4>
        <div className="grid grid-cols-3 gap-3">
          {Object.entries(policy.itemTypes).map(([code, term]) => (
            <div key={code} className="border rounded-lg p-3">
              <div className="font-medium text-gray-900">{term.korean}</div>
              <div className="text-xs font-mono text-gray-500">{code}</div>
              <div className="text-sm text-gray-600 mt-1">{term.description}</div>
            </div>
          ))}
        </div>
      </div>

      {/* 공정 용어 */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 mb-3">공정 용어</h4>
        <div className="grid grid-cols-4 gap-3">
          {Object.entries(policy.processes).map(([code, term]) => (
            <div key={code} className="border rounded-lg p-3 bg-purple-50">
              <div className="flex items-center gap-2">
                <span className="font-mono bg-purple-200 text-purple-800 px-2 py-0.5 rounded">{code}</span>
                <span className="font-medium text-gray-900">{term.korean}</span>
              </div>
              <div className="text-sm text-gray-600 mt-1">{term.description}</div>
            </div>
          ))}
        </div>
      </div>

      {/* 검사유형 용어 */}
      <div>
        <h4 className="text-sm font-medium text-gray-700 mb-3">검사유형 용어</h4>
        <div className="grid grid-cols-3 gap-3">
          {Object.entries(policy.inspectionTypes).map(([code, term]) => (
            <div key={code} className="border rounded-lg p-3 bg-green-50">
              <div className="flex items-center gap-2">
                <span className="font-mono bg-green-200 text-green-800 px-2 py-0.5 rounded">{code}</span>
                <span className="font-medium text-gray-900">{term.korean}</span>
              </div>
              <div className="text-xs text-gray-500 mt-1">{term.fullName}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ============ 알림 정책 섹션 ============
const NotificationSection = ({ policy }) => (
  <div className="space-y-6">
    <div>
      <h3 className="text-lg font-bold text-gray-900 mb-2">알림 정책</h3>
      <p className="text-sm text-gray-600">시스템 이벤트별 알림 대상과 채널을 정의합니다.</p>
    </div>

    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead className="bg-gray-50">
          <tr>
            <th className="px-4 py-2 text-left text-gray-600">이벤트</th>
            <th className="px-4 py-2 text-left text-gray-600">수신자</th>
            <th className="px-4 py-2 text-left text-gray-600">채널</th>
            <th className="px-4 py-2 text-left text-gray-600">템플릿</th>
          </tr>
        </thead>
        <tbody className="divide-y">
          {policy.events.map((event, idx) => (
            <tr key={idx}>
              <td className="px-4 py-2 font-mono text-blue-600">{event.event}</td>
              <td className="px-4 py-2">{event.recipients.join(', ')}</td>
              <td className="px-4 py-2">
                <div className="flex gap-1">
                  {event.channel.map(ch => (
                    <span key={ch} className="text-xs bg-gray-100 px-2 py-0.5 rounded">{ch}</span>
                  ))}
                </div>
              </td>
              <td className="px-4 py-2 font-mono text-xs">{event.template}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

export default PolicyGuide;
