import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, CardContent } from '@shared/components/ui/card';
import { Badge } from '@shared/components/ui/badge';
import { PageContainer, PageHeader } from '@shared/components/layout';
import {
  Brain, Database, MessageSquare, FileText, Activity, Shield, Ban,
  Server, RefreshCw, Search, Settings, Zap, GitBranch, Layers,
  CheckCircle, AlertTriangle, Clock,
  BarChart3, Lock, Cpu,
  ArrowUpDown, ArrowRight, TrendingUp,
} from 'lucide-react';

/*
 * SFR-20: 대규모 언어모델(LLM) 운영 기능
 * Qwen3-8B 기반 통합 LLM 운영 플랫폼
 *
 * 9개 기능 영역:
 * ① 모델 관리  ② 프롬프트 관리  ③ 추론 서비스
 * ④ 로그 및 추적  ⑤ 평가 및 품질  ⑥ 데이터 관리
 * ⑦ RAG 파이프라인  ⑧ 보안 및 접근제어  ⑨ 운영 모니터링
 */

type Tab = 'model' | 'prompt' | 'inference' | 'log' | 'eval' | 'data' | 'rag' | 'quality' | 'security' | 'monitoring';

const TABS: { key: Tab; label: string; icon: React.ElementType }[] = [
  { key: 'model', label: '모델 관리', icon: Brain },
  { key: 'prompt', label: '프롬프트', icon: MessageSquare },
  { key: 'inference', label: '추론 서비스', icon: Zap },
  { key: 'log', label: '로그/추적', icon: FileText },
  { key: 'eval', label: '평가/품질', icon: BarChart3 },
  { key: 'data', label: '데이터', icon: Database },
  { key: 'rag', label: 'RAG', icon: Layers },
  { key: 'quality', label: '품질개선', icon: Search },
  { key: 'security', label: '보안', icon: Shield },
  { key: 'monitoring', label: '모니터링', icon: Activity },
];

// ─── ① 모델 관리 ──────────────────
const MODEL_VERSIONS = [
  { version: 'v3.2.0', name: 'Qwen3-8B-KCG-FT', status: '운영중', params: '8.0B', deploy: 'Blue', date: '2026-04-01', accuracy: 94.2, f1: 93.1, hallu: 3.2 },
  { version: 'v3.1.0', name: 'Qwen3-8B-KCG-FT', status: '대기', params: '8.0B', deploy: 'Green', date: '2026-03-15', accuracy: 92.8, f1: 91.5, hallu: 4.1 },
  { version: 'v3.0.0', name: 'Qwen3-8B-Base', status: '보관', params: '8.0B', deploy: '-', date: '2026-02-20', accuracy: 88.5, f1: 87.2, hallu: 6.8 },
  { version: 'v2.5.0', name: 'Qwen2-7B-KCG', status: '폐기', params: '7.0B', deploy: '-', date: '2025-12-10', accuracy: 85.3, f1: 84.0, hallu: 8.5 },
];

const FINETUNE_HISTORY = [
  { id: 'FT-012', base: 'Qwen3-8B', dataset: '해양법령+단속사례', epochs: 5, lr: '2e-5', lora: 'r=16, alpha=32', result: 'v3.2.0', date: '2026-03-28', status: '완료' },
  { id: 'FT-011', base: 'Qwen3-8B', dataset: '해양법령+매뉴얼', epochs: 3, lr: '3e-5', lora: 'r=8, alpha=16', result: 'v3.1.0', date: '2026-03-10', status: '완료' },
  { id: 'FT-010', base: 'Qwen3-8B', dataset: '기본 도메인 적응', epochs: 2, lr: '5e-5', lora: '-', result: 'v3.0.0', date: '2026-02-15', status: '완료' },
];

// ─── ② 프롬프트 관리 ──────────────────
const PROMPT_TEMPLATES = [
  { id: 'PT-001', name: '상황 요약', category: 'summary', version: 'v2.3', abWinner: 'A', lastTest: '2026-04-05', accuracy: 94.5, tokens: 450, desc: 'AI 분석 결과 요약 (위험도·선박·해역 컨텍스트)' },
  { id: 'PT-002', name: 'XAI 설명', category: 'xai', version: 'v1.8', abWinner: 'B', lastTest: '2026-04-03', accuracy: 91.2, tokens: 620, desc: '탐지 결과 근거 설명 (피처 기여도·법적 근거)' },
  { id: 'PT-003', name: '시나리오 생성', category: 'scenario', version: 'v1.5', abWinner: 'A', lastTest: '2026-03-28', accuracy: 88.7, tokens: 850, desc: '단속 시나리오 자동 생성 (기상·선박·해역 조건)' },
  { id: 'PT-004', name: 'Q&A 답변', category: 'qa', version: 'v3.1', abWinner: 'A', lastTest: '2026-04-07', accuracy: 96.3, tokens: 380, desc: '법령·지침·유사사례 기반 자연어 답변' },
];

const AB_TESTS = [
  { id: 'AB-008', prompt: 'Q&A 답변', variantA: 'v3.1 (CoT 강화)', variantB: 'v3.0 (간결형)', traffic: '50/50', winner: 'A', scoreA: 96.3, scoreB: 93.1, period: '04-01~04-07', status: '완료' },
  { id: 'AB-007', prompt: 'XAI 설명', variantA: 'v1.8 (법조문 참조)', variantB: 'v1.7 (요약형)', traffic: '50/50', winner: 'B', scoreA: 89.5, scoreB: 91.2, period: '03-25~04-03', status: '완료' },
  { id: 'AB-009', prompt: '상황 요약', variantA: 'v2.4 (구조화)', variantB: 'v2.3 (내러티브)', traffic: '50/50', winner: '-', scoreA: 93.8, scoreB: 94.1, period: '04-08~진행중', status: '진행중' },
];

// ─── ③ 추론 서비스 ──────────────────
const INFERENCE_ENDPOINTS = [
  { name: '/v1/chat/completions', method: 'POST', model: 'Qwen3-8B v3.2.0', engine: 'vLLM', gpu: 'H200 x2', status: '정상', rps: 24, latency: '6.2s', p99: '9.8s', queue: 3 },
  { name: '/v1/embeddings', method: 'POST', model: 'BGE-M3', engine: 'vLLM', gpu: 'H200 x1', status: '정상', rps: 85, latency: '120ms', p99: '280ms', queue: 0 },
  { name: '/v1/rerank', method: 'POST', model: 'BGE-Reranker', engine: 'FastAPI', gpu: 'H200 x1', status: '정상', rps: 45, latency: '85ms', p99: '150ms', queue: 0 },
];

const INFERENCE_KPI = [
  { label: '평균 응답시간', value: '6.2초', target: '≤10초', ok: true, icon: Clock },
  { label: '동시 처리', value: '24건', target: '≥20건', ok: true, icon: Zap },
  { label: '가용성', value: '99.95%', target: '99.9%', ok: true, icon: CheckCircle },
  { label: '대기열', value: '3건', target: '≤10건', ok: true, icon: ArrowUpDown },
];

