/**
 * 디자인 시스템 관리 - 편집 가능 버전
 * Foundation, Components, Tokens, Responsive 모든 항목에 대해 추가/수정/삭제 가능
 */

import React, { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "./ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Textarea } from "./ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "./ui/dialog";
import {
  Palette, Code, Layers, Box, Plus, Edit, Trash2, Search, Monitor, Tablet as TabletIcon, Smartphone,
  Type, Ruler, Image as ImageIcon, CheckCircle, XCircle, Copy, Eye, ChevronUp, ChevronDown, X, Check, Package
} from "lucide-react";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { ComponentDetailDialog } from "./ComponentDetailDialog";
import { toast } from "sonner@2.0.3";
import { Checkbox } from "./ui/checkbox";
import { Switch } from "./ui/switch";
import { RadioGroup } from "./ui/radio-group";
import { Slider } from "./ui/slider";
import { Progress } from "./ui/progress";
import { Alert } from "./ui/alert";
import { Separator } from "./ui/separator";
import { Accordion } from "./ui/accordion";
import { AlertDialog } from "./ui/alert-dialog";
import { DropdownMenu } from "./ui/dropdown-menu";
import { Popover } from "./ui/popover";
import { Tooltip } from "./ui/tooltip";
import { Sheet } from "./ui/sheet";
import { Skeleton } from "./ui/skeleton";
import { Avatar } from "./ui/avatar";
import { Breadcrumb } from "./ui/breadcrumb";
import { QuoteNumberField } from "./modules/QuoteNumberField";
import { useData } from "./contexts/DataContext";

// 컴포넌트 맵 생성
const COMPONENT_MAP: Record<string, React.ComponentType<any>> = {
  Button,
  Input,
  Label,
  Badge,
  Textarea,
  Select,
  Card,
  Checkbox,
  Switch,
  RadioGroup,
  Slider,
  Progress,
  Alert,
  Separator,
  Tabs,
  Table,
  Dialog,
  AlertDialog,
  DropdownMenu,
  Popover,
  Tooltip,
  Sheet,
  Skeleton,
  Avatar,
  Breadcrumb,
  Accordion,
  PageLayout,
  PageHeader,
};

// ============= 타입 정의 =============

interface ColorItem {
  id: string;
  name: string;
  value: string;
  category: "primary" | "secondary" | "neutral" | "semantic";
  description?: string;
}

interface TypographyItem {
  id: string;
  name: string;
  fontSize: string;
  fontWeight: string;
  lineHeight: string;
  letterSpacing?: string;
  usage: string;
}

interface SpacingItem {
  id: string;
  name: string;
  value: string;
  pixels: string;
  usage: string;
}

interface ShadowItem {
  id: string;
  name: string;
  value: string;
  usage: string;
}

interface CompositionItem {
  id: string;
  componentId: string;
  componentName: string;
  componentDisplayName: string;
  componentCategory: "atoms" | "molecules" | "organisms";
  props?: Record<string, any>;
  order: number;
}

interface ComponentItem {
  id: string;
  name: string;
  displayName: string;
  category: "atoms" | "molecules" | "organisms" | "templates";
  path: string;
  description: string;
  status: "stable" | "beta" | "deprecated";
  responsive: boolean;
  composition?: CompositionItem[];
}

interface TokenItem {
  id: string;
  name: string;
  value: string;
  category: "color" | "typography" | "spacing" | "border" | "shadow" | "animation";
  description: string;
}

interface ResponsiveBreakpoint {
  id: string;
  name: string;
  minWidth: string;
  maxWidth?: string;
  description: string;
}

// ============= 초기 데이터 =============

const INITIAL_COLORS: ColorItem[] = [
  // Primary 계열
  { id: "1", name: "Primary", value: "#3B82F6", category: "primary", description: "주요 브랜드 색상 (Blue-500)" },
  { id: "2", name: "Primary-Dark", value: "#2563EB", category: "primary", description: "주요 색상 어두운 버전 (Blue-600)" },
  { id: "3", name: "Primary-Light", value: "#60A5FA", category: "primary", description: "주요 색상 밝은 버전 (Blue-400)" },
  
  // Secondary 계열
  { id: "4", name: "Secondary", value: "#8B5CF6", category: "secondary", description: "보조 색상 (Purple-500)" },
  { id: "5", name: "Secondary-Dark", value: "#7C3AED", category: "secondary", description: "보조 색상 어두운 버전 (Purple-600)" },
  
  // Semantic - Success (Green)
  { id: "6", name: "Success", value: "#10B981", category: "semantic", description: "성공 상태 (Green-500) - 사용중, 확정, 수주" },
  { id: "7", name: "Success-Dark", value: "#059669", category: "semantic", description: "성공 상태 어두운 버전 (Green-600)" },
  { id: "8", name: "Success-Light", value: "#34D399", category: "semantic", description: "성공 상태 밝은 버전 (Green-400)" },
  { id: "9", name: "Success-50", value: "#ECFDF5", category: "semantic", description: "성공 배경 (Green-50)" },
  { id: "10", name: "Success-100", value: "#D1FAE5", category: "semantic", description: "성공 배경 밝은 (Green-100)" },
  { id: "11", name: "Success-200", value: "#A7F3D0", category: "semantic", description: "성공 테두리 (Green-200)" },
  { id: "12", name: "Success-700", value: "#047857", category: "semantic", description: "성공 텍스트 어두운 (Green-700)" },
  
  // Semantic - Warning (Orange/Yellow)
  { id: "13", name: "Warning", value: "#F59E0B", category: "semantic", description: "경고 상태 (Orange-500)" },
  { id: "14", name: "Warning-Dark", value: "#D97706", category: "semantic", description: "경고 상태 어두운 버전 (Orange-600)" },
  { id: "15", name: "Warning-50", value: "#FFF7ED", category: "semantic", description: "경고 배경 (Orange-50)" },
  { id: "16", name: "Warning-100", value: "#FFEDD5", category: "semantic", description: "경고 배경 밝은 (Orange-100)" },
  { id: "17", name: "Warning-200", value: "#FED7AA", category: "semantic", description: "경고 테두리 (Orange-200)" },
  { id: "18", name: "Warning-700", value: "#C2410C", category: "semantic", description: "경고 텍스트 (Orange-700)" },
  
  // Semantic - Error (Red)
  { id: "19", name: "Error", value: "#EF4444", category: "semantic", description: "오류 상태 (Red-500) - 폐기, 거부" },
  { id: "20", name: "Error-Dark", value: "#DC2626", category: "semantic", description: "오류 상태 어두운 버전 (Red-600)" },
  { id: "21", name: "Error-50", value: "#FEF2F2", category: "semantic", description: "오류 배경 (Red-50)" },
  { id: "22", name: "Error-200", value: "#FECACA", category: "semantic", description: "오류 테두리 (Red-200)" },
  { id: "23", name: "Error-700", value: "#B91C1C", category: "semantic", description: "오류 텍스트 (Red-700)" },
  
  // Semantic - Info (Blue)
  { id: "24", name: "Info", value: "#3B82F6", category: "semantic", description: "정보 상태 (Blue-500) - 개발중, 산출내역" },
  { id: "25", name: "Info-Dark", value: "#2563EB", category: "semantic", description: "정보 상태 어두운 (Blue-600)" },
  { id: "26", name: "Info-50", value: "#EFF6FF", category: "semantic", description: "정보 배경 (Blue-50)" },
  { id: "27", name: "Info-100", value: "#DBEAFE", category: "semantic", description: "정보 배경 밝은 (Blue-100)" },
  { id: "28", name: "Info-200", value: "#BFDBFE", category: "semantic", description: "정보 테두리 (Blue-200)" },
  { id: "29", name: "Info-700", value: "#1D4ED8", category: "semantic", description: "정보 텍스트 (Blue-700)" },
  
  // Functional - Purple (제품, 발주서, 수주전환)
  { id: "30", name: "Purple-50", value: "#FAF5FF", category: "semantic", description: "제품/발주서 배경 (Purple-50)" },
  { id: "31", name: "Purple-100", value: "#F3E8FF", category: "semantic", description: "제품/발주서 배경 밝은 (Purple-100)" },
  { id: "32", name: "Purple-200", value: "#E9D5FF", category: "semantic", description: "제품/발주서 테두리 (Purple-200)" },
  { id: "33", name: "Purple-500", value: "#A855F7", category: "semantic", description: "제품/발주서 (Purple-500)" },
  { id: "34", name: "Purple-600", value: "#9333EA", category: "semantic", description: "제품/발주서 어두운 (Purple-600)" },
  { id: "35", name: "Purple-700", value: "#7E22CE", category: "semantic", description: "제품/발주서 텍스트 (Purple-700)" },
  
  // Functional - Lime (견적서, 확정)
  { id: "36", name: "Lime-50", value: "#F7FEE7", category: "semantic", description: "견적서 배경 (Lime-50)" },
  { id: "37", name: "Lime-100", value: "#ECFCCB", category: "semantic", description: "견적서 배경 밝은 (Lime-100)" },
  { id: "38", name: "Lime-300", value: "#BEF264", category: "semantic", description: "견적서 테두리 (Lime-300)" },
  { id: "39", name: "Lime-600", value: "#65A30D", category: "semantic", description: "견적서 확정 (Lime-600)" },
  { id: "40", name: "Lime-700", value: "#4D7C0F", category: "semantic", description: "견적서 텍스트 (Lime-700)" },
  
  // Functional - Cyan (부자재)
  { id: "41", name: "Cyan-50", value: "#ECFEFF", category: "semantic", description: "부자재 배경 (Cyan-50)" },
  { id: "42", name: "Cyan-500", value: "#06B6D4", category: "semantic", description: "부자재 (Cyan-500)" },
  
  // Neutral - Gray
  { id: "43", name: "Gray-50", value: "#F9FAFB", category: "neutral", description: "매우 밝은 회색" },
  { id: "44", name: "Gray-100", value: "#F3F4F6", category: "neutral", description: "밝은 회색" },
  { id: "45", name: "Gray-200", value: "#E5E7EB", category: "neutral", description: "테두리 회색" },
  { id: "46", name: "Gray-300", value: "#D1D5DB", category: "neutral", description: "구분선 회색" },
  { id: "47", name: "Gray-500", value: "#6B7280", category: "neutral", description: "보조 텍스트" },
  { id: "48", name: "Gray-600", value: "#4B5563", category: "neutral", description: "보조 텍스트 어두운" },
  { id: "49", name: "Gray-900", value: "#111827", category: "neutral", description: "매우 어두운 회색" },
];

const INITIAL_TYPOGRAPHY: TypographyItem[] = [
  { id: "1", name: "Heading-1", fontSize: "2.25rem", fontWeight: "700", lineHeight: "2.5rem", usage: "페이지 제목" },
  { id: "2", name: "Heading-2", fontSize: "1.875rem", fontWeight: "600", lineHeight: "2.25rem", usage: "섹션 제목" },
  { id: "3", name: "Heading-3", fontSize: "1.5rem", fontWeight: "600", lineHeight: "2rem", usage: "카드 제목" },
  { id: "4", name: "Body-Large", fontSize: "1.125rem", fontWeight: "400", lineHeight: "1.75rem", usage: "본문 큰 글씨" },
  { id: "5", name: "Body", fontSize: "1rem", fontWeight: "400", lineHeight: "1.5rem", usage: "기본 본문" },
  { id: "6", name: "Body-Small", fontSize: "0.875rem", fontWeight: "400", lineHeight: "1.25rem", usage: "작은 본문" },
  { id: "7", name: "Caption", fontSize: "0.75rem", fontWeight: "400", lineHeight: "1rem", usage: "캡션, 도움말" },
];

const INITIAL_SPACING: SpacingItem[] = [
  { id: "1", name: "xs", value: "0.25rem", pixels: "4px", usage: "매우 작은 간격" },
  { id: "2", name: "sm", value: "0.5rem", pixels: "8px", usage: "작은 간격" },
  { id: "3", name: "md", value: "1rem", pixels: "16px", usage: "기본 간격" },
  { id: "4", name: "lg", value: "1.5rem", pixels: "24px", usage: "큰 간격" },
  { id: "5", name: "xl", value: "2rem", pixels: "32px", usage: "매우 큰 간격" },
  { id: "6", name: "2xl", value: "3rem", pixels: "48px", usage: "초대형 간격" },
];

const INITIAL_SHADOWS: ShadowItem[] = [
  { id: "1", name: "sm", value: "0 1px 2px 0 rgba(0, 0, 0, 0.05)", usage: "작은 그림자" },
  { id: "2", name: "md", value: "0 4px 6px -1px rgba(0, 0, 0, 0.1)", usage: "기본 그림자" },
  { id: "3", name: "lg", value: "0 10px 15px -3px rgba(0, 0, 0, 0.1)", usage: "큰 그림자" },
  { id: "4", name: "xl", value: "0 20px 25px -5px rgba(0, 0, 0, 0.1)", usage: "매우 큰 그림자" },
];

const INITIAL_COMPONENTS: ComponentItem[] = [
  // ==================== ATOMS (UI) - 32개 ====================
  { id: "atom-1", name: "Button", displayName: "버튼", category: "atoms", path: "/components/ui/button.tsx", description: "클릭 가능한 버튼 컴포넌트", status: "stable", responsive: true },
  { id: "atom-2", name: "Input", displayName: "입력 필드", category: "atoms", path: "/components/ui/input.tsx", description: "텍스트 입력 필드", status: "stable", responsive: true },
  { id: "atom-3", name: "Textarea", displayName: "텍스트 영역", category: "atoms", path: "/components/ui/textarea.tsx", description: "여러 줄 텍스트 입력", status: "stable", responsive: true },
  { id: "atom-4", name: "Select", displayName: "셀렉트", category: "atoms", path: "/components/ui/select.tsx", description: "드롭다운 선택 메뉴", status: "stable", responsive: true },
  { id: "atom-5", name: "Checkbox", displayName: "체크박스", category: "atoms", path: "/components/ui/checkbox.tsx", description: "체크박스 선택", status: "stable", responsive: true },
  { id: "atom-6", name: "Switch", displayName: "스위치", category: "atoms", path: "/components/ui/switch.tsx", description: "토글 스위치", status: "stable", responsive: true },
  { id: "atom-7", name: "RadioGroup", displayName: "라디오 그룹", category: "atoms", path: "/components/ui/radio-group.tsx", description: "라디오 버튼 그룹", status: "stable", responsive: true },
  { id: "atom-8", name: "Label", displayName: "레이블", category: "atoms", path: "/components/ui/label.tsx", description: "폼 레이블", status: "stable", responsive: true },
  { id: "atom-9", name: "Slider", displayName: "슬라이더", category: "atoms", path: "/components/ui/slider.tsx", description: "범위 슬라이더", status: "stable", responsive: true },
  { id: "atom-10", name: "Badge", displayName: "뱃지", category: "atoms", path: "/components/ui/badge.tsx", description: "작은 라벨 배지", status: "stable", responsive: true },
  { id: "atom-11", name: "Progress", displayName: "프로그레스", category: "atoms", path: "/components/ui/progress.tsx", description: "진행률 표시 바", status: "stable", responsive: true },
  { id: "atom-12", name: "Card", displayName: "카드", category: "atoms", path: "/components/ui/card.tsx", description: "카드 컨테이너", status: "stable", responsive: true },
  { id: "atom-13", name: "Alert", displayName: "알림", category: "atoms", path: "/components/ui/alert.tsx", description: "알림 메시지 박스", status: "stable", responsive: true },
  { id: "atom-14", name: "Separator", displayName: "구분선", category: "atoms", path: "/components/ui/separator.tsx", description: "구분선", status: "stable", responsive: true },
  { id: "atom-15", name: "Tabs", displayName: "탭", category: "atoms", path: "/components/ui/tabs.tsx", description: "탭 네비게이션", status: "stable", responsive: true },
  { id: "atom-16", name: "Accordion", displayName: "아코디언", category: "atoms", path: "/components/ui/accordion.tsx", description: "접었다 펼치는 아코디언", status: "stable", responsive: true },
  { id: "atom-17", name: "Table", displayName: "테이블", category: "atoms", path: "/components/ui/table.tsx", description: "테이블 컴포넌트", status: "stable", responsive: true },
  { id: "atom-18", name: "Dialog", displayName: "다이얼로그", category: "atoms", path: "/components/ui/dialog.tsx", description: "모달 다이얼로그", status: "stable", responsive: true },
  { id: "atom-19", name: "AlertDialog", displayName: "확인 다이얼로그", category: "atoms", path: "/components/ui/alert-dialog.tsx", description: "확인/취소 알림 다이얼로그", status: "stable", responsive: true },
  { id: "atom-20", name: "DropdownMenu", displayName: "드롭다운 메뉴", category: "atoms", path: "/components/ui/dropdown-menu.tsx", description: "드롭다운 메뉴", status: "stable", responsive: true },
  { id: "atom-21", name: "Popover", displayName: "팝오버", category: "atoms", path: "/components/ui/popover.tsx", description: "팝오버 메뉴", status: "stable", responsive: true },
  { id: "atom-22", name: "Tooltip", displayName: "툴팁", category: "atoms", path: "/components/ui/tooltip.tsx", description: "툴팁", status: "stable", responsive: true },
  { id: "atom-23", name: "Sheet", displayName: "시트", category: "atoms", path: "/components/ui/sheet.tsx", description: "슬라이드 패널", status: "stable", responsive: true },
  { id: "atom-24", name: "Skeleton", displayName: "스켈레톤", category: "atoms", path: "/components/ui/skeleton.tsx", description: "로딩 스켈레톤", status: "stable", responsive: true },
  { id: "atom-25", name: "Avatar", displayName: "아바타", category: "atoms", path: "/components/ui/avatar.tsx", description: "아바타 이미지", status: "stable", responsive: true },
  { id: "atom-26", name: "Calendar", displayName: "캘린더", category: "atoms", path: "/components/ui/calendar.tsx", description: "날짜 선택 달력", status: "stable", responsive: true },
  { id: "atom-27", name: "Collapsible", displayName: "접을 수 있는 컨테이너", category: "atoms", path: "/components/ui/collapsible.tsx", description: "접을 수 있는 컨테이너", status: "stable", responsive: true },
  { id: "atom-28", name: "AspectRatio", displayName: "종횡비", category: "atoms", path: "/components/ui/aspect-ratio.tsx", description: "종횡비 유지 컨테이너", status: "stable", responsive: true },
  { id: "atom-29", name: "Breadcrumb", displayName: "브레드크럼", category: "atoms", path: "/components/ui/breadcrumb.tsx", description: "경로 탐색 breadcrumb", status: "stable", responsive: true },
  { id: "atom-30", name: "Pagination", displayName: "페이지네이션", category: "atoms", path: "/components/ui/pagination.tsx", description: "페이지네이션", status: "stable", responsive: true },
  { id: "atom-31", name: "Toggle", displayName: "토글", category: "atoms", path: "/components/ui/toggle.tsx", description: "토글 버튼", status: "stable", responsive: true },
  { id: "atom-32", name: "ToggleGroup", displayName: "토글 그룹", category: "atoms", path: "/components/ui/toggle-group.tsx", description: "토글 그룹", status: "stable", responsive: true },
  
  // ==================== MOLECULES - 9개 ====================
  { id: "mol-1", name: "FormField", displayName: "폼 필드", category: "molecules", path: "/components/molecules/FormField.tsx", description: "레이블 + 입력필드 조합 (필수 표시 지원)", status: "stable", responsive: true },
  { id: "mol-2", name: "SearchBar", displayName: "검색바", category: "molecules", path: "/components/molecules/SearchBar.tsx", description: "검색 아이콘 + 입력필드", status: "stable", responsive: true },
  { id: "mol-3", name: "StatCard", displayName: "통계 카드", category: "molecules", path: "/components/molecules/StatCard.tsx", description: "아이콘 + 통계 + 트렌드 카드", status: "stable", responsive: true },
  { id: "mol-4", name: "StatusBadge", displayName: "상태 배지", category: "molecules", path: "/components/molecules/StatusBadge.tsx", description: "상태별 컬러 배지", status: "stable", responsive: true },
  { id: "mol-5", name: "TableActions", displayName: "테이블 액션", category: "molecules", path: "/components/molecules/TableActions.tsx", description: "테이블 행 액션 버튼 그룹", status: "stable", responsive: true },
  { id: "mol-6", name: "IconWithBadge", displayName: "아이콘 + 배지", category: "molecules", path: "/components/molecules/IconWithBadge.tsx", description: "아이콘 + 카운트 배지", status: "stable", responsive: true },
  { id: "mol-7", name: "StandardDialog", displayName: "표준 다이얼로그", category: "molecules", path: "/components/molecules/StandardDialog.tsx", description: "표준 다이얼로그 - 일관된 마진과 스타일 적용", status: "stable", responsive: true },
  { id: "mol-8", name: "ConfirmDialog", displayName: "확인 다이얼로그", category: "molecules", path: "/components/molecules/StandardDialog.tsx", description: "확인/취소 다이얼로그", status: "stable", responsive: true },
  { id: "mol-9", name: "FormDialog", displayName: "폼 다이얼로그", category: "molecules", path: "/components/molecules/StandardDialog.tsx", description: "폼 입력용 다이얼로그", status: "stable", responsive: true },
  
  // ==================== ORGANISMS - 8개 ====================
  { id: "org-1", name: "PageHeader", displayName: "페이지 헤더", category: "organisms", path: "/components/organisms/PageHeader.tsx", description: "표준 페이지 헤더 (아이콘 + 제목 + 부제목 + 액션)", status: "stable", responsive: true },
  { id: "org-2", name: "StatCards", displayName: "통계 카드 그리드", category: "organisms", path: "/components/organisms/StatCards.tsx", description: "4개 통계 카드 그리드 레이아웃", status: "stable", responsive: true },
  { id: "org-3", name: "SearchFilter", displayName: "검색 필터", category: "organisms", path: "/components/organisms/SearchFilter.tsx", description: "검색바 + 다중 필터 조합", status: "stable", responsive: true },
  { id: "org-4", name: "EmptyState", displayName: "빈 상태", category: "organisms", path: "/components/organisms/EmptyState.tsx", description: "빈 상태 표시 (아이콘 + 메시지 + 액션)", status: "stable", responsive: true },
  { id: "org-5", name: "DataTable", displayName: "데이터 테이블", category: "organisms", path: "/components/organisms/DataTable.tsx", description: "고급 데이터 테이블 (정렬, 페이징, 타입별 렌더링, 모바일 카드뷰)", status: "stable", responsive: true },
  { id: "org-6", name: "FormSection", displayName: "폼 섹션", category: "organisms", path: "/components/organisms/FormSection.tsx", description: "접을 수 있는 폼 섹션 (에러 표시, 카운트 지원)", status: "stable", responsive: true },
  { id: "org-7", name: "MobileCard", displayName: "모바일 카드", category: "organisms", path: "/components/organisms/MobileCard.tsx", description: "모바일용 카드 뷰 (반응형 테이블 대체)", status: "stable", responsive: true },
  { id: "org-8", name: "PageLayout", displayName: "페이지 레이아웃", category: "organisms", path: "/components/organisms/PageLayout.tsx", description: "페이지 레이아웃 래퍼 (최대 너비, 여백 관리)", status: "stable", responsive: true },
  
  // ==================== TEMPLATES - 10개 ====================
  { id: "tmpl-1", name: "ResponsiveListTemplate", displayName: "반응형 목록 템플릿", category: "templates", path: "/components/templates/ResponsiveListTemplate.tsx", description: "기본 목록 템플릿 - 데스크톱/태블릿/모바일 반응형 (품목관리 스타일)", status: "stable", responsive: true },
  { id: "tmpl-2", name: "IntegratedListTemplateV2", displayName: "통합 목록 템플릿 V2", category: "templates", path: "/components/templates/IntegratedListTemplateV2.tsx", description: "기본 통합 목록_버젼2 - PageHeader + 통계 + 검색 + 탭 + 테이블/카드", status: "stable", responsive: true },
  { id: "tmpl-3", name: "ResponsiveFormTemplate", displayName: "반응형 폼 템플릿", category: "templates", path: "/components/templates/ResponsiveFormTemplate.tsx", description: "기본 등록_데스크톱/태블릿/모바일 통합 템플릿", status: "stable", responsive: true },
  { id: "tmpl-4", name: "IntegratedFormTemplateV2", displayName: "통합 폼 템플릿 V2", category: "templates", path: "/components/templates/IntegratedFormTemplateV2.tsx", description: "품목관리 상세 정보 페이지 기반 - Atoms(InfoLabel, InfoValue, StatusBadge), Molecules(InfoField, SectionHeader, InfoGrid, TabButton), Organisms(DetailSection, BOMTable, TabPanel, ImageGallery)로 구성된 상세 정보 레이아웃 템플릿", status: "stable", responsive: true },
  { id: "tmpl-9", name: "IntegratedFormTemplateV3", displayName: "통합 폼 템플릿 V3", category: "templates", path: "/components/templates/IntegratedFormTemplateV3.tsx", description: "품목관리 상세 페이지 완전 재현 - 설정 기반 템플릿 (반응형 그리드, 버전 관리, 이미지 갤러리, 테이블, 조건부 섹션 렌더링 포함). Atoms(FieldLabel, FieldValue), Molecules(InfoField, RevisionSelector, VersionHistory), Organisms(InfoSection, TableSection, ImageGallery)로 구성. 모든 요소와 레이아웃을 config 객체로 제어", status: "stable", responsive: true },
  { id: "tmpl-10", name: "CommonBottomSheet", displayName: "공통 바텀시트", category: "templates", path: "/components/templates/CommonBottomSheet.tsx", description: "모바일 바텀시트/데스크톱 다이얼로그 통합 템플릿 - 자동 반응형, 핸들바, 커스텀 푸터 지원 (위젯관리 스타일)", status: "stable", responsive: true },
  { id: "tmpl-5", name: "DashboardTemplate", displayName: "대시보드 템플릿", category: "templates", path: "/components/templates/DashboardTemplate.tsx", description: "대시보드 페이지 표준 템플릿", status: "stable", responsive: true },
  { id: "tmpl-6", name: "ListPageTemplate", displayName: "목록 페이지 템플릿", category: "templates", path: "/components/templates/ListPageTemplate.tsx", description: "목록 페이지 표준 템플릿", status: "stable", responsive: true },
  { id: "tmpl-7", name: "FormPageTemplate", displayName: "폼 페이지 템플릿", category: "templates", path: "/components/templates/FormPageTemplate.tsx", description: "폼 페이지 표준 템플릿", status: "stable", responsive: true },
  { id: "tmpl-8", name: "TabbedPageTemplate", displayName: "탭 페이지 템플릿", category: "templates", path: "/components/templates/TabbedPageTemplate.tsx", description: "탭 페이지 표준 템플릿", status: "stable", responsive: true },
];

const INITIAL_TOKENS: TokenItem[] = [
  // Color Tokens
  { id: "1", name: "--primary-color", value: "#3B82F6", category: "color", description: "주요 브랜드 색상" },
  { id: "2", name: "--success-color", value: "#10B981", category: "color", description: "성공/확정/수주 색상" },
  { id: "3", name: "--success-hover", value: "#059669", category: "color", description: "성공 호버 색상" },
  { id: "4", name: "--warning-color", value: "#F59E0B", category: "color", description: "경고 색상" },
  { id: "5", name: "--error-color", value: "#EF4444", category: "color", description: "오류/폐기 색상" },
  { id: "6", name: "--info-color", value: "#3B82F6", category: "color", description: "정보 색상" },
  { id: "7", name: "--quote-color", value: "#65A30D", category: "color", description: "견적서 색상 (Lime-600)" },
  { id: "8", name: "--quote-bg", value: "#F7FEE7", category: "color", description: "견적서 배경 (Lime-50)" },
  { id: "9", name: "--calculation-color", value: "#2563EB", category: "color", description: "산출내역서 색상 (Blue-600)" },
  { id: "10", name: "--calculation-bg", value: "#EFF6FF", category: "color", description: "산출내역서 배경 (Blue-50)" },
  { id: "11", name: "--order-color", value: "#9333EA", category: "color", description: "발주서 색상 (Purple-600)" },
  { id: "12", name: "--order-bg", value: "#FAF5FF", category: "color", description: "발주서 배경 (Purple-50)" },
  { id: "13", name: "--item-product-color", value: "#7E22CE", category: "color", description: "품목 제품 색상 (Purple-700)" },
  { id: "14", name: "--item-part-color", value: "#C2410C", category: "color", description: "품목 부품 색상 (Orange-700)" },
  { id: "15", name: "--item-material-color", value: "#047857", category: "color", description: "품목 부자재 색상 (Green-700)" },
  { id: "16", name: "--item-raw-color", value: "#1D4ED8", category: "color", description: "품목 원자재 색상 (Blue-700)" },
  { id: "17", name: "--status-active-color", value: "#10B981", category: "color", description: "사용중 상태 색상" },
  { id: "18", name: "--status-development-color", value: "#3B82F6", category: "color", description: "개발중 상태 색상" },
  { id: "19", name: "--status-discontinued-color", value: "#EF4444", category: "color", description: "폐기 상태 색상" },
  
  // Typography Tokens
  { id: "20", name: "--font-sans", value: "system-ui, sans-serif", category: "typography", description: "기본 폰트" },
  
  // Spacing Tokens
  { id: "21", name: "--spacing-unit", value: "0.25rem", category: "spacing", description: "기본 간격 단위" },
  
  // Border Tokens
  { id: "22", name: "--border-radius", value: "0.375rem", category: "border", description: "기본 테두리 반경" },
  
  // Animation Tokens
  { id: "23", name: "--transition-duration", value: "200ms", category: "animation", description: "기본 전환 시간" },
];

const INITIAL_BREAKPOINTS: ResponsiveBreakpoint[] = [
  { id: "1", name: "Mobile", minWidth: "0px", maxWidth: "767px", description: "모바일 디바이스" },
  { id: "2", name: "Tablet", minWidth: "768px", maxWidth: "1023px", description: "태블릿 디바이스" },
  { id: "3", name: "Desktop", minWidth: "1024px", description: "데스크톱 디바이스" },
];

// ============= 모듈 프리뷰 컴포넌트 =============

function ModulePreviewCard() {
  const { generateLotNumber } = useData();
  const [previewQuoteNumber, setPreviewQuoteNumber] = useState("");

  return (
    <div className="border rounded-lg p-6 space-y-4">
      <div className="flex items-start justify-between">
        <div className="space-y-1">
          <h3 className="font-semibold flex items-center gap-2">
            <Package className="h-4 w-4 text-primary" />
            QuoteNumberField
          </h3>
          <p className="text-sm text-muted-foreground">
            견적번호 자동 생성 및 직접 입력 기능을 제공하는 필드 컴포넌트
          </p>
        </div>
        <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
          stable
        </Badge>
      </div>
      
      <Separator />
      
      <div className="space-y-3">
        <div>
          <h4 className="text-sm font-medium mb-2">미리보기</h4>
          <div className="border rounded-lg p-4 bg-muted/30">
            <QuoteNumberField
              value={previewQuoteNumber}
              onChange={setPreviewQuoteNumber}
              onGenerate={() => generateLotNumber('quote')}
              label="견적번호"
              description="자동 생성 또는 직접 입력할 수 있습니다"
              required
            />
          </div>
        </div>

        <div>
          <h4 className="text-sm font-medium mb-2">경로</h4>
          <code className="text-xs bg-muted px-2 py-1 rounded">
            /components/modules/QuoteNumberField.tsx
          </code>
        </div>
        
        <div>
          <h4 className="text-sm font-medium mb-2">Props</h4>
          <div className="text-xs space-y-1 bg-muted p-3 rounded">
            <div><code>value: string</code> - 현재 견적번호 값</div>
            <div><code>onChange: (value: string) =&gt; void</code> - 값 변경 핸들러</div>
            <div><code>onGenerate: () =&gt; string</code> - 번호 생성 함수</div>
            <div><code>label?: string</code> - 필드 라벨 (기본: "견적번호")</div>
            <div><code>placeholder?: string</code> - 플레이스홀더 텍스트</div>
            <div><code>description?: string</code> - 설명 텍스트</div>
            <div><code>required?: boolean</code> - 필수 여부</div>
          </div>
        </div>
        
        <div>
          <h4 className="text-sm font-medium mb-2">사용 예시</h4>
          <pre className="text-xs bg-muted p-3 rounded overflow-x-auto">
{`import { QuoteNumberField } from "./modules/QuoteNumberField";

<QuoteNumberField
  value={quoteNumber}
  onChange={setQuoteNumber}
  onGenerate={() => generateLotNumber('quote')}
  required
/>`}
          </pre>
        </div>
        
        <div>
          <h4 className="text-sm font-medium mb-2">원본 위치</h4>
          <p className="text-xs text-muted-foreground">
            QuoteManagement3Write.tsx (1348-1374 라인) - 주석 처리됨
          </p>
        </div>
      </div>
    </div>
  );
}

// ============= 메인 컴포넌트 =============

export function DesignSystemManagement() {
  const [activeTab, setActiveTab] = useState<"foundation" | "components" | "tokens" | "responsive">("foundation");
  const [searchTerm, setSearchTerm] = useState("");

  // Foundation 데이터
  const [colors, setColors] = useState<ColorItem[]>([]);
  const [typography, setTypography] = useState<TypographyItem[]>([]);
  const [spacing, setSpacing] = useState<SpacingItem[]>([]);
  const [shadows, setShadows] = useState<ShadowItem[]>([]);

  // Components 데이터
  const [components, setComponents] = useState<ComponentItem[]>([]);

  // Tokens 데이터
  const [tokens, setTokens] = useState<TokenItem[]>([]);

  // Responsive 데이터
  const [breakpoints, setBreakpoints] = useState<ResponsiveBreakpoint[]>([]);

  // Dialog 상태
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [dialogMode, setDialogMode] = useState<"add" | "edit">("add");
  const [dialogType, setDialogType] = useState<"color" | "typography" | "spacing" | "shadow" | "component" | "token" | "breakpoint">("color");
  const [editingItem, setEditingItem] = useState<any>(null);

  // 컴포넌트 구조 편집 상태
  const [isEditingStructure, setIsEditingStructure] = useState(false);
  const [editingComponent, setEditingComponent] = useState<ComponentItem | null>(null);

  // localStorage에서 데이터 로드
  useEffect(() => {
    const loadData = () => {
      const savedColors = localStorage.getItem("SAM_DESIGN_COLORS");
      const savedTypography = localStorage.getItem("SAM_DESIGN_TYPOGRAPHY");
      const savedSpacing = localStorage.getItem("SAM_DESIGN_SPACING");
      const savedShadows = localStorage.getItem("SAM_DESIGN_SHADOWS");
      const savedComponents = localStorage.getItem("SAM_DESIGN_COMPONENTS");
      const savedTokens = localStorage.getItem("SAM_DESIGN_TOKENS");
      const savedBreakpoints = localStorage.getItem("SAM_DESIGN_BREAKPOINTS");

      setColors(savedColors ? JSON.parse(savedColors) : INITIAL_COLORS);
      setTypography(savedTypography ? JSON.parse(savedTypography) : INITIAL_TYPOGRAPHY);
      setSpacing(savedSpacing ? JSON.parse(savedSpacing) : INITIAL_SPACING);
      setShadows(savedShadows ? JSON.parse(savedShadows) : INITIAL_SHADOWS);
      setComponents(savedComponents ? JSON.parse(savedComponents) : INITIAL_COMPONENTS);
      setTokens(savedTokens ? JSON.parse(savedTokens) : INITIAL_TOKENS);
      setBreakpoints(savedBreakpoints ? JSON.parse(savedBreakpoints) : INITIAL_BREAKPOINTS);
    };

    loadData();
  }, []);

  // 데이터 저장
  const saveData = (type: string, data: any[]) => {
    localStorage.setItem(`SAM_DESIGN_${type.toUpperCase()}`, JSON.stringify(data));
  };

  // 추가 핸들러
  const handleAdd = (type: typeof dialogType) => {
    setDialogMode("add");
    setDialogType(type);
    setEditingItem(null);
    setIsDialogOpen(true);
  };

  // 수정 핸들러
  const handleEdit = (type: typeof dialogType, item: any) => {
    // 컴포넌트 편집인 경우 구조 편집 뷰로 전환
    if (type === "component") {
      setEditingComponent(item);
      setIsEditingStructure(true);
    } else {
      setDialogMode("edit");
      setDialogType(type);
      setEditingItem(item);
      setIsDialogOpen(true);
    }
  };

  // 삭제 핸들러
  const handleDelete = (type: typeof dialogType, id: string, skipConfirm: boolean = false) => {
    if (!skipConfirm && !confirm("정말 삭제하시겠습니까?")) return;

    switch (type) {
      case "color":
        const newColors = colors.filter((item) => item.id !== id);
        setColors(newColors);
        saveData("colors", newColors);
        break;
      case "typography":
        const newTypography = typography.filter((item) => item.id !== id);
        setTypography(newTypography);
        saveData("typography", newTypography);
        break;
      case "spacing":
        const newSpacing = spacing.filter((item) => item.id !== id);
        setSpacing(newSpacing);
        saveData("spacing", newSpacing);
        break;
      case "shadow":
        const newShadows = shadows.filter((item) => item.id !== id);
        setShadows(newShadows);
        saveData("shadows", newShadows);
        break;
      case "component":
        const newComponents = components.filter((item) => item.id !== id);
        setComponents(newComponents);
        saveData("components", newComponents);
        break;
      case "token":
        const newTokens = tokens.filter((item) => item.id !== id);
        setTokens(newTokens);
        saveData("tokens", newTokens);
        break;
      case "breakpoint":
        const newBreakpoints = breakpoints.filter((item) => item.id !== id);
        setBreakpoints(newBreakpoints);
        saveData("breakpoints", newBreakpoints);
        break;
    }

    if (!skipConfirm) {
      toast.success("삭제되었습니다");
    }
  };

  // 컴포넌트 구조 저장 핸들러
  const handleSaveComponentStructure = (updatedComponent: ComponentItem) => {
    const updatedComponents = components.map((comp) =>
      comp.id === updatedComponent.id ? updatedComponent : comp
    );
    setComponents(updatedComponents);
    saveData("components", updatedComponents);
    setIsEditingStructure(false);
    setEditingComponent(null);
    toast.success("컴포넌트 구조가 저장되었습니다");
  };

  // 컴포넌트 구조 편집 취소
  const handleCancelStructureEdit = () => {
    setIsEditingStructure(false);
    setEditingComponent(null);
  };

  // 미리보기 핸들러
  const handlePreview = (component: ComponentItem) => {
    setEditingComponent(component);
    setIsEditingStructure(true);
  };

  // Composition 업데이트 핸들러
  const handleUpdateComposition = (componentId: string, composition: CompositionItem[]) => {
    const updatedComponents = components.map((comp) =>
      comp.id === componentId ? { ...comp, composition } : comp
    );
    setComponents(updatedComponents);
    saveData("components", updatedComponents);
  };

  return (
    <PageLayout>
      <PageHeader
        title="디자인시스템 관리"
        description="Foundation, Components, Tokens, Responsive 관리"
        icon={Palette}
      />

      <Card>
        <CardContent className="pt-6">
          {/* 통합 검색창 */}
          <div className="mb-6">
            <div className="flex gap-2">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-muted-foreground" />
                <Input
                  placeholder="Foundation, Components, Tokens, Responsive 통합 검색..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-12 h-12 text-base"
                />
              </div>
              <Button
                variant="outline"
                onClick={() => {
                  localStorage.setItem("SAM_DESIGN_BREAKPOINTS", JSON.stringify(INITIAL_BREAKPOINTS));
                  setBreakpoints(INITIAL_BREAKPOINTS);
                  toast.success("브레이크포인트 데이터가 복구되었습니다");
                }}
              >
                데이터 복구
              </Button>
            </div>
            {searchTerm && (
              <p className="text-sm text-muted-foreground mt-2">
                검색어: <span className="font-medium">"{searchTerm}"</span>
              </p>
            )}
          </div>

          {searchTerm ? (
            <UnifiedSearchResults
              searchTerm={searchTerm}
              colors={colors}
              typography={typography}
              spacing={spacing}
              shadows={shadows}
              components={components}
              tokens={tokens}
              breakpoints={breakpoints}
              onEdit={handleEdit}
              onDelete={handleDelete}
              onViewComponent={(comp) => {
                setSelectedComponent(comp);
                setIsEditingStructure(true);
              }}
              onClearSearch={() => setSearchTerm("")}
            />
          ) : (
            <Tabs value={activeTab} onValueChange={(v: any) => setActiveTab(v)}>
              <TabsList className="grid w-full grid-cols-5">
                <TabsTrigger value="foundation">
                  <Palette className="h-4 w-4 mr-2" />
                  Foundation
                </TabsTrigger>
                <TabsTrigger value="components">
                  <Box className="h-4 w-4 mr-2" />
                  Components
                </TabsTrigger>
                <TabsTrigger value="modules">
                  <Package className="h-4 w-4 mr-2" />
                  Modules
                </TabsTrigger>
                <TabsTrigger value="tokens">
                  <Code className="h-4 w-4 mr-2" />
                  Tokens
                </TabsTrigger>
                <TabsTrigger value="responsive">
                  <Monitor className="h-4 w-4 mr-2" />
                  Responsive
                </TabsTrigger>
              </TabsList>

              {/* Foundation 탭 */}
              <TabsContent value="foundation" className="space-y-6 mt-6">
              <FoundationSection
                colors={colors}
                typography={typography}
                spacing={spacing}
                shadows={shadows}
                searchTerm={searchTerm}
                onAdd={handleAdd}
                onEdit={handleEdit}
                onDelete={handleDelete}
              />
            </TabsContent>

            {/* Components 탭 */}
            <TabsContent value="components" className="space-y-6 mt-6">
              {/* 아토믹 디자인 시스템 서브 탭 */}
              <Tabs defaultValue="atoms" className="w-full">
                <TabsList className="grid w-full grid-cols-4">
                  <TabsTrigger value="atoms">
                    <Box className="h-4 w-4 mr-2" />
                    Atoms
                  </TabsTrigger>
                  <TabsTrigger value="molecules">
                    <Layers className="h-4 w-4 mr-2" />
                    Molecules
                  </TabsTrigger>
                  <TabsTrigger value="organisms">
                    <Code className="h-4 w-4 mr-2" />
                    Organisms
                  </TabsTrigger>
                  <TabsTrigger value="templates">
                    <Monitor className="h-4 w-4 mr-2" />
                    Templates
                  </TabsTrigger>
                </TabsList>

                {/* Atoms 탭 */}
                <TabsContent value="atoms" className="mt-6">
                  <ComponentsSection
                    components={components.filter(c => c.category === "atoms")}
                    searchTerm={searchTerm}
                    onAdd={handleAdd}
                    onEdit={handleEdit}
                    onDelete={handleDelete}
                    onPreview={handlePreview}
                    categoryTitle="Atoms (원자)"
                    categoryDescription="가장 작은 단위의 UI 요소들"
                  />
                </TabsContent>

                {/* Molecules 탭 */}
                <TabsContent value="molecules" className="mt-6">
                  <ComponentsSection
                    components={components.filter(c => c.category === "molecules")}
                    searchTerm={searchTerm}
                    onAdd={handleAdd}
                    onEdit={handleEdit}
                    onDelete={handleDelete}
                    onPreview={handlePreview}
                    categoryTitle="Molecules (분자)"
                    categoryDescription="Atoms를 조합한 단순한 컴포넌트 그룹"
                  />
                </TabsContent>

                {/* Organisms 탭 */}
                <TabsContent value="organisms" className="mt-6">
                  <ComponentsSection
                    components={components.filter(c => c.category === "organisms")}
                    searchTerm={searchTerm}
                    onAdd={handleAdd}
                    onEdit={handleEdit}
                    onDelete={handleDelete}
                    onPreview={handlePreview}
                    categoryTitle="Organisms (유기체)"
                    categoryDescription="Molecules와 Atoms를 조합한 복잡한 UI 구성 요소"
                  />
                </TabsContent>

                {/* Templates 탭 */}
                <TabsContent value="templates" className="mt-6">
                  <ComponentsSection
                    components={components.filter(c => c.category === "templates")}
                    searchTerm={searchTerm}
                    onAdd={handleAdd}
                    onEdit={handleEdit}
                    onDelete={handleDelete}
                    onPreview={handlePreview}
                    categoryTitle="Templates (템플릿)"
                    categoryDescription="페이지 레이아웃과 구조를 정의하는 템플릿"
                  />
                </TabsContent>
              </Tabs>
            </TabsContent>

            {/* Modules 탭 */}
            <TabsContent value="modules" className="space-y-6 mt-6">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Package className="h-5 w-5" />
                    재사용 가능한 모듈
                  </CardTitle>
                  <CardDescription>
                    프로젝트에서 분리하여 관리하는 재사용 가능한 기능 모듈 컴포넌트
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  {/* QuoteNumberField 모듈 */}
                  <ModulePreviewCard />
                </CardContent>
              </Card>
            </TabsContent>

            {/* Tokens 탭 */}
            <TabsContent value="tokens" className="space-y-6 mt-6">
              <TokensSection
                tokens={tokens}
                searchTerm={searchTerm}
                onAdd={handleAdd}
                onEdit={handleEdit}
                onDelete={handleDelete}
              />
            </TabsContent>

              {/* Responsive 탭 */}
              <TabsContent value="responsive" className="space-y-6 mt-6">
                <ResponsiveSection
                  breakpoints={breakpoints}
                  searchTerm={searchTerm}
                  onAdd={handleAdd}
                  onEdit={handleEdit}
                  onDelete={handleDelete}
                />
              </TabsContent>
            </Tabs>
          )}
        </CardContent>
      </Card>

      {/* 컴포넌트 상세 미리보기 다이얼로그 */}
      <ComponentDetailDialog
        open={isEditingStructure}
        onOpenChange={setIsEditingStructure}
        component={editingComponent}
        availableComponents={components}
        onUpdateComposition={handleUpdateComposition}
      />

      {/* 편집 다이얼로그 */}
      <EditDialog
        open={isDialogOpen}
        onOpenChange={setIsDialogOpen}
        mode={dialogMode}
        type={dialogType}
        editingItem={editingItem}
        onSave={(data) => {
          if (dialogMode === "add") {
            // 추가
            const newItem = { ...data, id: `${dialogType}-${Date.now()}` };
            switch (dialogType) {
              case "color":
                const newColors = [...colors, newItem];
                setColors(newColors);
                saveData("colors", newColors);
                break;
              case "typography":
                const newTypography = [...typography, newItem];
                setTypography(newTypography);
                saveData("typography", newTypography);
                break;
              case "spacing":
                const newSpacing = [...spacing, newItem];
                setSpacing(newSpacing);
                saveData("spacing", newSpacing);
                break;
              case "shadow":
                const newShadows = [...shadows, newItem];
                setShadows(newShadows);
                saveData("shadows", newShadows);
                break;
              case "component":
                const newComponents = [...components, newItem];
                setComponents(newComponents);
                saveData("components", newComponents);
                break;
              case "token":
                const newTokens = [...tokens, newItem];
                setTokens(newTokens);
                saveData("tokens", newTokens);
                break;
              case "breakpoint":
                const newBreakpoints = [...breakpoints, newItem];
                setBreakpoints(newBreakpoints);
                saveData("breakpoints", newBreakpoints);
                break;
            }
            toast.success("추가되었습니다");
          } else {
            // 수정
            switch (dialogType) {
              case "color":
                const updatedColors = colors.map((item) => (item.id === data.id ? data : item));
                setColors(updatedColors);
                saveData("colors", updatedColors);
                break;
              case "typography":
                const updatedTypography = typography.map((item) => (item.id === data.id ? data : item));
                setTypography(updatedTypography);
                saveData("typography", updatedTypography);
                break;
              case "spacing":
                const updatedSpacing = spacing.map((item) => (item.id === data.id ? data : item));
                setSpacing(updatedSpacing);
                saveData("spacing", updatedSpacing);
                break;
              case "shadow":
                const updatedShadows = shadows.map((item) => (item.id === data.id ? data : item));
                setShadows(updatedShadows);
                saveData("shadows", updatedShadows);
                break;
              case "component":
                const updatedComponents = components.map((item) => (item.id === data.id ? data : item));
                setComponents(updatedComponents);
                saveData("components", updatedComponents);
                break;
              case "token":
                const updatedTokens = tokens.map((item) => (item.id === data.id ? data : item));
                setTokens(updatedTokens);
                saveData("tokens", updatedTokens);
                break;
              case "breakpoint":
                const updatedBreakpoints = breakpoints.map((item) => (item.id === data.id ? data : item));
                setBreakpoints(updatedBreakpoints);
                saveData("breakpoints", updatedBreakpoints);
                break;
            }
            toast.success("수정되었습니다");
          }
          setIsDialogOpen(false);
        }}
      />
    </PageLayout>
  );
}

// ============= ComponentPreview =============

function ComponentPreview({ componentPath, componentName }: { componentPath: string; componentName: string }) {
  // COMPONENT_MAP에서 직접 가져오기
  const PreviewComponent = COMPONENT_MAP[componentName];

  if (!PreviewComponent) {
    return <p className="text-xs text-muted-foreground">미리보기 없음</p>;
  }

  // Atoms 컴포넌트에 따라 적절한 props 전달
  try {
    if (componentName === "Button") {
      return <PreviewComponent size="sm">샘플</PreviewComponent>;
    } else if (componentName === "Input") {
      return <PreviewComponent placeholder="샘플 입력" className="max-w-[200px]" />;
    } else if (componentName === "Badge") {
      return <PreviewComponent>뱃지</PreviewComponent>;
    } else if (componentName === "Card") {
      return (
        <PreviewComponent className="w-full">
          <CardHeader>
            <CardTitle className="text-sm">카드 제목</CardTitle>
          </CardHeader>
          <CardContent className="text-xs">카드 내용</CardContent>
        </PreviewComponent>
      );
    } else if (componentName === "Alert") {
      return <PreviewComponent className="text-xs"><div>알림 메시지</div></PreviewComponent>;
    } else if (componentName === "Label") {
      return <PreviewComponent>레이블</PreviewComponent>;
    } else if (componentName === "Textarea") {
      return <PreviewComponent placeholder="텍스트 영역" className="max-w-[200px] h-16" />;
    } else if (componentName === "Checkbox") {
      return <div className="flex items-center gap-2"><PreviewComponent /><span className="text-xs">체크박스</span></div>;
    } else if (componentName === "Switch") {
      return <div className="flex items-center gap-2"><PreviewComponent /><span className="text-xs">스위치</span></div>;
    } else if (componentName === "Slider") {
      return <PreviewComponent defaultValue={[50]} max={100} className="max-w-[200px]" />;
    } else if (componentName === "Progress") {
      return <PreviewComponent value={60} className="max-w-[200px]" />;
    } else if (componentName === "Separator") {
      return <PreviewComponent className="my-2" />;
    } else if (componentName === "Skeleton") {
      return <Skeleton className="w-[200px] h-8" />;
    } else {
      // 기본 렌더링
      return <div className="text-xs text-muted-foreground">복합 컴포넌트</div>;
    }
  } catch (err) {
    return <p className="text-xs text-red-500">렌더링 오류</p>;
  }
}

// ============= Foundation 섹션 =============

interface FoundationSectionProps {
  colors: ColorItem[];
  typography: TypographyItem[];
  spacing: SpacingItem[];
  shadows: ShadowItem[];
  searchTerm: string;
  onAdd: (type: any) => void;
  onEdit: (type: any, item: any) => void;
  onDelete: (type: any, id: string, skipConfirm?: boolean) => void;
}

function FoundationSection({ colors, typography, spacing, shadows, searchTerm, onAdd, onEdit, onDelete }: FoundationSectionProps) {
  // 검색 필터링
  const filteredColors = colors.filter(
    (item) =>
      item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.value.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.description?.toLowerCase().includes(searchTerm.toLowerCase())
  );
  const filteredTypography = typography.filter(
    (item) =>
      item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.usage.toLowerCase().includes(searchTerm.toLowerCase())
  );
  const filteredSpacing = spacing.filter(
    (item) =>
      item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.usage.toLowerCase().includes(searchTerm.toLowerCase())
  );
  const filteredShadows = shadows.filter(
    (item) =>
      item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.usage.toLowerCase().includes(searchTerm.toLowerCase())
  );
  return (
    <div className="space-y-8">
      {/* 색상 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Palette className="h-5 w-5" />
              색상 (Colors)
            </CardTitle>
            <Button onClick={() => onAdd("color")} size="sm">
              <Plus className="h-4 w-4 mr-2" />
              추가
            </Button>
          </div>
          <CardDescription>브랜드 색상 및 시맨틱 색상</CardDescription>
        </CardHeader>
        <CardContent>
          {filteredColors.length === 0 ? (
            <p className="text-center text-muted-foreground py-8">검색 결과가 없습니다.</p>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {filteredColors.map((color) => (
                <div key={color.id} className="border rounded-lg p-4 space-y-3">
                  <div
                    className="h-20 rounded-md border"
                    style={{ backgroundColor: color.value }}
                  />
                  <div className="space-y-1">
                    <div className="flex items-center justify-between">
                      <span className="font-medium">{color.name}</span>
                      <Badge variant="outline">{color.category}</Badge>
                    </div>
                    <p className="text-sm text-muted-foreground font-mono">{color.value}</p>
                    {color.description && (
                      <p className="text-xs text-muted-foreground">{color.description}</p>
                    )}
                  </div>
                  <div className="flex gap-2">
                    <Button variant="ghost" size="sm" onClick={() => onEdit("color", color)}>
                      <Edit className="h-3 w-3" />
                    </Button>
                    <Button variant="ghost" size="sm" onClick={() => onDelete("color", color.id)}>
                      <Trash2 className="h-3 w-3" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 타이포그래피 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Type className="h-5 w-5" />
              타이포그래피 (Typography)
            </CardTitle>
            <Button onClick={() => onAdd("typography")} size="sm">
              <Plus className="h-4 w-4 mr-2" />
              추가
            </Button>
          </div>
          <CardDescription>폰트 크기, 굵기, 행간</CardDescription>
        </CardHeader>
        <CardContent>
          {filteredTypography.length === 0 ? (
            <p className="text-center text-muted-foreground py-8">검색 결과가 없습니다.</p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>이름</TableHead>
                  <TableHead>크기</TableHead>
                  <TableHead>굵기</TableHead>
                  <TableHead>행간</TableHead>
                  <TableHead>용도</TableHead>
                  <TableHead className="text-right">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredTypography.map((typo) => (
                  <TableRow key={typo.id}>
                    <TableCell className="font-medium">{typo.name}</TableCell>
                    <TableCell className="font-mono">{typo.fontSize}</TableCell>
                    <TableCell>{typo.fontWeight}</TableCell>
                    <TableCell className="font-mono">{typo.lineHeight}</TableCell>
                    <TableCell className="text-sm text-muted-foreground">{typo.usage}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button variant="ghost" size="sm" onClick={() => onEdit("typography", typo)}>
                          <Edit className="h-3 w-3" />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => onDelete("typography", typo.id)}>
                          <Trash2 className="h-3 w-3" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* 간격 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Ruler className="h-5 w-5" />
              간격 (Spacing)
            </CardTitle>
            <Button onClick={() => onAdd("spacing")} size="sm">
              <Plus className="h-4 w-4 mr-2" />
              추가
            </Button>
          </div>
          <CardDescription>마진, 패딩 등 간격 시스템</CardDescription>
        </CardHeader>
        <CardContent>
          {filteredSpacing.length === 0 ? (
            <p className="text-center text-muted-foreground py-8">검색 결과가 없습니다.</p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>이름</TableHead>
                  <TableHead>값 (rem)</TableHead>
                  <TableHead>픽셀</TableHead>
                  <TableHead>용도</TableHead>
                  <TableHead className="text-right">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredSpacing.map((space) => (
                  <TableRow key={space.id}>
                    <TableCell className="font-medium">{space.name}</TableCell>
                    <TableCell className="font-mono">{space.value}</TableCell>
                    <TableCell className="font-mono">{space.pixels}</TableCell>
                    <TableCell className="text-sm text-muted-foreground">{space.usage}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button variant="ghost" size="sm" onClick={() => onEdit("spacing", space)}>
                          <Edit className="h-3 w-3" />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => onDelete("spacing", space.id)}>
                          <Trash2 className="h-3 w-3" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* 그림자 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <ImageIcon className="h-5 w-5" />
              그림자 (Shadow)
            </CardTitle>
            <Button onClick={() => onAdd("shadow")} size="sm">
              <Plus className="h-4 w-4 mr-2" />
              추가
            </Button>
          </div>
          <CardDescription>박스 그림자 효과</CardDescription>
        </CardHeader>
        <CardContent>
          {filteredShadows.length === 0 ? (
            <p className="text-center text-muted-foreground py-8">검색 결과가 없습니다.</p>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {filteredShadows.map((shadow) => (
              <div key={shadow.id} className="border rounded-lg p-4 space-y-3">
                <div
                  className="h-20 bg-white rounded-md"
                  style={{ boxShadow: shadow.value }}
                />
                <div className="space-y-1">
                  <span className="font-medium">{shadow.name}</span>
                  <p className="text-xs text-muted-foreground font-mono">{shadow.value}</p>
                  <p className="text-xs text-muted-foreground">{shadow.usage}</p>
                </div>
                <div className="flex gap-2">
                  <Button variant="ghost" size="sm" onClick={() => onEdit("shadow", shadow)}>
                    <Edit className="h-3 w-3" />
                  </Button>
                  <Button variant="ghost" size="sm" onClick={() => onDelete("shadow", shadow.id)}>
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

// ============= Components 섹션 =============

interface ComponentsSectionProps {
  components: ComponentItem[];
  searchTerm: string;
  onAdd: (type: any) => void;
  onEdit: (type: any, item: any) => void;
  onDelete: (type: any, id: string, skipConfirm?: boolean) => void;
  onPreview?: (component: ComponentItem) => void;
  categoryTitle?: string;
  categoryDescription?: string;
}

function ComponentsSection({ components, searchTerm, onAdd, onEdit, onDelete, onPreview, categoryTitle, categoryDescription }: ComponentsSectionProps) {
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  
  const filteredComponents = components.filter(
    (comp) =>
      comp.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      comp.displayName.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const isAllSelected = filteredComponents.length > 0 && selectedIds.length === filteredComponents.length;
  const isSomeSelected = selectedIds.length > 0 && selectedIds.length < filteredComponents.length;

  const handleSelectAll = () => {
    if (isAllSelected) {
      setSelectedIds([]);
    } else {
      setSelectedIds(filteredComponents.map(comp => comp.id));
    }
  };

  const handleSelectOne = (id: string) => {
    setSelectedIds(prev => 
      prev.includes(id) 
        ? prev.filter(selectedId => selectedId !== id)
        : [...prev, id]
    );
  };

  const handleDeleteSelected = () => {
    if (selectedIds.length === 0) return;
    setIsDeleteDialogOpen(true);
  };

  const confirmDeleteSelected = () => {
    selectedIds.forEach(id => {
      onDelete("component", id, true);
    });
    toast.success(`${selectedIds.length}개의 컴포넌트가 삭제되었습니다.`);
    setSelectedIds([]);
    setIsDeleteDialogOpen(false);
  };

  return (
    <div className="space-y-4">
      {/* 카테고리 헤더 */}
      {categoryTitle && (
        <div className="mb-4">
          <h3 className="text-lg font-semibold">{categoryTitle}</h3>
          {categoryDescription && (
            <p className="text-sm text-muted-foreground mt-1">{categoryDescription}</p>
          )}
        </div>
      )}

      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-2">
          <div className="flex items-center gap-2 border rounded-md px-3 py-2">
            <input
              type="checkbox"
              checked={isAllSelected}
              ref={(input) => {
                if (input) {
                  input.indeterminate = isSomeSelected;
                }
              }}
              onChange={handleSelectAll}
              className="h-4 w-4 rounded border-gray-300 cursor-pointer"
            />
            <Label className="text-sm cursor-pointer" onClick={handleSelectAll}>
              전체 선택
            </Label>
          </div>
          
          {selectedIds.length > 0 && (
            <Button variant="destructive" size="sm" onClick={handleDeleteSelected}>
              <Trash2 className="h-4 w-4 mr-2" />
              선택 삭제 ({selectedIds.length})
            </Button>
          )}
        </div>
        
        <Button onClick={() => onAdd("component")}>
          <Plus className="h-4 w-4 mr-2" />
          컴포넌트 추가
        </Button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {filteredComponents.map((comp) => (
          <Card key={comp.id} className={selectedIds.includes(comp.id) ? "ring-2 ring-primary" : ""}>
            <CardHeader>
              <div className="flex items-start justify-between">
                <div className="flex items-start gap-2 flex-1">
                  <input
                    type="checkbox"
                    checked={selectedIds.includes(comp.id)}
                    onChange={() => handleSelectOne(comp.id)}
                    className="h-4 w-4 rounded border-gray-300 mt-1 cursor-pointer"
                  />
                  <div>
                    <CardTitle className="text-lg">{comp.displayName}</CardTitle>
                    <CardDescription className="font-mono text-xs mt-1">{comp.name}</CardDescription>
                  </div>
                </div>
                <Badge variant={comp.status === "stable" ? "default" : comp.status === "beta" ? "secondary" : "destructive"}>
                  {comp.status}
                </Badge>
              </div>
            </CardHeader>
            <CardContent className="space-y-3">
              <p className="text-sm text-muted-foreground">{comp.description}</p>
              <div className="flex flex-wrap gap-2">
                <Badge variant="outline">{comp.category}</Badge>
                {comp.responsive && <Badge variant="outline">반응형</Badge>}
              </div>
              <p className="text-xs text-muted-foreground font-mono">{comp.path}</p>
              
              {/* UI 미리보기 */}
              <div className="space-y-2">
                <Label className="text-xs font-semibold">UI 미리보기</Label>
                <div className="p-4 bg-white border-2 border-dashed border-gray-300 rounded-lg min-h-[100px] flex items-center justify-center">
                  <ComponentPreview componentPath={comp.path} componentName={comp.name} />
                </div>
              </div>
              
              {/* 미리보기: 컴포넌트 구조 */}
              {comp.composition && comp.composition.length > 0 && (
                <div className="space-y-2">
                  <Label className="text-xs font-semibold">컴포넌트 구조</Label>
                  <div className="p-3 bg-muted rounded-lg space-y-1">
                    {comp.composition
                      .sort((a, b) => a.order - b.order)
                      .map((item, idx) => (
                        <div key={item.id} className="flex items-center gap-2 text-xs">
                          <Badge variant="secondary" className="text-xs px-1.5 py-0">
                            {idx + 1}
                          </Badge>
                          <span className="font-mono">{item.componentDisplayName}</span>
                          <Badge variant="outline" className="text-xs px-1.5 py-0">
                            {item.componentCategory}
                          </Badge>
                        </div>
                      ))}
                  </div>
                </div>
              )}
              
              <div className="flex gap-2 flex-wrap">

                <Button variant="outline" size="sm" onClick={() => onEdit("component", comp)}>
                  <Edit className="h-3 w-3 mr-1" />
                  수정
                </Button>
                <Button variant="ghost" size="sm" onClick={() => onDelete("component", comp.id)}>
                  <Trash2 className="h-3 w-3 mr-1" />
                  삭제
                </Button>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 삭제 확인 다이얼로그 */}
      <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>컴포넌트 삭제 확인</DialogTitle>
            <DialogDescription>
              선택한 {selectedIds.length}개의 컴포넌트를 삭제하시겠습니까?
              <br />
              이 작업은 되돌릴 수 없습니다.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsDeleteDialogOpen(false)}>
              취소
            </Button>
            <Button variant="destructive" onClick={confirmDeleteSelected}>
              삭제
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

// ============= Tokens 섹션 =============

interface TokensSectionProps {
  tokens: TokenItem[];
  searchTerm: string;
  onAdd: (type: any) => void;
  onEdit: (type: any, item: any) => void;
  onDelete: (type: any, id: string, skipConfirm?: boolean) => void;
}

function TokensSection({ tokens, searchTerm, onAdd, onEdit, onDelete }: TokensSectionProps) {
  const filteredTokens = tokens.filter(
    (token) =>
      token.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      token.description.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-end gap-4">
        <Button onClick={() => onAdd("token")}>
          <Plus className="h-4 w-4 mr-2" />
          토큰 추가
        </Button>
      </div>

      {filteredTokens.length === 0 ? (
        <p className="text-center text-muted-foreground py-8">검색 결과가 없습니다.</p>
      ) : (
        <Table>
        <TableHeader>
          <TableRow>
            <TableHead>토큰명</TableHead>
            <TableHead>값</TableHead>
            <TableHead>카테고리</TableHead>
            <TableHead>설명</TableHead>
            <TableHead className="text-right">작업</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {filteredTokens.map((token) => (
            <TableRow key={token.id}>
              <TableCell className="font-mono">{token.name}</TableCell>
              <TableCell className="font-mono text-sm">{token.value}</TableCell>
              <TableCell>
                <Badge variant="outline">{token.category}</Badge>
              </TableCell>
              <TableCell className="text-sm text-muted-foreground">{token.description}</TableCell>
              <TableCell className="text-right">
                <div className="flex justify-end gap-2">
                  <Button variant="ghost" size="sm" onClick={() => onEdit("token", token)}>
                    <Edit className="h-3 w-3" />
                  </Button>
                  <Button variant="ghost" size="sm" onClick={() => onDelete("token", token.id)}>
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
        </Table>
      )}
    </div>
  );
}

// ============= Responsive 섹션 =============

interface ResponsiveSectionProps {
  breakpoints: ResponsiveBreakpoint[];
  searchTerm: string;
  onAdd: (type: any) => void;
  onEdit: (type: any, item: any) => void;
  onDelete: (type: any, id: string, skipConfirm?: boolean) => void;
}

function ResponsiveSection({ breakpoints, searchTerm, onAdd, onEdit, onDelete }: ResponsiveSectionProps) {
  const filteredBreakpoints = breakpoints.filter(
    (bp) =>
      bp.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      bp.description.toLowerCase().includes(searchTerm.toLowerCase())
  );
  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="font-semibold">브레이크포인트 (Breakpoints)</h3>
        <Button onClick={() => onAdd("breakpoint")}>
          <Plus className="h-4 w-4 mr-2" />
          브레이크포인트 추가
        </Button>
      </div>

      {filteredBreakpoints.length === 0 ? (
        <p className="text-center text-muted-foreground py-8">검색 결과가 없습니다.</p>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {filteredBreakpoints.map((bp) => (
          <Card key={bp.id}>
            <CardHeader>
              <div className="flex items-start justify-between">
                <CardTitle className="text-lg flex items-center gap-2">
                  {bp.name === "Mobile" && <Smartphone className="h-5 w-5" />}
                  {bp.name === "Tablet" && <TabletIcon className="h-5 w-5" />}
                  {bp.name === "Desktop" && <Monitor className="h-5 w-5" />}
                  {bp.name}
                </CardTitle>
              </div>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="space-y-1">
                <p className="text-sm text-muted-foreground">최소 너비: {bp.minWidth}</p>
                {bp.maxWidth && <p className="text-sm text-muted-foreground">최대 너비: {bp.maxWidth}</p>}
              </div>
              <p className="text-sm">{bp.description}</p>
              <div className="flex gap-2">
                <Button variant="outline" size="sm" onClick={() => onEdit("breakpoint", bp)}>
                  <Edit className="h-3 w-3 mr-1" />
                  수정
                </Button>
                <Button variant="ghost" size="sm" onClick={() => onDelete("breakpoint", bp.id)}>
                  <Trash2 className="h-3 w-3 mr-1" />
                  삭제
                </Button>
              </div>
            </CardContent>
          </Card>
          ))}
        </div>
      )}
    </div>
  );
}

// ============= 편집 다이얼로그 =============

interface EditDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  mode: "add" | "edit";
  type: "color" | "typography" | "spacing" | "shadow" | "component" | "token" | "breakpoint";
  editingItem: any;
  onSave: (data: any) => void;
}

function EditDialog({ open, onOpenChange, mode, type, editingItem, onSave }: EditDialogProps) {
  const [formData, setFormData] = useState<any>({});

  useEffect(() => {
    if (editingItem) {
      setFormData(editingItem);
    } else {
      // 초기화
      setFormData({});
    }
  }, [editingItem, open]);

  const handleSave = () => {
    // 유효성 검사
    if (type === "color" && (!formData.name || !formData.value)) {
      toast.error("이름과 색상 값을 입력해주세요");
      return;
    }

    onSave(formData);
  };

  const getDialogTitle = () => {
    const typeNames = {
      color: "색상",
      typography: "타이포그래피",
      spacing: "간격",
      shadow: "그림자",
      component: "컴포넌트",
      token: "토큰",
      breakpoint: "브레이크포인트",
    };
    return `${typeNames[type]} ${mode === "add" ? "추가" : "수정"}`;
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{getDialogTitle()}</DialogTitle>
          <DialogDescription>
            {mode === "add" ? "새로운 항목을 추��합니다" : "항목을 수정합니다"}
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-4 py-4">
          {/* Color Form */}
          {type === "color" && (
            <>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">이름 *</Label>
                <Input
                  id="name"
                  className="col-span-3"
                  value={formData.name || ""}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="예: Primary"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="value" className="text-right">색상 값 *</Label>
                <Input
                  id="value"
                  type="color"
                  className="col-span-3"
                  value={formData.value || "#000000"}
                  onChange={(e) => setFormData({ ...formData, value: e.target.value })}
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="category" className="text-right">카테고리</Label>
                <Select
                  value={formData.category || "primary"}
                  onValueChange={(value) => setFormData({ ...formData, category: value })}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="primary">Primary</SelectItem>
                    <SelectItem value="secondary">Secondary</SelectItem>
                    <SelectItem value="neutral">Neutral</SelectItem>
                    <SelectItem value="semantic">Semantic</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="description" className="text-right">설명</Label>
                <Input
                  id="description"
                  className="col-span-3"
                  value={formData.description || ""}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="색상에 대한 설명"
                />
              </div>
            </>
          )}

          {/* Typography Form */}
          {type === "typography" && (
            <>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">이름 *</Label>
                <Input
                  id="name"
                  className="col-span-3"
                  value={formData.name || ""}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="예: Heading-1"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="fontSize" className="text-right">폰트 크기 *</Label>
                <Input
                  id="fontSize"
                  className="col-span-3"
                  value={formData.fontSize || ""}
                  onChange={(e) => setFormData({ ...formData, fontSize: e.target.value })}
                  placeholder="예: 2rem"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="fontWeight" className="text-right">폰트 굵기 *</Label>
                <Input
                  id="fontWeight"
                  className="col-span-3"
                  value={formData.fontWeight || ""}
                  onChange={(e) => setFormData({ ...formData, fontWeight: e.target.value })}
                  placeholder="예: 700"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="lineHeight" className="text-right">행간 *</Label>
                <Input
                  id="lineHeight"
                  className="col-span-3"
                  value={formData.lineHeight || ""}
                  onChange={(e) => setFormData({ ...formData, lineHeight: e.target.value })}
                  placeholder="예: 2.5rem"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="usage" className="text-right">용도</Label>
                <Input
                  id="usage"
                  className="col-span-3"
                  value={formData.usage || ""}
                  onChange={(e) => setFormData({ ...formData, usage: e.target.value })}
                  placeholder="사용 용도"
                />
              </div>
            </>
          )}

          {/* Spacing Form */}
          {type === "spacing" && (
            <>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">이름 *</Label>
                <Input
                  id="name"
                  className="col-span-3"
                  value={formData.name || ""}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="예: md"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="value" className="text-right">값 (rem) *</Label>
                <Input
                  id="value"
                  className="col-span-3"
                  value={formData.value || ""}
                  onChange={(e) => setFormData({ ...formData, value: e.target.value })}
                  placeholder="예: 1rem"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="pixels" className="text-right">픽셀 *</Label>
                <Input
                  id="pixels"
                  className="col-span-3"
                  value={formData.pixels || ""}
                  onChange={(e) => setFormData({ ...formData, pixels: e.target.value })}
                  placeholder="예: 16px"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="usage" className="text-right">용도</Label>
                <Input
                  id="usage"
                  className="col-span-3"
                  value={formData.usage || ""}
                  onChange={(e) => setFormData({ ...formData, usage: e.target.value })}
                  placeholder="사용 용도"
                />
              </div>
            </>
          )}

          {/* Shadow Form */}
          {type === "shadow" && (
            <>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">이름 *</Label>
                <Input
                  id="name"
                  className="col-span-3"
                  value={formData.name || ""}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="예: md"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="value" className="text-right">그림자 값 *</Label>
                <Textarea
                  id="value"
                  className="col-span-3"
                  value={formData.value || ""}
                  onChange={(e) => setFormData({ ...formData, value: e.target.value })}
                  placeholder="예: 0 4px 6px -1px rgba(0, 0, 0, 0.1)"
                  rows={2}
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="usage" className="text-right">용도</Label>
                <Input
                  id="usage"
                  className="col-span-3"
                  value={formData.usage || ""}
                  onChange={(e) => setFormData({ ...formData, usage: e.target.value })}
                  placeholder="사용 용도"
                />
              </div>
            </>
          )}

          {/* Component Form */}
          {type === "component" && (
            <>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">컴포넌트명 *</Label>
                <Input
                  id="name"
                  className="col-span-3"
                  value={formData.name || ""}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="예: Button"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="displayName" className="text-right">표시명 *</Label>
                <Input
                  id="displayName"
                  className="col-span-3"
                  value={formData.displayName || ""}
                  onChange={(e) => setFormData({ ...formData, displayName: e.target.value })}
                  placeholder="예: 버튼"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="category" className="text-right">카테고리 *</Label>
                <Select
                  value={formData.category || "atoms"}
                  onValueChange={(value) => setFormData({ ...formData, category: value })}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="atoms">Atoms</SelectItem>
                    <SelectItem value="molecules">Molecules</SelectItem>
                    <SelectItem value="organisms">Organisms</SelectItem>
                    <SelectItem value="templates">Templates</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="path" className="text-right">경로 *</Label>
                <Input
                  id="path"
                  className="col-span-3"
                  value={formData.path || ""}
                  onChange={(e) => setFormData({ ...formData, path: e.target.value })}
                  placeholder="예: /components/ui/button.tsx"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="description" className="text-right">설명</Label>
                <Textarea
                  id="description"
                  className="col-span-3"
                  value={formData.description || ""}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="컴포넌트 설명"
                  rows={2}
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="status" className="text-right">상태</Label>
                <Select
                  value={formData.status || "stable"}
                  onValueChange={(value) => setFormData({ ...formData, status: value })}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="stable">Stable</SelectItem>
                    <SelectItem value="beta">Beta</SelectItem>
                    <SelectItem value="deprecated">Deprecated</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">반응형</Label>
                <div className="col-span-3 flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={formData.responsive || false}
                    onChange={(e) => setFormData({ ...formData, responsive: e.target.checked })}
                    className="h-4 w-4"
                  />
                  <span className="text-sm text-muted-foreground">반응형 컴포넌트</span>
                </div>
              </div>
            </>
          )}

          {/* Token Form */}
          {type === "token" && (
            <>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">토큰명 *</Label>
                <Input
                  id="name"
                  className="col-span-3"
                  value={formData.name || ""}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="예: --primary-color"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="value" className="text-right">값 *</Label>
                <Input
                  id="value"
                  className="col-span-3"
                  value={formData.value || ""}
                  onChange={(e) => setFormData({ ...formData, value: e.target.value })}
                  placeholder="예: #3B82F6"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="category" className="text-right">카테고리</Label>
                <Select
                  value={formData.category || "color"}
                  onValueChange={(value) => setFormData({ ...formData, category: value })}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="color">Color</SelectItem>
                    <SelectItem value="typography">Typography</SelectItem>
                    <SelectItem value="spacing">Spacing</SelectItem>
                    <SelectItem value="border">Border</SelectItem>
                    <SelectItem value="shadow">Shadow</SelectItem>
                    <SelectItem value="animation">Animation</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="description" className="text-right">설명</Label>
                <Input
                  id="description"
                  className="col-span-3"
                  value={formData.description || ""}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="토큰 설명"
                />
              </div>
            </>
          )}

          {/* Breakpoint Form */}
          {type === "breakpoint" && (
            <>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">이름 *</Label>
                <Input
                  id="name"
                  className="col-span-3"
                  value={formData.name || ""}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="예: Mobile"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="minWidth" className="text-right">최소 너비 *</Label>
                <Input
                  id="minWidth"
                  className="col-span-3"
                  value={formData.minWidth || ""}
                  onChange={(e) => setFormData({ ...formData, minWidth: e.target.value })}
                  placeholder="예: 0px"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="maxWidth" className="text-right">최대 너비</Label>
                <Input
                  id="maxWidth"
                  className="col-span-3"
                  value={formData.maxWidth || ""}
                  onChange={(e) => setFormData({ ...formData, maxWidth: e.target.value })}
                  placeholder="예: 767px (선택사항)"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="description" className="text-right">설명</Label>
                <Input
                  id="description"
                  className="col-span-3"
                  value={formData.description || ""}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="브레이크포인트 설명"
                />
              </div>
            </>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button onClick={handleSave}>
            {mode === "add" ? "추가" : "수정"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ============= 컴포넌트 구조 편집기 =============

interface ComponentStructureEditorProps {
  component: ComponentItem;
  allComponents: ComponentItem[];
  onSave: (component: ComponentItem) => void;
  onCancel: () => void;
}

function ComponentStructureEditor({ component, allComponents, onSave, onCancel }: ComponentStructureEditorProps) {
  const [editedComponent, setEditedComponent] = useState<ComponentItem>({
    ...component,
    composition: component.composition || []
  });
  const [isAddingComposition, setIsAddingComposition] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");

  // Atoms와 Molecules만 선택 가능 (자기보다 낮은 레벨)
  const availableComponents = allComponents.filter((comp) => {
    if (component.category === "templates") {
      return comp.category === "atoms" || comp.category === "molecules" || comp.category === "organisms";
    } else if (component.category === "organisms") {
      return comp.category === "atoms" || comp.category === "molecules";
    } else if (component.category === "molecules") {
      return comp.category === "atoms";
    }
    return false;
  }).filter((comp) =>
    comp.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    comp.displayName.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleAddComposition = (selectedComponent: ComponentItem) => {
    const newComposition: CompositionItem = {
      id: Date.now().toString(),
      componentId: selectedComponent.id,
      componentName: selectedComponent.name,
      componentDisplayName: selectedComponent.displayName,
      componentCategory: selectedComponent.category as "atoms" | "molecules" | "organisms",
      props: {},
      order: (editedComponent.composition || []).length
    };

    setEditedComponent({
      ...editedComponent,
      composition: [...(editedComponent.composition || []), newComposition]
    });
    setIsAddingComposition(false);
    setSearchTerm("");
  };

  const handleRemoveComposition = (compositionId: string) => {
    setEditedComponent({
      ...editedComponent,
      composition: (editedComponent.composition || []).filter(c => c.id !== compositionId)
    });
  };

  const handleMoveComposition = (compositionId: string, direction: "up" | "down") => {
    const composition = editedComponent.composition || [];
    const index = composition.findIndex(c => c.id === compositionId);
    
    if (
      (direction === "up" && index > 0) ||
      (direction === "down" && index < composition.length - 1)
    ) {
      const newComposition = [...composition];
      const targetIndex = direction === "up" ? index - 1 : index + 1;
      [newComposition[index], newComposition[targetIndex]] = [newComposition[targetIndex], newComposition[index]];
      
      // order 업데이트
      newComposition.forEach((item, idx) => {
        item.order = idx;
      });

      setEditedComponent({
        ...editedComponent,
        composition: newComposition
      });
    }
  };

  const handleSave = () => {
    onSave(editedComponent);
  };

  return (
    <PageLayout>
      <PageHeader
        title={`컴포넌트 구조 편집: ${component.displayName}`}
        description={`${component.name} 컴포넌트의 구성 요소를 관리합니다`}
        icon={Layers}
      />

      <div className="space-y-6">
        {/* 컴포넌트 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle>기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label className="text-sm text-muted-foreground">컴포넌트명</Label>
                <p className="font-medium">{component.name}</p>
              </div>
              <div>
                <Label className="text-sm text-muted-foreground">표시명</Label>
                <p className="font-medium">{component.displayName}</p>
              </div>
              <div>
                <Label className="text-sm text-muted-foreground">카테고리</Label>
                <Badge>{component.category}</Badge>
              </div>
              <div>
                <Label className="text-sm text-muted-foreground">상태</Label>
                <Badge variant={component.status === "stable" ? "default" : component.status === "beta" ? "secondary" : "destructive"}>
                  {component.status}
                </Badge>
              </div>
            </div>
            <div>
              <Label className="text-sm text-muted-foreground">설명</Label>
              <p className="text-sm">{component.description}</p>
            </div>
          </CardContent>
        </Card>

        {/* 구성 요소 관리 */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle>구성 요소</CardTitle>
                <CardDescription>
                  이 컴포넌트를 구성하는 하위 요소들을 관리합니다
                </CardDescription>
              </div>
              <Button onClick={() => setIsAddingComposition(true)}>
                <Plus className="h-4 w-4 mr-2" />
                구성 요소 추가
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {(!editedComponent.composition || editedComponent.composition.length === 0) ? (
              <div className="text-center py-12 text-muted-foreground">
                <Layers className="h-12 w-12 mx-auto mb-4 opacity-20" />
                <p>구성 요소가 없습니다</p>
                <p className="text-sm">버튼을 클릭하여 구성 요소를 추가하세요</p>
              </div>
            ) : (
              <div className="space-y-2">
                {editedComponent.composition.map((comp, index) => (
                  <div
                    key={comp.id}
                    className="flex items-center gap-4 p-4 border rounded-lg bg-card hover:bg-accent/50 transition-colors"
                  >
                    <div className="flex flex-col gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleMoveComposition(comp.id, "up")}
                        disabled={index === 0}
                        className="h-6 w-6 p-0"
                      >
                        <ChevronUp className="h-3 w-3" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleMoveComposition(comp.id, "down")}
                        disabled={index === (editedComponent.composition || []).length - 1}
                        className="h-6 w-6 p-0"
                      >
                        <ChevronDown className="h-3 w-3" />
                      </Button>
                    </div>
                    
                    <div className="flex-1">
                      <div className="flex items-center gap-2">
                        <span className="font-medium">{comp.componentDisplayName}</span>
                        <Badge variant="outline" className="text-xs">
                          {comp.componentCategory}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground font-mono">{comp.componentName}</p>
                    </div>

                    <div className="flex items-center gap-2">
                      <span className="text-sm text-muted-foreground">순서: {index + 1}</span>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleRemoveComposition(comp.id)}
                      >
                        <Trash2 className="h-4 w-4 text-destructive" />
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* 하단 버튼 */}
        <div className="flex justify-end gap-4">
          <Button variant="outline" onClick={onCancel}>
            취소
          </Button>
          <Button onClick={handleSave}>
            저장
          </Button>
        </div>
      </div>

      {/* 구성 요소 추가 다이얼로그 */}
      <Dialog open={isAddingComposition} onOpenChange={setIsAddingComposition}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden flex flex-col">
          <DialogHeader>
            <DialogTitle>구성 요소 추가</DialogTitle>
            <DialogDescription>
              추가할 컴포넌트를 선택하세요
            </DialogDescription>
          </DialogHeader>

          <div className="relative mb-4">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="컴포넌트 검색..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>

          <div className="flex-1 overflow-y-auto">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              {availableComponents.length === 0 ? (
                <div className="col-span-2 text-center py-8 text-muted-foreground">
                  <p>사용 가능한 컴포넌트가 없습니다</p>
                </div>
              ) : (
                availableComponents.map((comp) => (
                  <button
                    key={comp.id}
                    onClick={() => handleAddComposition(comp)}
                    className="text-left p-4 border rounded-lg hover:bg-accent transition-colors"
                  >
                    <div className="flex items-start justify-between mb-2">
                      <div>
                        <p className="font-medium">{comp.displayName}</p>
                        <p className="text-xs text-muted-foreground font-mono">{comp.name}</p>
                      </div>
                      <Badge variant="outline" className="text-xs">
                        {comp.category}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground line-clamp-2">
                      {comp.description}
                    </p>
                  </button>
                ))
              )}
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setIsAddingComposition(false)}>
              취소
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}

// ============= 통합 검색 결과 컴포넌트 =============

interface UnifiedSearchResultsProps {
  searchTerm: string;
  colors: ColorItem[];
  typography: TypographyItem[];
  spacing: SpacingItem[];
  shadows: ShadowItem[];
  components: ComponentItem[];
  tokens: TokenItem[];
  breakpoints: ResponsiveBreakpoint[];
  onEdit: (type: any, item: any) => void;
  onDelete: (type: any, id: string, skipConfirm?: boolean) => void;
  onViewComponent: (component: ComponentItem) => void;
  onClearSearch: () => void;
}

function UnifiedSearchResults({
  searchTerm,
  colors,
  typography,
  spacing,
  shadows,
  components,
  tokens,
  breakpoints,
  onEdit,
  onDelete,
  onViewComponent,
  onClearSearch
}: UnifiedSearchResultsProps) {
  const term = searchTerm.toLowerCase();

  // 각 섹션별로 검색
  const foundColors = colors.filter(item =>
    item.name.toLowerCase().includes(term) ||
    item.value.toLowerCase().includes(term) ||
    item.description?.toLowerCase().includes(term)
  );

  const foundTypography = typography.filter(item =>
    item.name.toLowerCase().includes(term) ||
    item.usage.toLowerCase().includes(term)
  );

  const foundSpacing = spacing.filter(item =>
    item.name.toLowerCase().includes(term) ||
    item.usage.toLowerCase().includes(term)
  );

  const foundShadows = shadows.filter(item =>
    item.name.toLowerCase().includes(term) ||
    item.usage.toLowerCase().includes(term)
  );

  const foundComponents = components.filter(item =>
    item.name.toLowerCase().includes(term) ||
    item.displayName.toLowerCase().includes(term) ||
    item.description.toLowerCase().includes(term)
  );

  const foundTokens = tokens.filter(item =>
    item.name.toLowerCase().includes(term) ||
    item.value.toLowerCase().includes(term) ||
    item.description.toLowerCase().includes(term)
  );

  const foundBreakpoints = breakpoints.filter(item =>
    item.name.toLowerCase().includes(term) ||
    item.description.toLowerCase().includes(term)
  );

  const totalResults = 
    foundColors.length +
    foundTypography.length +
    foundSpacing.length +
    foundShadows.length +
    foundComponents.length +
    foundTokens.length +
    foundBreakpoints.length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold">
          통합 검색 결과 <Badge variant="secondary" className="ml-2">{totalResults}개</Badge>
        </h3>
        <Button variant="outline" size="sm" onClick={onClearSearch}>
          <X className="h-4 w-4 mr-2" />
          검색 초기화
        </Button>
      </div>

      {totalResults === 0 ? (
        <Card>
          <CardContent className="py-12 text-center">
            <Search className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
            <p className="text-muted-foreground">검색 결과가 없습니다.</p>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-6">
          {/* Foundation - Colors */}
          {foundColors.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Palette className="h-5 w-5" />
                  Colors <Badge variant="secondary">{foundColors.length}</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                  {foundColors.map((color) => (
                    <div key={color.id} className="flex items-center gap-3 p-3 border rounded-lg">
                      <div
                        className="w-12 h-12 rounded-lg border-2 border-gray-300 shadow-sm"
                        style={{ backgroundColor: color.value }}
                      />
                      <div className="flex-1 min-w-0">
                        <p className="font-medium truncate">{color.name}</p>
                        <code className="text-xs text-muted-foreground">{color.value}</code>
                      </div>
                      <div className="flex gap-1">
                        <Button variant="ghost" size="sm" onClick={() => onEdit("color", color)}>
                          <Edit className="h-3 w-3" />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => onDelete("color", color.id)}>
                          <Trash2 className="h-3 w-3" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Foundation - Typography */}
          {foundTypography.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Type className="h-5 w-5" />
                  Typography <Badge variant="secondary">{foundTypography.length}</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>이름</TableHead>
                      <TableHead>미리보기</TableHead>
                      <TableHead>속성</TableHead>
                      <TableHead>사용처</TableHead>
                      <TableHead className="text-right">작업</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {foundTypography.map((typo) => (
                      <TableRow key={typo.id}>
                        <TableCell className="font-medium">{typo.name}</TableCell>
                        <TableCell>
                          <span style={{
                            fontSize: typo.fontSize,
                            fontWeight: typo.fontWeight,
                            lineHeight: typo.lineHeight
                          }}>
                            Aa
                          </span>
                        </TableCell>
                        <TableCell>
                          <div className="text-xs text-muted-foreground space-y-1">
                            <div>Size: {typo.fontSize}</div>
                            <div>Weight: {typo.fontWeight}</div>
                            <div>Line: {typo.lineHeight}</div>
                          </div>
                        </TableCell>
                        <TableCell>{typo.usage}</TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button variant="outline" size="sm" onClick={() => onEdit("typography", typo)}>
                              <Edit className="h-3 w-3" />
                            </Button>
                            <Button variant="ghost" size="sm" onClick={() => onDelete("typography", typo.id)}>
                              <Trash2 className="h-3 w-3" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          )}

          {/* Foundation - Spacing */}
          {foundSpacing.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Ruler className="h-5 w-5" />
                  Spacing <Badge variant="secondary">{foundSpacing.length}</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {foundSpacing.map((space) => (
                    <div key={space.id} className="p-3 border rounded-lg">
                      <div className="flex items-center justify-between mb-2">
                        <span className="font-medium">{space.name}</span>
                        <div className="flex gap-1">
                          <Button variant="ghost" size="sm" onClick={() => onEdit("spacing", space)}>
                            <Edit className="h-3 w-3" />
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => onDelete("spacing", space.id)}>
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        </div>
                      </div>
                      <div className="text-sm text-muted-foreground">
                        {space.value} ({space.pixels})
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Foundation - Shadows */}
          {foundShadows.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <ImageIcon className="h-5 w-5" />
                  Shadows <Badge variant="secondary">{foundShadows.length}</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {foundShadows.map((shadow) => (
                    <div key={shadow.id} className="p-3 border rounded-lg">
                      <div className="flex items-center justify-between mb-3">
                        <span className="font-medium">{shadow.name}</span>
                        <div className="flex gap-1">
                          <Button variant="ghost" size="sm" onClick={() => onEdit("shadow", shadow)}>
                            <Edit className="h-3 w-3" />
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => onDelete("shadow", shadow.id)}>
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        </div>
                      </div>
                      <div
                        className="w-full h-16 bg-white rounded"
                        style={{ boxShadow: shadow.value }}
                      />
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Components */}
          {foundComponents.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Box className="h-5 w-5" />
                  Components <Badge variant="secondary">{foundComponents.length}</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                  {foundComponents.map((comp) => (
                    <Card key={comp.id}>
                      <CardHeader>
                        <div className="flex items-start justify-between">
                          <div>
                            <CardTitle className="text-base">{comp.displayName}</CardTitle>
                            <CardDescription className="text-xs font-mono mt-1">
                              {comp.name}
                            </CardDescription>
                          </div>
                          <Badge variant={
                            comp.category === "atoms" ? "default" :
                            comp.category === "molecules" ? "secondary" :
                            comp.category === "organisms" ? "outline" : "destructive"
                          }>
                            {comp.category}
                          </Badge>
                        </div>
                      </CardHeader>
                      <CardContent>
                        <p className="text-sm text-muted-foreground mb-3">{comp.description}</p>
                        <div className="flex items-center gap-2 mb-3">
                          <Badge variant={comp.status === "stable" ? "default" : comp.status === "beta" ? "secondary" : "destructive"}>
                            {comp.status}
                          </Badge>
                          {comp.responsive && (
                            <Badge variant="outline">
                              <Monitor className="h-3 w-3 mr-1" />
                              반응형
                            </Badge>
                          )}
                        </div>
                        <div className="flex gap-2">
                          <Button variant="outline" size="sm" onClick={() => onViewComponent(comp)}>
                            <Eye className="h-3 w-3 mr-1" />
                            구조
                          </Button>
                          <Button variant="outline" size="sm" onClick={() => onEdit("component", comp)}>
                            <Edit className="h-3 w-3 mr-1" />
                            수정
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => onDelete("component", comp.id)}>
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Tokens */}
          {foundTokens.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Code className="h-5 w-5" />
                  Tokens <Badge variant="secondary">{foundTokens.length}</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>이름</TableHead>
                      <TableHead>값</TableHead>
                      <TableHead>카테고리</TableHead>
                      <TableHead>설명</TableHead>
                      <TableHead className="text-right">작업</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {foundTokens.map((token) => (
                      <TableRow key={token.id}>
                        <TableCell className="font-mono text-sm">{token.name}</TableCell>
                        <TableCell className="font-mono text-sm">{token.value}</TableCell>
                        <TableCell>
                          <Badge variant="outline">{token.category}</Badge>
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground">{token.description}</TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button variant="outline" size="sm" onClick={() => onEdit("token", token)}>
                              <Edit className="h-3 w-3" />
                            </Button>
                            <Button variant="ghost" size="sm" onClick={() => onDelete("token", token.id)}>
                              <Trash2 className="h-3 w-3" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          )}

          {/* Breakpoints */}
          {foundBreakpoints.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Monitor className="h-5 w-5" />
                  Breakpoints <Badge variant="secondary">{foundBreakpoints.length}</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  {foundBreakpoints.map((bp) => (
                    <Card key={bp.id}>
                      <CardHeader>
                        <div className="flex items-start justify-between">
                          <CardTitle className="text-lg flex items-center gap-2">
                            {bp.name === "Mobile" && <Smartphone className="h-5 w-5" />}
                            {bp.name === "Tablet" && <TabletIcon className="h-5 w-5" />}
                            {bp.name === "Desktop" && <Monitor className="h-5 w-5" />}
                            {bp.name}
                          </CardTitle>
                        </div>
                      </CardHeader>
                      <CardContent className="space-y-3">
                        <div className="space-y-1">
                          <p className="text-sm text-muted-foreground">최소 너비: {bp.minWidth}</p>
                          {bp.maxWidth && <p className="text-sm text-muted-foreground">최대 너비: {bp.maxWidth}</p>}
                        </div>
                        <p className="text-sm">{bp.description}</p>
                        <div className="flex gap-2">
                          <Button variant="outline" size="sm" onClick={() => onEdit("breakpoint", bp)}>
                            <Edit className="h-3 w-3 mr-1" />
                            수정
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => onDelete("breakpoint", bp.id)}>
                            <Trash2 className="h-3 w-3 mr-1" />
                            삭제
                          </Button>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      )}
    </div>
  );
}