// ─── ④ 로그 및 추적 ──────────────────
const LOG_ENTRIES = [
  { id: 'QRY-48291', time: '2026-04-08 18:32:15', user: '김영수', type: 'Q&A', input: 'EEZ 침범 중국어선 단속 절차는?', tokens: 842, latency: '5.8s', status: '성공', masked: 2 },
  { id: 'QRY-48290', time: '2026-04-08 18:30:02', user: '박민지', type: '상황요약', input: '서해 NLL 인근 위험도 요약 요청', tokens: 1240, latency: '8.1s', status: '성공', masked: 5 },
  { id: 'QRY-48289', time: '2026-04-08 18:28:44', user: '이준호', type: 'XAI', input: '다크베셀 DV-2024-0892 탐지 근거', tokens: 680, latency: '4.2s', status: '성공', masked: 1 },
  { id: 'QRY-48288', time: '2026-04-08 18:25:11', user: '최수진', type: 'Q&A', input: '환적 의심 선박 MMSI 4128*** 조회', tokens: 520, latency: '3.9s', status: '성공', masked: 3 },
  { id: 'QRY-48287', time: '2026-04-08 18:22:30', user: '김영수', type: '시나리오', input: '야간 불법조업 단속 시나리오 생성', tokens: 1580, latency: '11.2s', status: '타임아웃', masked: 0 },
];

const TRACE_STATS = [
  { label: '오늘 요청 수', value: '1,247건' },
  { label: '평균 토큰', value: '892' },
  { label: '마스킹 처리', value: '3,891건' },
  { label: '검색 평균', value: '1.8초' },
];

// ─── ⑤ 평가 및 품질 ──────────────────
const EVAL_METRICS = [
  { version: 'v3.2.0', date: '2026-04-07', hallu: 3.2, bleu: 0.72, rouge: 0.81, f1: 0.931, faithfulness: 0.94, relevancy: 0.92, context: 0.88 },
  { version: 'v3.1.0', date: '2026-03-22', hallu: 4.1, bleu: 0.68, rouge: 0.78, f1: 0.915, faithfulness: 0.91, relevancy: 0.89, context: 0.85 },
  { version: 'v3.0.0', date: '2026-03-01', hallu: 6.8, bleu: 0.61, rouge: 0.72, f1: 0.872, faithfulness: 0.86, relevancy: 0.84, context: 0.80 },
];

const EVAL_KPI = [
  { label: '할루시네이션율', value: '3.2%', target: '≤5%', ok: true },
  { label: 'F1 Score', value: '0.931', target: '≥0.91', ok: true },
  { label: 'Faithfulness', value: '0.94', target: '≥0.90', ok: true },
  { label: 'BLEU', value: '0.72', target: '≥0.65', ok: true },
];

// ─── ⑥ 데이터 관리 ──────────────────
const KNOWLEDGE_SOURCES = [
  { category: '해양 법령', count: 1250, lastUpdate: '2026-04-05', embedding: '완료', version: 'v3', size: '2.8GB' },
  { category: '단속 매뉴얼', count: 380, lastUpdate: '2026-04-02', embedding: '완료', version: 'v3', size: '850MB' },
  { category: '단속 사례', count: 2150, lastUpdate: '2026-04-08', embedding: '갱신중', version: 'v3→v4', size: '4.2GB' },
  { category: 'AI 분석 결과', count: 890, lastUpdate: '2026-04-08', embedding: '완료', version: 'v3', size: '1.6GB' },
  { category: '국제 협약', count: 420, lastUpdate: '2026-03-20', embedding: '완료', version: 'v2', size: '1.1GB' },
  { category: '기상/해양 데이터', count: 310, lastUpdate: '2026-04-08', embedding: '완료', version: 'v3', size: '680MB' },
];

const DATA_KPI = [
  { label: '총 등록 데이터', value: '5,400건', target: '5,200+', ok: true },
  { label: '임베딩 완료율', value: '94.2%', target: '≥90%', ok: true },
  { label: '갱신 지연', value: '18시간', target: '≤24시간', ok: true },
  { label: 'R@5', value: '87.3%', target: '≥85%', ok: true },
];

// ─── ⑥-b 문서 등록 관리 ──────────────────
const DOC_CATEGORIES = [
  { key: 'law', label: '법령·고시', icon: '⚖️', desc: '해양경찰 관련 법률, 시행령, 시행규칙, 고시' },
  { key: 'guideline', label: '내부 지침', icon: '📋', desc: '해양경찰청 내부 업무 지침, 훈령, 예규' },
  { key: 'manual', label: '매뉴얼', icon: '📘', desc: '단속·수사·장비 운용 매뉴얼, SOP' },
  { key: 'enforcement', label: '단속 사례', icon: '🚔', desc: '불법조업 단속 사례, 현장 보고서' },
  { key: 'investigation', label: '수사 사례', icon: '🔍', desc: '수사 기록, 판례, 처분 결과' },
];

const REGISTERED_DOCS = [
  { id: 'DOC-1842', title: '배타적경제수역에서의 외국인어업 등에 대한 주권적 권리의 행사에 관한 법률', category: 'law', version: 'v3', pages: 42, date: '2026-04-05', status: '임베딩 완료' },
  { id: 'DOC-1841', title: '불법조업 외국어선 단속 업무처리 지침 (해양경찰청 훈령 제312호)', category: 'guideline', version: 'v2', pages: 68, date: '2026-04-03', status: '임베딩 완료' },
  { id: 'DOC-1840', title: '해상단속 현장조치 매뉴얼 (2026년 개정판)', category: 'manual', version: 'v4', pages: 125, date: '2026-04-01', status: '임베딩 완료' },
  { id: 'DOC-1839', title: '중국어선 EEZ 침범 단속 사례 (2026-Q1, 서해5도)', category: 'enforcement', version: 'v1', pages: 34, date: '2026-03-30', status: '임베딩 완료' },
  { id: 'DOC-1838', title: '한중어업협정 위반 수사 사례집 (2025~2026)', category: 'investigation', version: 'v2', pages: 89, date: '2026-03-28', status: '임베딩 완료' },
  { id: 'DOC-1837', title: '무허가 조업행위 처벌 기준 고시 (해수부 고시 제2026-15호)', category: 'law', version: 'v1', pages: 18, date: '2026-03-25', status: '임베딩 완료' },
  { id: 'DOC-1836', title: '야간 불법조업 단속 SOP (함정용)', category: 'manual', version: 'v3', pages: 45, date: '2026-03-22', status: '임베딩 완료' },
  { id: 'DOC-1835', title: '다크베셀 수사 절차 가이드라인', category: 'investigation', version: 'v1', pages: 56, date: '2026-03-20', status: '갱신중' },
];

// ─── ⑥-c 품질개선 (불용어·필터링·분류체계·규칙) ──────────────────
const STOPWORDS = [
  { id: 1, word: '그리고', category: '접속사', status: '활성', addedBy: '시스템', date: '2026-01-15' },
  { id: 2, word: '하지만', category: '접속사', status: '활성', addedBy: '시스템', date: '2026-01-15' },
  { id: 3, word: '그러나', category: '접속사', status: '활성', addedBy: '시스템', date: '2026-01-15' },
  { id: 4, word: '따라서', category: '접속부사', status: '활성', addedBy: '시스템', date: '2026-01-15' },
  { id: 5, word: '있습니다', category: '어미', status: '활성', addedBy: '시스템', date: '2026-01-15' },
  { id: 6, word: '됩니다', category: '어미', status: '활성', addedBy: '시스템', date: '2026-01-15' },
  { id: 7, word: '해당', category: '관형사', status: '활성', addedBy: '관리자', date: '2026-02-10' },
  { id: 8, word: '관련', category: '관형사', status: '활성', addedBy: '관리자', date: '2026-02-10' },
];

const PROFANITY_FILTERS = [
  { category: '욕설·비속어', count: 1240, lastUpdate: '2026-04-01', status: '활성', action: '마스킹 치환' },
  { category: '혐오 표현', count: 380, lastUpdate: '2026-04-01', status: '활성', action: '응답 차단' },
  { category: '개인정보 패턴', count: 45, lastUpdate: '2026-03-15', status: '활성', action: '마스킹 치환' },
  { category: '프롬프트 인젝션', count: 128, lastUpdate: '2026-04-05', status: '활성', action: '입력 차단' },
  { category: '민감 군사정보', count: 62, lastUpdate: '2026-03-20', status: '활성', action: '응답 차단' },
];

const TAXONOMY = [
  { id: 'TX-01', name: '불법조업 유형', items: 12, desc: 'EEZ침범, 무허가, 금지구역, 휴어기 등', version: 'v3', date: '2026-04-02' },
  { id: 'TX-02', name: '선박 분류', items: 8, desc: '어선, 화물선, 유조선, 모선, 부속선 등', version: 'v2', date: '2026-03-20' },
  { id: 'TX-03', name: '해역 구분', items: 15, desc: 'NLL, EEZ, 영해, 접속수역, 공해 등', version: 'v2', date: '2026-03-15' },
  { id: 'TX-04', name: '단속 조치', items: 10, desc: '나포, 추방, 경고, 과태료, 형사입건 등', version: 'v3', date: '2026-04-01' },
  { id: 'TX-05', name: '위험도 등급', items: 5, desc: 'CRITICAL, HIGH, MEDIUM, LOW, NORMAL', version: 'v1', date: '2026-01-10' },
];

const QUALITY_RULES = [
  { id: 'QR-01', name: '법조문 참조 필수', desc: '법령 관련 답변 시 해당 법률·조항 반드시 인용', status: '활성', priority: '높음' },
  { id: 'QR-02', name: '좌표 마스킹', desc: '정밀 좌표(소수점 4자리+)는 자동 마스킹 처리', status: '활성', priority: '높음' },
  { id: 'QR-03', name: 'MMSI 익명화', desc: 'MMSI 번호 뒤 3자리 *** 처리', status: '활성', priority: '높음' },
  { id: 'QR-04', name: '불확실성 표시', desc: 'AI 확신도 80% 미만 시 "추정" 문구 삽입', status: '활성', priority: '중간' },
  { id: 'QR-05', name: '출처 명시', desc: '모든 답변에 참조 문서 ID·페이지 표기', status: '활성', priority: '중간' },
  { id: 'QR-06', name: '이중언어 지원', desc: '한국어 질의에 영문 법률명 병기 시 원문 유지', status: '활성', priority: '낮음' },
];

// ─── ⑦ RAG 파이프라인 ──────────────────
const RAG_PIPELINE = [
  { stage: '① 쿼리 분석', engine: 'LangChain', status: '정상', latency: '120ms', desc: '질의 의도 분류 + 키워드 추출' },
  { stage: '② 벡터 검색', engine: 'pgvector + FAISS', status: '정상', latency: '250ms', desc: 'BGE-M3 임베딩 하이브리드 검색' },
  { stage: '③ 재정렬', engine: 'BGE Reranker', status: '정상', latency: '85ms', desc: 'Top-20 → Top-5 문서 재정렬' },
  { stage: '④ 컨텍스트 조립', engine: 'LangChain', status: '정상', latency: '30ms', desc: '프롬프트 템플릿 + 검색 결과 결합' },
  { stage: '⑤ LLM 추론', engine: 'vLLM (Qwen3-8B)', status: '정상', latency: '5.8s', desc: '최종 응답 생성' },
  { stage: '⑥ 후처리', engine: 'FastAPI', status: '정상', latency: '50ms', desc: '출력 필터링 + 참조 링크 삽입' },
];

const RAG_KPI = [
  { label: 'MRR', value: '0.85', target: '≥0.82', ok: true },
  { label: 'NDCG@10', value: '0.81', target: '≥0.78', ok: true },
  { label: '재색인 주기', value: '일 1회', target: '일 1회', ok: true },
  { label: 'E2E 지연', value: '6.3초', target: '≤10초', ok: true },
];

const REINDEX_HISTORY = [
  { id: 'IDX-042', date: '2026-04-08 03:00', docs: 5400, duration: '45분', delta: '+23건', status: '완료' },
  { id: 'IDX-041', date: '2026-04-07 03:00', docs: 5377, duration: '43분', delta: '+15건', status: '완료' },
  { id: 'IDX-040', date: '2026-04-06 03:00', docs: 5362, duration: '42분', delta: '+8건', status: '완료' },
];

// ─── ⑧ 보안 ──────────────────
const SECURITY_LAYERS = [
  { layer: '입력 필터링', desc: '프롬프트 인젝션·악성 입력 탐지 차단', status: '활성', blocked: 12, total: 1247 },
  { layer: '출력 검증', desc: '할루시네이션·부적절 응답 필터링', status: '활성', blocked: 8, total: 1235 },
  { layer: '민감정보 마스킹', desc: 'MMSI·개인정보·좌표 자동 마스킹', status: '활성', blocked: 3891, total: 3891 },
  { layer: 'RBAC 접근제어', desc: 'JWT + 역할 기반 API 접근 제어', status: '활성', blocked: 3, total: 1250 },
  { layer: 'TLS 1.3 암호화', desc: '모든 통신 구간 암호화', status: '활성', blocked: 0, total: 0 },
  { layer: '망분리 차단', desc: '외부 LLM API 호출 완전 차단', status: '활성', blocked: 0, total: 0 },
];

// ─── ⑨ 운영 모니터링 ──────────────────
const GPU_NODES = [
  { name: 'gpu-node-01', gpu: 'H200 80GB', role: 'LLM 추론 (Primary)', util: 72, mem: 58, temp: 65, status: '정상' },
  { name: 'gpu-node-02', gpu: 'H200 80GB', role: 'LLM 추론 (Secondary)', util: 45, mem: 38, temp: 52, status: '정상' },
  { name: 'gpu-node-03', gpu: 'H200 80GB', role: '임베딩 + 리랭킹', util: 35, mem: 28, temp: 48, status: '정상' },
];

const SERVICES = [
  { name: 'vLLM Serving', port: 8000, status: '정상', uptime: '15d 8h', version: '0.6.2' },
  { name: 'RAG Pipeline', port: 8001, status: '정상', uptime: '15d 8h', version: '1.4.0' },
  { name: 'Embedding API', port: 8002, status: '정상', uptime: '15d 8h', version: '1.2.0' },
  { name: 'MLflow Registry', port: 5000, status: '정상', uptime: '30d 2h', version: '2.16' },
  { name: 'Airflow DAG', port: 8080, status: '정상', uptime: '30d 2h', version: '2.10' },
  { name: 'ELK Stack', port: 9200, status: '정상', uptime: '30d 2h', version: '8.15' },
  { name: 'Prometheus', port: 9090, status: '정상', uptime: '30d 2h', version: '2.54' },
  { name: 'Grafana', port: 3000, status: '정상', uptime: '30d 2h', version: '11.2' },
];

const ALERT_RULES = [
  { name: 'GPU 사용률 초과', condition: 'GPU util > 90%', action: '자동 스케일링', status: '활성' },
  { name: '응답 지연 초과', condition: '응답시간 > 20초', action: 'Alertmanager 알림', status: '활성' },
  { name: '오류율 초과', condition: '오류율 > 1%', action: 'Alertmanager 알림', status: '활성' },
  { name: 'VRAM 부족', condition: 'VRAM > 90%', action: '배치 큐 일시정지', status: '활성' },
  { name: 'RAG 품질 하락', condition: 'MRR < 0.80', action: '재색인 트리거', status: '활성' },
];

// ─── 헬퍼 ──────────────────
function statusIntent(s: string) {
  if (['정상', '활성', '완료', '운영중', '성공'].includes(s)) return 'success' as const;
  if (['경고', '갱신중', '진행중', '대기'].includes(s)) return 'warning' as const;
  if (['오류', '장애', '타임아웃', '폐기'].includes(s)) return 'critical' as const;
  return 'muted' as const;
}

function kpiCard(items: { label: string; value: string; target: string; ok: boolean }[]) {
  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-4">
      {items.map((k) => (
        <Card key={k.label}>
          <CardContent className="p-3">
            <div className="text-[10px] text-hint mb-1">{k.label}</div>
            <div className="text-lg font-bold text-heading">{k.value}</div>
            <div className="flex items-center gap-1 mt-1">
              {k.ok ? <CheckCircle className="w-3 h-3 text-emerald-400" /> : <AlertTriangle className="w-3 h-3 text-amber-400" />}
              <span className="text-[9px] text-hint">목표 {k.target}</span>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  );
}

// ─── 탭 콘텐츠 ──────────────────

function ModelTab() {
  return (
    <div className="space-y-4">
      {/* 모델 버전 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Brain className="w-4 h-4 text-purple-400" />
            <h3 className="text-sm font-bold text-heading">Qwen3-8B 모델 레지스트리</h3>
            <Badge intent="info" size="xs">MLflow</Badge>
            <Badge intent="muted" size="xs">Blue-Green 배포</Badge>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">버전</th>
                  <th className="text-left py-2 pr-3">모델명</th>
                  <th className="text-left py-2 pr-3">상태</th>
                  <th className="text-left py-2 pr-3">파라미터</th>
                  <th className="text-left py-2 pr-3">배포 슬롯</th>
                  <th className="text-right py-2 pr-3">Accuracy</th>
                  <th className="text-right py-2 pr-3">F1</th>
                  <th className="text-right py-2 pr-3">할루시네이션</th>
                  <th className="text-left py-2">등록일</th>
                </tr>
              </thead>
              <tbody>
                {MODEL_VERSIONS.map((m) => (
                  <tr key={m.version} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 font-mono font-bold text-heading">{m.version}</td>
                    <td className="py-2 pr-3 text-label">{m.name}</td>
                    <td className="py-2 pr-3"><Badge intent={statusIntent(m.status)} size="xs">{m.status}</Badge></td>
                    <td className="py-2 pr-3 text-hint">{m.params}</td>
                    <td className="py-2 pr-3">
                      {m.deploy !== '-' && <Badge intent={m.deploy === 'Blue' ? 'info' : 'success'} size="xs">{m.deploy}</Badge>}
                      {m.deploy === '-' && <span className="text-hint">-</span>}
                    </td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{m.accuracy}%</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{m.f1}%</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{m.hallu}%</td>
                    <td className="py-2 text-hint">{m.date}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* 파인튜닝 이력 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <GitBranch className="w-4 h-4 text-cyan-400" />
            <h3 className="text-sm font-bold text-heading">파인튜닝 이력</h3>
            <Badge intent="muted" size="xs">DVC 추적</Badge>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">ID</th>
                  <th className="text-left py-2 pr-3">베이스 모델</th>
                  <th className="text-left py-2 pr-3">데이터셋</th>
                  <th className="text-right py-2 pr-3">Epochs</th>
                  <th className="text-left py-2 pr-3">LR</th>
                  <th className="text-left py-2 pr-3">LoRA</th>
                  <th className="text-left py-2 pr-3">결과 버전</th>
                  <th className="text-left py-2 pr-3">상태</th>
                  <th className="text-left py-2">날짜</th>
                </tr>
              </thead>
              <tbody>
                {FINETUNE_HISTORY.map((ft) => (
                  <tr key={ft.id} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 font-mono text-blue-400">{ft.id}</td>
                    <td className="py-2 pr-3 text-label">{ft.base}</td>
                    <td className="py-2 pr-3 text-label">{ft.dataset}</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{ft.epochs}</td>
                    <td className="py-2 pr-3 font-mono text-hint">{ft.lr}</td>
                    <td className="py-2 pr-3 text-hint">{ft.lora}</td>
                    <td className="py-2 pr-3 font-mono font-bold text-heading">{ft.result}</td>
                    <td className="py-2 pr-3"><Badge intent="success" size="xs">{ft.status}</Badge></td>
                    <td className="py-2 text-hint">{ft.date}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* 롤백 안내 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-2">
            <RefreshCw className="w-4 h-4 text-orange-400" />
            <h3 className="text-sm font-bold text-heading">Blue-Green 무중단 배포</h3>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            <div className="bg-surface-overlay rounded-lg p-3">
              <div className="text-[10px] text-hint mb-1">현재 운영 (Blue)</div>
              <div className="text-sm font-bold text-blue-400">v3.2.0</div>
              <div className="text-[10px] text-hint mt-1">트래픽 100%</div>
            </div>
            <div className="bg-surface-overlay rounded-lg p-3">
              <div className="text-[10px] text-hint mb-1">대기 (Green)</div>
              <div className="text-sm font-bold text-emerald-400">v3.1.0</div>
              <div className="text-[10px] text-hint mt-1">핫스탠바이</div>
            </div>
            <div className="bg-surface-overlay rounded-lg p-3">
              <div className="text-[10px] text-hint mb-1">롤백 소요시간</div>
              <div className="text-sm font-bold text-heading">≤ 5분</div>
              <div className="text-[10px] text-hint mt-1">KPI 목표 충족</div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function PromptTab() {
  return (
    <div className="space-y-4">
      {/* 프롬프트 템플릿 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <MessageSquare className="w-4 h-4 text-green-400" />
            <h3 className="text-sm font-bold text-heading">프롬프트 템플릿 (4종)</h3>
            <Badge intent="muted" size="xs">LangChain PromptTemplate</Badge>
            <Badge intent="muted" size="xs">Git 버전관리</Badge>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {PROMPT_TEMPLATES.map((pt) => (
              <div key={pt.id} className="bg-surface-overlay rounded-lg p-3">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-bold text-heading">{pt.name}</span>
                    <Badge intent="info" size="xs">{pt.version}</Badge>
                  </div>
                  <Badge intent="success" size="xs">정확도 {pt.accuracy}%</Badge>
                </div>
                <div className="text-[10px] text-hint mb-2">{pt.desc}</div>
                <div className="flex items-center gap-3 text-[9px] text-hint">
                  <span>A/B 우승: Variant {pt.abWinner}</span>
                  <span>토큰: ~{pt.tokens}</span>
                  <span>최종 테스트: {pt.lastTest}</span>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* A/B 테스트 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <ArrowUpDown className="w-4 h-4 text-amber-400" />
            <h3 className="text-sm font-bold text-heading">A/B 테스트 이력</h3>
            <Badge intent="muted" size="xs">2주 주기 자동 선정</Badge>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">ID</th>
                  <th className="text-left py-2 pr-3">프롬프트</th>
                  <th className="text-left py-2 pr-3">Variant A</th>
                  <th className="text-left py-2 pr-3">Variant B</th>
                  <th className="text-right py-2 pr-3">A 점수</th>
                  <th className="text-right py-2 pr-3">B 점수</th>
                  <th className="text-center py-2 pr-3">우승</th>
                  <th className="text-left py-2 pr-3">기간</th>
                  <th className="text-left py-2">상태</th>
                </tr>
              </thead>
              <tbody>
                {AB_TESTS.map((ab) => (
                  <tr key={ab.id} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 font-mono text-blue-400">{ab.id}</td>
                    <td className="py-2 pr-3 text-label">{ab.prompt}</td>
                    <td className="py-2 pr-3 text-hint">{ab.variantA}</td>
                    <td className="py-2 pr-3 text-hint">{ab.variantB}</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{ab.scoreA}</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{ab.scoreB}</td>
                    <td className="py-2 pr-3 text-center">
                      {ab.winner !== '-' ? <Badge intent={ab.winner === 'A' ? 'info' : 'success'} size="xs">{ab.winner}</Badge> : <span className="text-hint">-</span>}
                    </td>
                    <td className="py-2 pr-3 text-hint">{ab.period}</td>
                    <td className="py-2"><Badge intent={statusIntent(ab.status)} size="xs">{ab.status}</Badge></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function InferenceTab() {
  return (
    <div className="space-y-4">
      {kpiCard(INFERENCE_KPI.map((k) => ({ label: k.label, value: k.value, target: k.target, ok: k.ok })))}

      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Zap className="w-4 h-4 text-yellow-400" />
            <h3 className="text-sm font-bold text-heading">추론 엔드포인트</h3>
            <Badge intent="muted" size="xs">vLLM PagedAttention</Badge>
            <Badge intent="muted" size="xs">H200 GPU</Badge>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">엔드포인트</th>
                  <th className="text-left py-2 pr-3">모델</th>
                  <th className="text-left py-2 pr-3">엔진</th>
                  <th className="text-left py-2 pr-3">GPU</th>
                  <th className="text-left py-2 pr-3">상태</th>
                  <th className="text-right py-2 pr-3">RPS</th>
                  <th className="text-right py-2 pr-3">지연</th>
                  <th className="text-right py-2 pr-3">P99</th>
                  <th className="text-right py-2">대기열</th>
                </tr>
              </thead>
              <tbody>
                {INFERENCE_ENDPOINTS.map((ep) => (
                  <tr key={ep.name} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 font-mono text-blue-400">{ep.name}</td>
                    <td className="py-2 pr-3 text-label">{ep.model}</td>
                    <td className="py-2 pr-3 text-hint">{ep.engine}</td>
                    <td className="py-2 pr-3 text-hint">{ep.gpu}</td>
                    <td className="py-2 pr-3"><Badge intent="success" size="xs">{ep.status}</Badge></td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{ep.rps}</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{ep.latency}</td>
                    <td className="py-2 pr-3 text-right font-mono text-hint">{ep.p99}</td>
                    <td className="py-2 text-right font-mono text-label">{ep.queue}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* 스케일링 정책 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-2">
            <Server className="w-4 h-4 text-indigo-400" />
            <h3 className="text-sm font-bold text-heading">오토 스케일링 정책</h3>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            <div className="bg-surface-overlay rounded-lg p-3">
              <div className="text-[10px] text-hint mb-1">타임아웃</div>
              <div className="text-sm font-bold text-heading">30초</div>
              <div className="text-[10px] text-hint mt-1">초과 시 재시도 3회</div>
            </div>
            <div className="bg-surface-overlay rounded-lg p-3">
              <div className="text-[10px] text-hint mb-1">큐잉 한도</div>
              <div className="text-sm font-bold text-heading">20건</div>
              <div className="text-[10px] text-hint mt-1">초과 시 자동 스케일업</div>
            </div>
            <div className="bg-surface-overlay rounded-lg p-3">
              <div className="text-[10px] text-hint mb-1">동시 처리</div>
              <div className="text-sm font-bold text-heading">≥ 20건</div>
              <div className="text-[10px] text-hint mt-1">현재 24건 보장</div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function LogTab() {
  return (
    <div className="space-y-4">
      {/* 통계 */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        {TRACE_STATS.map((s) => (
          <Card key={s.label}>
            <CardContent className="p-3">
              <div className="text-[10px] text-hint mb-1">{s.label}</div>
              <div className="text-lg font-bold text-heading">{s.value}</div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 로그 테이블 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <FileText className="w-4 h-4 text-cyan-400" />
            <h3 className="text-sm font-bold text-heading">요청-응답 트랜잭션 로그</h3>
            <Badge intent="muted" size="xs">ELK Stack</Badge>
            <Badge intent="muted" size="xs">OpenTelemetry</Badge>
            <Badge intent="info" size="xs">보존 1년</Badge>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">질의 ID</th>
                  <th className="text-left py-2 pr-3">시간</th>
                  <th className="text-left py-2 pr-3">사용자</th>
                  <th className="text-left py-2 pr-3">유형</th>
                  <th className="text-left py-2 pr-3">입력 (마스킹)</th>
                  <th className="text-right py-2 pr-3">토큰</th>
                  <th className="text-right py-2 pr-3">지연</th>
                  <th className="text-center py-2 pr-3">마스킹</th>
                  <th className="text-left py-2">상태</th>
                </tr>
              </thead>
              <tbody>
                {LOG_ENTRIES.map((log) => (
                  <tr key={log.id} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 font-mono text-blue-400">{log.id}</td>
                    <td className="py-2 pr-3 text-hint whitespace-nowrap">{log.time}</td>
                    <td className="py-2 pr-3 text-label">{log.user}</td>
                    <td className="py-2 pr-3"><Badge intent="info" size="xs">{log.type}</Badge></td>
                    <td className="py-2 pr-3 text-label max-w-[200px] truncate">{log.input}</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{log.tokens}</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{log.latency}</td>
                    <td className="py-2 pr-3 text-center">
                      {log.masked > 0 && <Badge intent="warning" size="xs">{log.masked}건</Badge>}
                      {log.masked === 0 && <span className="text-hint">-</span>}
                    </td>
                    <td className="py-2"><Badge intent={statusIntent(log.status)} size="xs">{log.status}</Badge></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function EvalTab() {
  return (
    <div className="space-y-4">
      {kpiCard(EVAL_KPI.map((k) => ({ label: k.label, value: k.value, target: k.target, ok: k.ok })))}

      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <BarChart3 className="w-4 h-4 text-violet-400" />
            <h3 className="text-sm font-bold text-heading">RAGAS 자동 평가 결과 (주 1회)</h3>
            <Badge intent="muted" size="xs">MLflow Experiment</Badge>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">버전</th>
                  <th className="text-left py-2 pr-3">평가일</th>
                  <th className="text-right py-2 pr-3">할루시네이션</th>
                  <th className="text-right py-2 pr-3">BLEU</th>
                  <th className="text-right py-2 pr-3">ROUGE</th>
                  <th className="text-right py-2 pr-3">F1</th>
                  <th className="text-right py-2 pr-3">Faithfulness</th>
                  <th className="text-right py-2 pr-3">Relevancy</th>
                  <th className="text-right py-2">Context</th>
                </tr>
              </thead>
              <tbody>
                {EVAL_METRICS.map((e, i) => (
                  <tr key={e.version} className={`border-b border-border/50 hover:bg-surface-overlay ${i === 0 ? 'bg-emerald-500/5' : ''}`}>
                    <td className="py-2 pr-3 font-mono font-bold text-heading">{e.version}</td>
                    <td className="py-2 pr-3 text-hint">{e.date}</td>
                    <td className="py-2 pr-3 text-right font-mono">
                      <Badge intent={e.hallu <= 5 ? 'success' : 'critical'} size="xs">{e.hallu}%</Badge>
                    </td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{e.bleu}</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{e.rouge}</td>
                    <td className="py-2 pr-3 text-right font-mono">
                      <Badge intent={e.f1 >= 0.91 ? 'success' : 'warning'} size="xs">{e.f1}</Badge>
                    </td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{e.faithfulness}</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{e.relevancy}</td>
                    <td className="py-2 text-right font-mono text-label">{e.context}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* 버전별 개선 추이 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <TrendingUp className="w-4 h-4 text-emerald-400" />
            <h3 className="text-sm font-bold text-heading">버전별 품질 추이</h3>
          </div>
          <div className="space-y-2">
            {EVAL_METRICS.map((e) => (
              <div key={e.version} className="flex items-center gap-3">
                <span className="w-14 text-[11px] font-mono font-bold text-heading">{e.version}</span>
                <div className="flex-1 bg-surface-overlay rounded-full h-4 overflow-hidden">
                  <div className="h-full rounded-full bg-emerald-500/60 flex items-center justify-end pr-2" style={{ width: `${e.f1 * 100}%` }}>
                    <span className="text-[9px] font-mono text-on-vivid">{(e.f1 * 100).toFixed(1)}%</span>
                  </div>
                </div>
                <Badge intent={e.hallu <= 5 ? 'success' : 'warning'} size="xs">H {e.hallu}%</Badge>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function DataTab() {
  return (
    <div className="space-y-4">
      {kpiCard(DATA_KPI)}

      {/* 문서 등록 카테고리 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <FileText className="w-4 h-4 text-emerald-400" />
            <h3 className="text-sm font-bold text-heading">문서 등록 (법령·지침·매뉴얼·사례)</h3>
            <Badge intent="muted" size="xs">DVC 버전관리</Badge>
          </div>
          <div className="grid grid-cols-2 lg:grid-cols-5 gap-2 mb-4">
            {DOC_CATEGORIES.map((dc) => (
              <button key={dc.key} type="button" className="bg-surface-overlay hover:bg-blue-600/10 border border-border hover:border-blue-500/30 rounded-lg p-3 text-left transition-colors">
                <div className="text-lg mb-1">{dc.icon}</div>
                <div className="text-[11px] font-bold text-heading">{dc.label}</div>
                <div className="text-[9px] text-hint mt-0.5">{dc.desc}</div>
              </button>
            ))}
          </div>
          {/* 등록 문서 목록 */}
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">ID</th>
                  <th className="text-left py-2 pr-3">문서명</th>
                  <th className="text-left py-2 pr-3">분류</th>
                  <th className="text-left py-2 pr-3">버전</th>
                  <th className="text-right py-2 pr-3">페이지</th>
                  <th className="text-left py-2 pr-3">등록일</th>
                  <th className="text-left py-2">상태</th>
                </tr>
              </thead>
              <tbody>
                {REGISTERED_DOCS.map((doc) => (
                  <tr key={doc.id} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 font-mono text-blue-400">{doc.id}</td>
                    <td className="py-2 pr-3 text-label max-w-[300px] truncate">{doc.title}</td>
                    <td className="py-2 pr-3">
                      <Badge intent="info" size="xs">
                        {DOC_CATEGORIES.find((c) => c.key === doc.category)?.label ?? doc.category}
                      </Badge>
                    </td>
                    <td className="py-2 pr-3 font-mono text-hint">{doc.version}</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{doc.pages}</td>
                    <td className="py-2 pr-3 text-hint">{doc.date}</td>
                    <td className="py-2"><Badge intent={statusIntent(doc.status)} size="xs">{doc.status}</Badge></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Database className="w-4 h-4 text-blue-400" />
            <h3 className="text-sm font-bold text-heading">지식 데이터 소스</h3>
            <Badge intent="muted" size="xs">BGE-M3 임베딩</Badge>
            <Badge intent="muted" size="xs">pgvector</Badge>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">카테고리</th>
                  <th className="text-right py-2 pr-3">건수</th>
                  <th className="text-left py-2 pr-3">최종 갱신</th>
                  <th className="text-left py-2 pr-3">임베딩 상태</th>
                  <th className="text-left py-2 pr-3">버전</th>
                  <th className="text-right py-2">크기</th>
                </tr>
              </thead>
              <tbody>
                {KNOWLEDGE_SOURCES.map((ks) => (
                  <tr key={ks.category} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 text-label font-medium">{ks.category}</td>
                    <td className="py-2 pr-3 text-right font-mono text-heading">{ks.count.toLocaleString()}</td>
                    <td className="py-2 pr-3 text-hint">{ks.lastUpdate}</td>
                    <td className="py-2 pr-3"><Badge intent={statusIntent(ks.embedding)} size="xs">{ks.embedding}</Badge></td>
                    <td className="py-2 pr-3 font-mono text-hint">{ks.version}</td>
                    <td className="py-2 text-right text-hint">{ks.size}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="mt-3 pt-3 border-t border-border flex items-center justify-between text-[10px] text-hint">
            <span>총 {KNOWLEDGE_SOURCES.reduce((s, k) => s + k.count, 0).toLocaleString()}건 등록</span>
            <span>총 용량 {KNOWLEDGE_SOURCES.reduce((s, k) => s + parseFloat(k.size), 0).toFixed(1)}GB</span>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function RagTab() {
  return (
    <div className="space-y-4">
      {kpiCard(RAG_KPI)}

      {/* 파이프라인 단계 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Layers className="w-4 h-4 text-indigo-400" />
            <h3 className="text-sm font-bold text-heading">RAG 파이프라인 단계</h3>
            <Badge intent="muted" size="xs">pgvector + FAISS</Badge>
            <Badge intent="muted" size="xs">BGE Reranker</Badge>
          </div>
          <div className="space-y-2">
            {RAG_PIPELINE.map((stage, i) => (
              <div key={stage.stage} className="flex items-center gap-3 bg-surface-overlay rounded-lg p-3">
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-[11px] font-bold text-heading">{stage.stage}</span>
                    <Badge intent="success" size="xs">{stage.status}</Badge>
                  </div>
                  <div className="text-[10px] text-hint">{stage.desc}</div>
                </div>
                <div className="text-right">
                  <div className="text-[10px] text-hint">엔진</div>
                  <div className="text-[11px] text-label">{stage.engine}</div>
                </div>
                <div className="text-right min-w-[60px]">
                  <div className="text-[10px] text-hint">지연</div>
                  <div className="text-[11px] font-mono text-heading">{stage.latency}</div>
                </div>
                {i < RAG_PIPELINE.length - 1 && <ArrowRight className="w-3 h-3 text-hint shrink-0" />}
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 재색인 이력 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <RefreshCw className="w-4 h-4 text-amber-400" />
            <h3 className="text-sm font-bold text-heading">Airflow DAG 재색인 이력</h3>
            <Badge intent="muted" size="xs">일 1회 자동</Badge>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">ID</th>
                  <th className="text-left py-2 pr-3">실행 시각</th>
                  <th className="text-right py-2 pr-3">문서 수</th>
                  <th className="text-right py-2 pr-3">소요시간</th>
                  <th className="text-left py-2 pr-3">변동</th>
                  <th className="text-left py-2">상태</th>
                </tr>
              </thead>
              <tbody>
                {REINDEX_HISTORY.map((r) => (
                  <tr key={r.id} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 font-mono text-blue-400">{r.id}</td>
                    <td className="py-2 pr-3 text-hint">{r.date}</td>
                    <td className="py-2 pr-3 text-right font-mono text-label">{r.docs.toLocaleString()}</td>
                    <td className="py-2 pr-3 text-right text-label">{r.duration}</td>
                    <td className="py-2 pr-3 text-emerald-400">{r.delta}</td>
                    <td className="py-2"><Badge intent="success" size="xs">{r.status}</Badge></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function QualityTab() {
  return (
    <div className="space-y-4">
      {/* 불용어 관리 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Ban className="w-4 h-4 text-orange-400" />
            <h3 className="text-sm font-bold text-heading">불용어 용어 보관</h3>
            <Badge intent="info" size="xs">{STOPWORDS.length}개 등록</Badge>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">#</th>
                  <th className="text-left py-2 pr-3">불용어</th>
                  <th className="text-left py-2 pr-3">분류</th>
                  <th className="text-left py-2 pr-3">상태</th>
                  <th className="text-left py-2 pr-3">등록자</th>
                  <th className="text-left py-2">등록일</th>
                </tr>
              </thead>
              <tbody>
                {STOPWORDS.map((sw) => (
                  <tr key={sw.id} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 text-hint">{sw.id}</td>
                    <td className="py-2 pr-3 font-mono font-bold text-heading">{sw.word}</td>
                    <td className="py-2 pr-3"><Badge intent="muted" size="xs">{sw.category}</Badge></td>
                    <td className="py-2 pr-3"><Badge intent="success" size="xs">{sw.status}</Badge></td>
                    <td className="py-2 pr-3 text-hint">{sw.addedBy}</td>
                    <td className="py-2 text-hint">{sw.date}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* 불용어·욕설 필터링 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Shield className="w-4 h-4 text-red-400" />
            <h3 className="text-sm font-bold text-heading">불용어 용어 보완 (욕설·유해 표현 필터링)</h3>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">카테고리</th>
                  <th className="text-right py-2 pr-3">등록 패턴 수</th>
                  <th className="text-left py-2 pr-3">최종 갱신</th>
                  <th className="text-left py-2 pr-3">상태</th>
                  <th className="text-left py-2">처리 방식</th>
                </tr>
              </thead>
              <tbody>
                {PROFANITY_FILTERS.map((pf) => (
                  <tr key={pf.category} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 text-label font-medium">{pf.category}</td>
                    <td className="py-2 pr-3 text-right font-mono text-heading">{pf.count.toLocaleString()}</td>
                    <td className="py-2 pr-3 text-hint">{pf.lastUpdate}</td>
                    <td className="py-2 pr-3"><Badge intent="success" size="xs">{pf.status}</Badge></td>
                    <td className="py-2">
                      <Badge intent={pf.action.includes('차단') ? 'critical' : 'warning'} size="xs">{pf.action}</Badge>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="mt-3 pt-3 border-t border-border text-[10px] text-hint">
            총 {PROFANITY_FILTERS.reduce((s, f) => s + f.count, 0).toLocaleString()}개 패턴 등록 · 입력/출력 양방향 필터링 적용
          </div>
        </CardContent>
      </Card>

      {/* 분류체계 보관/수정 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Layers className="w-4 h-4 text-indigo-400" />
            <h3 className="text-sm font-bold text-heading">분류체계 보관/수정</h3>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">ID</th>
                  <th className="text-left py-2 pr-3">분류체계명</th>
                  <th className="text-right py-2 pr-3">항목 수</th>
                  <th className="text-left py-2 pr-3">설명</th>
                  <th className="text-left py-2 pr-3">버전</th>
                  <th className="text-left py-2">갱신일</th>
                </tr>
              </thead>
              <tbody>
                {TAXONOMY.map((tx) => (
                  <tr key={tx.id} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 font-mono text-blue-400">{tx.id}</td>
                    <td className="py-2 pr-3 text-label font-medium">{tx.name}</td>
                    <td className="py-2 pr-3 text-right font-mono text-heading">{tx.items}</td>
                    <td className="py-2 pr-3 text-hint max-w-[250px] truncate">{tx.desc}</td>
                    <td className="py-2 pr-3 font-mono text-hint">{tx.version}</td>
                    <td className="py-2 text-hint">{tx.date}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* 규칙 보완 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Settings className="w-4 h-4 text-cyan-400" />
            <h3 className="text-sm font-bold text-heading">규칙 보완</h3>
          </div>
          <div className="space-y-2">
            {QUALITY_RULES.map((qr) => (
              <div key={qr.id} className="flex items-center gap-3 bg-surface-overlay rounded-lg p-3">
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="font-mono text-[10px] text-blue-400">{qr.id}</span>
                    <span className="text-[11px] font-bold text-heading">{qr.name}</span>
                    <Badge intent="success" size="xs">{qr.status}</Badge>
                    <Badge intent={qr.priority === '높음' ? 'critical' : qr.priority === '중간' ? 'warning' : 'muted'} size="xs">
                      {qr.priority}
                    </Badge>
                  </div>
                  <div className="text-[10px] text-hint">{qr.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function SecurityTab() {
  return (
    <div className="space-y-4">
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Shield className="w-4 h-4 text-red-400" />
            <h3 className="text-sm font-bold text-heading">3단계 보안 파이프라인</h3>
            <Badge intent="muted" size="xs">Keycloak RBAC</Badge>
            <Badge intent="muted" size="xs">JWT / TLS 1.3</Badge>
          </div>
          <div className="space-y-2">
            {SECURITY_LAYERS.map((sl) => (
              <div key={sl.layer} className="flex items-center gap-3 bg-surface-overlay rounded-lg p-3">
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-[11px] font-bold text-heading">{sl.layer}</span>
                    <Badge intent="success" size="xs">{sl.status}</Badge>
                  </div>
                  <div className="text-[10px] text-hint">{sl.desc}</div>
                </div>
                {sl.total > 0 && (
                  <div className="text-right">
                    <div className="text-[10px] text-hint">차단/처리</div>
                    <div className="text-[11px] font-mono text-heading">
                      {sl.blocked.toLocaleString()}<span className="text-hint">/{sl.total.toLocaleString()}</span>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 보안 KPI */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Lock className="w-4 h-4 text-amber-400" />
            <h3 className="text-sm font-bold text-heading">보안 KPI</h3>
          </div>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
            <div className="bg-surface-overlay rounded-lg p-3">
              <div className="text-[10px] text-hint mb-1">마스킹 자동화</div>
              <div className="text-lg font-bold text-emerald-400">100%</div>
              <div className="flex items-center gap-1 mt-1">
                <CheckCircle className="w-3 h-3 text-emerald-400" />
                <span className="text-[9px] text-hint">목표 100%</span>
              </div>
            </div>
            <div className="bg-surface-overlay rounded-lg p-3">
              <div className="text-[10px] text-hint mb-1">외부 LLM 차단</div>
              <div className="text-lg font-bold text-emerald-400">완전차단</div>
              <div className="flex items-center gap-1 mt-1">
                <CheckCircle className="w-3 h-3 text-emerald-400" />
                <span className="text-[9px] text-hint">행정망 망분리</span>
              </div>
            </div>
            <div className="bg-surface-overlay rounded-lg p-3">
              <div className="text-[10px] text-hint mb-1">입력 필터 차단율</div>
              <div className="text-lg font-bold text-heading">0.96%</div>
              <div className="flex items-center gap-1 mt-1">
                <CheckCircle className="w-3 h-3 text-emerald-400" />
                <span className="text-[9px] text-hint">12건 차단</span>
              </div>
            </div>
            <div className="bg-surface-overlay rounded-lg p-3">
              <div className="text-[10px] text-hint mb-1">TLS 암호화</div>
              <div className="text-lg font-bold text-emerald-400">TLS 1.3</div>
              <div className="flex items-center gap-1 mt-1">
                <CheckCircle className="w-3 h-3 text-emerald-400" />
                <span className="text-[9px] text-hint">모든 구간</span>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function MonitoringTab() {
  return (
    <div className="space-y-4">
      {/* GPU 노드 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Cpu className="w-4 h-4 text-purple-400" />
            <h3 className="text-sm font-bold text-heading">GPU 노드 상태</h3>
            <Badge intent="muted" size="xs">Prometheus + Grafana</Badge>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            {GPU_NODES.map((node) => (
              <div key={node.name} className="bg-surface-overlay rounded-lg p-3">
                <div className="flex items-center justify-between mb-2">
                  <span className="text-[11px] font-bold text-heading">{node.name}</span>
                  <Badge intent="success" size="xs">{node.status}</Badge>
                </div>
                <div className="text-[10px] text-hint mb-2">{node.gpu} — {node.role}</div>
                <div className="space-y-1.5">
                  <div>
                    <div className="flex justify-between text-[9px] mb-0.5">
                      <span className="text-hint">GPU 사용률</span>
                      <span className="text-label">{node.util}%</span>
                    </div>
                    <div className="h-1.5 bg-background rounded-full overflow-hidden">
                      <div className={`h-full rounded-full ${node.util > 80 ? 'bg-red-500' : node.util > 60 ? 'bg-amber-500' : 'bg-emerald-500'}`} style={{ width: `${node.util}%` }} />
                    </div>
                  </div>
                  <div>
                    <div className="flex justify-between text-[9px] mb-0.5">
                      <span className="text-hint">VRAM</span>
                      <span className="text-label">{node.mem}%</span>
                    </div>
                    <div className="h-1.5 bg-background rounded-full overflow-hidden">
                      <div className="h-full rounded-full bg-blue-500" style={{ width: `${node.mem}%` }} />
                    </div>
                  </div>
                  <div className="flex justify-between text-[9px] text-hint">
                    <span>온도</span>
                    <span>{node.temp}°C</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 서비스 상태 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <Server className="w-4 h-4 text-cyan-400" />
            <h3 className="text-sm font-bold text-heading">서비스 상태</h3>
          </div>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-2">
            {SERVICES.map((svc) => (
              <div key={svc.name} className="bg-surface-overlay rounded-lg p-2.5 flex items-center gap-2">
                <div className="w-2 h-2 rounded-full bg-emerald-400 shrink-0" />
                <div className="min-w-0">
                  <div className="text-[11px] font-medium text-heading truncate">{svc.name}</div>
                  <div className="text-[9px] text-hint">:{svc.port} · {svc.version} · {svc.uptime}</div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 알림 규칙 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center gap-2 mb-3">
            <AlertTriangle className="w-4 h-4 text-amber-400" />
            <h3 className="text-sm font-bold text-heading">Alertmanager 규칙</h3>
            <Badge intent="muted" size="xs">이상 탐지 ≤30초</Badge>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-border text-hint">
                  <th className="text-left py-2 pr-3">규칙명</th>
                  <th className="text-left py-2 pr-3">조건</th>
                  <th className="text-left py-2 pr-3">액션</th>
                  <th className="text-left py-2">상태</th>
                </tr>
              </thead>
              <tbody>
                {ALERT_RULES.map((rule) => (
                  <tr key={rule.name} className="border-b border-border/50 hover:bg-surface-overlay">
                    <td className="py-2 pr-3 text-label font-medium">{rule.name}</td>
                    <td className="py-2 pr-3 font-mono text-hint">{rule.condition}</td>
                    <td className="py-2 pr-3 text-label">{rule.action}</td>
                    <td className="py-2"><Badge intent="success" size="xs">{rule.status}</Badge></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

// ─── 메인 컴포넌트 ──────────────────

export function LLMOpsPage() {
  const { t } = useTranslation('ai');
  const [tab, setTab] = useState<Tab>('model');

  const renderTab = () => {
    switch (tab) {
      case 'model': return <ModelTab />;
      case 'prompt': return <PromptTab />;
      case 'inference': return <InferenceTab />;
      case 'log': return <LogTab />;
      case 'eval': return <EvalTab />;
      case 'data': return <DataTab />;
      case 'rag': return <RagTab />;
      case 'quality': return <QualityTab />;
      case 'security': return <SecurityTab />;
      case 'monitoring': return <MonitoringTab />;
    }
  };

  return (
    <PageContainer>
      <PageHeader
        icon={Brain}
        iconColor="text-violet-400"
        title={t('llmOps.title')}
        description={t('llmOps.desc')}
        demo
      />

      {/* 탭 네비게이션 */}
      <div className="flex gap-1 overflow-x-auto border-b border-border pb-px mb-4">
        {TABS.map((t) => {
          const Icon = t.icon;
          return (
            <button
              key={t.key}
              type="button"
              onClick={() => setTab(t.key)}
              className={`flex items-center gap-1.5 px-3 py-2 text-[11px] font-medium whitespace-nowrap rounded-t-lg transition-colors ${
                tab === t.key
                  ? 'bg-blue-600/10 border-b-2 border-blue-500 text-blue-400'
                  : 'text-hint hover:bg-surface-overlay hover:text-label'
              }`}
            >
              <Icon className="w-3.5 h-3.5" />
              {t.label}
            </button>
          );
        })}
      </div>

      {renderTab()}
    </PageContainer>
  );
}
