'use client'

import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { Checkbox } from "@/components/ui/checkbox"
import { Slider } from "@/components/ui/slider"
import {
  Search,
  ChevronDown,
  ChevronUp,
  X,
  Filter,
  Dna,
  BarChart3,
  Pin,
  GripVertical,
  ChevronLeft,
  ChevronRight,
  Settings,
  Plus
} from 'lucide-react'

// 샘플 유전자 데이터 (실제 전역필터와 동일한 구조)
const SAMPLE_GENES = {
  quantity: [
    { id: 'PLAG1', name: 'PLAG1', description: '성장 및 체중 증가' },
    { id: 'NCAPG2', name: 'NCAPG2', description: '체구 크기와 성장 속도' },
    { id: 'LCORL', name: 'LCORL', description: '체형 및 성장' },
    { id: 'ARRDC3', name: 'ARRDC3', description: '체중 증가' },
    { id: 'LAP3', name: 'LAP3', description: '성장 속도' },
  ],
  quality: [
    { id: 'NT5E', name: 'NT5E', description: '근내지방도' },
    { id: 'SCD', name: 'SCD', description: '지방산 불포화도' },
    { id: 'FASN', name: 'FASN', description: '지방 합성' },
    { id: 'CAPN1', name: 'CAPN1', description: '육질 연도' },
    { id: 'CAST', name: 'CAST', description: '육질 연도 억제' },
    { id: 'DGAT1', name: 'DGAT1', description: '지방 함량' },
  ]
}

// 샘플 형질 데이터 (실제 전역필터와 동일한 구조)
const SAMPLE_TRAITS = {
  growth: [
    { id: '12개월령체중', name: '12개월령체중', description: '12개월 시점 체중' },
  ],
  economic: [
    { id: '도체중', name: '도체중', description: '도축 후 고기 무게' },
    { id: '등심단면적', name: '등심단면적', description: '등심의 단면 크기' },
    { id: '등지방두께', name: '등지방두께', description: '등 부위 지방 두께' },
    { id: '근내지방도', name: '근내지방도', description: '마블링 정도' },
  ],
  body: [
    { id: '체고', name: '체고', description: '어깨 높이' },
    { id: '십자', name: '십자', description: '엉덩이뼈 높이' },
    { id: '체장', name: '체장', description: '몸통 길이' },
    { id: '흉심', name: '흉심', description: '가슴 깊이' },
    { id: '흉폭', name: '흉폭', description: '가슴 너비' },
    { id: '고장', name: '고장', description: '허리뼈 길이' },
    { id: '요각폭', name: '요각폭', description: '허리뼈 너비' },
    { id: '좌골폭', name: '좌골폭', description: '엉덩이뼈 너비' },
    { id: '곤폭', name: '곤폭', description: '엉덩이뼈 끝 너비' },
    { id: '흉위', name: '흉위', description: '가슴 둘레' },
  ],
  weight: [
    { id: '안심weight', name: '안심', description: '안심 부위 무게' },
    { id: '등심weight', name: '등심', description: '등심 부위 무게' },
    { id: '채끝weight', name: '채끝', description: '채끝 부위 무게' },
    { id: '목심weight', name: '목심', description: '목심 부위 무게' },
    { id: '앞다리weight', name: '앞다리', description: '앞다리 부위 무게' },
    { id: '우둔weight', name: '우둔', description: '우둔 부위 무게' },
    { id: '설도weight', name: '설도', description: '설도 부위 무게' },
    { id: '사태weight', name: '사태', description: '사태 부위 무게' },
    { id: '양지weight', name: '양지', description: '양지 부위 무게' },
    { id: '갈비weight', name: '갈비', description: '갈비 부위 무게' },
  ],
  rate: [
    { id: '안심rate', name: '안심', description: '전체 대비 안심 비율' },
    { id: '등심rate', name: '등심', description: '전체 대비 등심 비율' },
    { id: '채끝rate', name: '채끝', description: '전체 대비 채끝 비율' },
    { id: '목심rate', name: '목심', description: '전체 대비 목심 비율' },
    { id: '앞다리rate', name: '앞다리', description: '전체 대비 앞다리 비율' },
    { id: '우둔rate', name: '우둔', description: '전체 대비 우둔 비율' },
    { id: '설도rate', name: '설도', description: '전체 대비 설도 비율' },
    { id: '사태rate', name: '사태', description: '전체 대비 사태 비율' },
    { id: '양지rate', name: '양지', description: '전체 대비 양지 비율' },
    { id: '갈비rate', name: '갈비', description: '전체 대비 갈비 비율' },
  ],
}

export default function GlobalFilterDemo() {
  const [activeTab, setActiveTab] = useState('option-a')

  return (
    <div className="min-h-screen bg-slate-100 p-4 sm:p-8">
      <div className="max-w-4xl mx-auto space-y-6">
        <h1 className="text-2xl font-bold text-foreground">전역 필터 UI 시안 데모</h1>
        <p className="text-muted-foreground">
          7가지 시안을 비교해보세요. 각 탭을 눌러 다른 UI 방식을 확인할 수 있습니다.
        </p>
        <p className="text-sm text-blue-600">
          ✓ 모든 시안에 고정(Pin) 기능과 드래그 순서 변경 기능이 포함되어 있습니다.
        </p>

        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-4 lg:grid-cols-7">
            <TabsTrigger value="option-a">A: 드롭다운</TabsTrigger>
            <TabsTrigger value="option-b">B: 통합검색</TabsTrigger>
            <TabsTrigger value="option-c">C: 현재방식</TabsTrigger>
            <TabsTrigger value="option-d">D: 스텝</TabsTrigger>
            <TabsTrigger value="option-e">E: 탭분리</TabsTrigger>
            <TabsTrigger value="option-f">F: 모달선택</TabsTrigger>
            <TabsTrigger value="option-h">H: 칩기반</TabsTrigger>
          </TabsList>

          <TabsContent value="option-a" className="mt-6">
            <OptionA />
          </TabsContent>

          <TabsContent value="option-b" className="mt-6">
            <OptionB />
          </TabsContent>

          <TabsContent value="option-c" className="mt-6">
            <OptionC />
          </TabsContent>

          <TabsContent value="option-d" className="mt-6">
            <OptionD />
          </TabsContent>

          <TabsContent value="option-e" className="mt-6">
            <OptionE />
          </TabsContent>

          <TabsContent value="option-f" className="mt-6">
            <OptionF />
          </TabsContent>

          <TabsContent value="option-h" className="mt-6">
            <OptionH />
          </TabsContent>
        </Tabs>
      </div>
    </div>
  )
}

// 공통 드래그 가능한 아이템 컴포넌트
function DraggableItem({
  id,
  label,
  isPinned,
  onTogglePin,
  onRemove,
  weight,
  onWeightChange,
  showWeight = false
}: {
  id: string
  label: string
  isPinned: boolean
  onTogglePin: () => void
  onRemove: () => void
  weight?: number
  onWeightChange?: (value: number) => void
  showWeight?: boolean
}) {
  return (
    <div className={`flex items-center gap-2 p-2 rounded-lg border ${isPinned ? 'bg-amber-50 border-amber-200' : 'bg-white'}`}>
      <GripVertical className="w-4 h-4 text-slate-400 cursor-grab" />
      <span className="font-medium flex-1">{label}</span>
      {showWeight && weight !== undefined && onWeightChange && (
        <div className="flex items-center gap-2 flex-1">
          <Slider
            value={[weight]}
            onValueChange={([v]) => onWeightChange(v)}
            max={10}
            step={1}
            className="w-20"
          />
          <span className="text-xs w-6">{weight}점</span>
        </div>
      )}
      <button
        onClick={onTogglePin}
        className={`p-1 rounded ${isPinned ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
        title={isPinned ? '고정 해제' : '고정'}
      >
        <Pin className="w-4 h-4" fill={isPinned ? 'currentColor' : 'none'} />
      </button>
      <button onClick={onRemove} className="p-1 text-slate-400 hover:text-red-500">
        <X className="w-4 h-4" />
      </button>
    </div>
  )
}

/**
 * 시안 A: 드롭다운 방식
 * - 선택한 필터 조건 박스 안에서 "유전자를 선택해주세요" 클릭 시 드롭다운
 * - 드롭다운 내에서 고정 영역 + 검색 + 목록
 */
function OptionA() {
  const [selectedGenes, setSelectedGenes] = useState<string[]>(['PLAG1', 'NT5E', 'SCD'])
  const [pinnedGenes, setPinnedGenes] = useState<string[]>(['PLAG1', 'NT5E'])
  const [selectedTraits, setSelectedTraits] = useState<string[]>(['도체중', '등심단면적'])
  const [pinnedTraits, setPinnedTraits] = useState<string[]>(['도체중'])
  const [traitWeights, setTraitWeights] = useState<Record<string, number>>({ '도체중': 7, '등심단면적': 5 })
  const [geneDropdownOpen, setGeneDropdownOpen] = useState(false)
  const [traitDropdownOpen, setTraitDropdownOpen] = useState(false)
  const [geneSearch, setGeneSearch] = useState('')
  const [traitSearch, setTraitSearch] = useState('')

  const toggleGene = (geneId: string) => {
    if (selectedGenes.includes(geneId)) {
      setSelectedGenes(prev => prev.filter(g => g !== geneId))
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else {
      setSelectedGenes(prev => [...prev, geneId])
    }
  }

  const toggleGenePin = (geneId: string) => {
    if (pinnedGenes.includes(geneId)) {
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else if (pinnedGenes.length < 5) {
      setPinnedGenes(prev => [...prev, geneId])
    }
  }

  const toggleTrait = (traitId: string) => {
    if (selectedTraits.includes(traitId)) {
      setSelectedTraits(prev => prev.filter(t => t !== traitId))
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
      setTraitWeights(prev => {
        const newWeights = { ...prev }
        delete newWeights[traitId]
        return newWeights
      })
    } else {
      setSelectedTraits(prev => [...prev, traitId])
      setTraitWeights(prev => ({ ...prev, [traitId]: 5 }))
    }
  }

  const toggleTraitPin = (traitId: string) => {
    if (pinnedTraits.includes(traitId)) {
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
    } else if (pinnedTraits.length < 5) {
      setPinnedTraits(prev => [...prev, traitId])
    }
  }

  const allGenes = [...SAMPLE_GENES.quantity, ...SAMPLE_GENES.quality]
  const allTraits = [...SAMPLE_TRAITS.economic, ...SAMPLE_TRAITS.growth, ...SAMPLE_TRAITS.body]

  const filteredGenes = allGenes.filter(g =>
    g.name.toLowerCase().includes(geneSearch.toLowerCase()) ||
    g.description.toLowerCase().includes(geneSearch.toLowerCase())
  )

  const filteredTraits = allTraits.filter(t =>
    t.name.toLowerCase().includes(traitSearch.toLowerCase()) ||
    t.description.toLowerCase().includes(traitSearch.toLowerCase())
  )

  // 정렬: 고정된 것 먼저, 그 다음 일반
  const sortedSelectedGenes = [
    ...pinnedGenes.filter(g => selectedGenes.includes(g)),
    ...selectedGenes.filter(g => !pinnedGenes.includes(g))
  ]

  const sortedSelectedTraits = [
    ...pinnedTraits.filter(t => selectedTraits.includes(t)),
    ...selectedTraits.filter(t => !pinnedTraits.includes(t))
  ]

  return (
    <Card className="bg-white border shadow-sm rounded-2xl">
      <CardHeader className="pb-4">
        <CardTitle className="flex items-center gap-2 text-lg">
          <Filter className="w-5 h-5" />
          시안 A: 드롭다운 방식
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          선택 영역 터치 → 드롭다운 펼침 → 고정 영역 + 검색 + 목록
        </p>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="p-4 bg-slate-50 rounded-xl border space-y-4">
          <h4 className="font-semibold text-foreground">선택한 필터 조건</h4>

          {/* 유전자 드롭다운 */}
          <Collapsible open={geneDropdownOpen} onOpenChange={setGeneDropdownOpen}>
            <CollapsibleTrigger className="w-full">
              <div className="flex items-center justify-between p-3 bg-white rounded-lg border hover:bg-slate-50 transition-colors">
                <div className="flex items-center gap-2">
                  <Dna className="w-4 h-4 text-blue-500" />
                  <span className="font-medium">유전자</span>
                  {selectedGenes.length > 0 && (
                    <Badge variant="secondary">{selectedGenes.length}개</Badge>
                  )}
                  {pinnedGenes.length > 0 && (
                    <Badge variant="outline" className="text-amber-600 border-amber-300">
                      <Pin className="w-3 h-3 mr-1" fill="currentColor" />{pinnedGenes.length}
                    </Badge>
                  )}
                </div>
                {geneDropdownOpen ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
              </div>
            </CollapsibleTrigger>
            <CollapsibleContent className="mt-2">
              <div className="p-3 bg-white rounded-lg border space-y-3">
                {/* 고정된 유전자 */}
                {sortedSelectedGenes.length > 0 && (
                  <div className="space-y-2">
                    <div className="flex items-center gap-2 text-xs font-semibold text-amber-600">
                      <Pin className="w-3 h-3" fill="currentColor" />
                      고정됨 (드래그로 순서 변경)
                    </div>
                    {sortedSelectedGenes.filter(g => pinnedGenes.includes(g)).map(geneId => (
                      <DraggableItem
                        key={geneId}
                        id={geneId}
                        label={geneId}
                        isPinned={true}
                        onTogglePin={() => toggleGenePin(geneId)}
                        onRemove={() => toggleGene(geneId)}
                      />
                    ))}
                    {sortedSelectedGenes.filter(g => !pinnedGenes.includes(g)).length > 0 && (
                      <>
                        <div className="text-xs font-semibold text-slate-500 mt-3">일반</div>
                        {sortedSelectedGenes.filter(g => !pinnedGenes.includes(g)).map(geneId => (
                          <DraggableItem
                            key={geneId}
                            id={geneId}
                            label={geneId}
                            isPinned={false}
                            onTogglePin={() => toggleGenePin(geneId)}
                            onRemove={() => toggleGene(geneId)}
                          />
                        ))}
                      </>
                    )}
                  </div>
                )}

                {/* 검색창 */}
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    placeholder="유전자 검색..."
                    className="pl-9"
                    value={geneSearch}
                    onChange={(e) => setGeneSearch(e.target.value)}
                  />
                </div>

                {/* 유전자 목록 */}
                <div className="max-h-48 overflow-y-auto space-y-1">
                  <div className="text-xs font-semibold text-blue-600 py-1">육량형</div>
                  {filteredGenes.filter(g => SAMPLE_GENES.quantity.some(q => q.id === g.id)).map(gene => (
                    <div
                      key={gene.id}
                      className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                        selectedGenes.includes(gene.id) ? 'bg-blue-50 border border-blue-200' : 'hover:bg-slate-50 border border-transparent'
                      }`}
                      onClick={() => toggleGene(gene.id)}
                    >
                      <div className="flex items-center gap-2">
                        <Checkbox checked={selectedGenes.includes(gene.id)} />
                        <span className="font-medium">{gene.name}</span>
                        <span className="text-xs text-muted-foreground">{gene.description}</span>
                      </div>
                      {selectedGenes.includes(gene.id) && (
                        <button
                          onClick={(e) => { e.stopPropagation(); toggleGenePin(gene.id); }}
                          className={`p-1 rounded ${pinnedGenes.includes(gene.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                        >
                          <Pin className="w-4 h-4" fill={pinnedGenes.includes(gene.id) ? 'currentColor' : 'none'} />
                        </button>
                      )}
                    </div>
                  ))}
                  <div className="text-xs font-semibold text-orange-600 py-1 mt-2">육질형</div>
                  {filteredGenes.filter(g => SAMPLE_GENES.quality.some(q => q.id === g.id)).map(gene => (
                    <div
                      key={gene.id}
                      className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                        selectedGenes.includes(gene.id) ? 'bg-orange-50 border border-orange-200' : 'hover:bg-slate-50 border border-transparent'
                      }`}
                      onClick={() => toggleGene(gene.id)}
                    >
                      <div className="flex items-center gap-2">
                        <Checkbox checked={selectedGenes.includes(gene.id)} />
                        <span className="font-medium">{gene.name}</span>
                        <span className="text-xs text-muted-foreground">{gene.description}</span>
                      </div>
                      {selectedGenes.includes(gene.id) && (
                        <button
                          onClick={(e) => { e.stopPropagation(); toggleGenePin(gene.id); }}
                          className={`p-1 rounded ${pinnedGenes.includes(gene.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                        >
                          <Pin className="w-4 h-4" fill={pinnedGenes.includes(gene.id) ? 'currentColor' : 'none'} />
                        </button>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </CollapsibleContent>
          </Collapsible>

          {/* 형질 드롭다운 */}
          <Collapsible open={traitDropdownOpen} onOpenChange={setTraitDropdownOpen}>
            <CollapsibleTrigger className="w-full">
              <div className="flex items-center justify-between p-3 bg-white rounded-lg border hover:bg-slate-50 transition-colors">
                <div className="flex items-center gap-2">
                  <BarChart3 className="w-4 h-4 text-emerald-500" />
                  <span className="font-medium">형질</span>
                  {selectedTraits.length > 0 && (
                    <Badge variant="secondary">{selectedTraits.length}개</Badge>
                  )}
                  {pinnedTraits.length > 0 && (
                    <Badge variant="outline" className="text-amber-600 border-amber-300">
                      <Pin className="w-3 h-3 mr-1" fill="currentColor" />{pinnedTraits.length}
                    </Badge>
                  )}
                </div>
                {traitDropdownOpen ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
              </div>
            </CollapsibleTrigger>
            <CollapsibleContent className="mt-2">
              <div className="p-3 bg-white rounded-lg border space-y-3">
                {/* 선택된 형질 + 가중치 */}
                {sortedSelectedTraits.length > 0 && (
                  <div className="space-y-2">
                    <div className="flex items-center gap-2 text-xs font-semibold text-amber-600">
                      <Pin className="w-3 h-3" fill="currentColor" />
                      고정됨 (드래그로 순서 변경)
                    </div>
                    {sortedSelectedTraits.filter(t => pinnedTraits.includes(t)).map(traitId => (
                      <DraggableItem
                        key={traitId}
                        id={traitId}
                        label={traitId}
                        isPinned={true}
                        onTogglePin={() => toggleTraitPin(traitId)}
                        onRemove={() => toggleTrait(traitId)}
                        showWeight={true}
                        weight={traitWeights[traitId]}
                        onWeightChange={(v) => setTraitWeights(prev => ({ ...prev, [traitId]: v }))}
                      />
                    ))}
                    {sortedSelectedTraits.filter(t => !pinnedTraits.includes(t)).length > 0 && (
                      <>
                        <div className="text-xs font-semibold text-slate-500 mt-3">일반</div>
                        {sortedSelectedTraits.filter(t => !pinnedTraits.includes(t)).map(traitId => (
                          <DraggableItem
                            key={traitId}
                            id={traitId}
                            label={traitId}
                            isPinned={false}
                            onTogglePin={() => toggleTraitPin(traitId)}
                            onRemove={() => toggleTrait(traitId)}
                            showWeight={true}
                            weight={traitWeights[traitId]}
                            onWeightChange={(v) => setTraitWeights(prev => ({ ...prev, [traitId]: v }))}
                          />
                        ))}
                      </>
                    )}
                  </div>
                )}

                {/* 검색창 */}
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    placeholder="형질 검색..."
                    className="pl-9"
                    value={traitSearch}
                    onChange={(e) => setTraitSearch(e.target.value)}
                  />
                </div>

                {/* 형질 목록 */}
                <div className="max-h-48 overflow-y-auto space-y-1">
                  <div className="text-xs font-semibold text-emerald-600 py-1">경제형질</div>
                  {filteredTraits.filter(t => SAMPLE_TRAITS.economic.some(e => e.id === t.id)).map(trait => (
                    <div
                      key={trait.id}
                      className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                        selectedTraits.includes(trait.id) ? 'bg-emerald-50 border border-emerald-200' : 'hover:bg-slate-50 border border-transparent'
                      }`}
                      onClick={() => toggleTrait(trait.id)}
                    >
                      <div className="flex items-center gap-2">
                        <Checkbox checked={selectedTraits.includes(trait.id)} />
                        <span className="font-medium">{trait.name}</span>
                        <span className="text-xs text-muted-foreground">{trait.description}</span>
                      </div>
                      {selectedTraits.includes(trait.id) && (
                        <button
                          onClick={(e) => { e.stopPropagation(); toggleTraitPin(trait.id); }}
                          className={`p-1 rounded ${pinnedTraits.includes(trait.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                        >
                          <Pin className="w-4 h-4" fill={pinnedTraits.includes(trait.id) ? 'currentColor' : 'none'} />
                        </button>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </CollapsibleContent>
          </Collapsible>
        </div>

        <div className="flex gap-2">
          <Button className="flex-1">적용</Button>
          <Button variant="outline">초기화</Button>
        </div>
      </CardContent>
    </Card>
  )
}

/**
 * 시안 B: 통합검색 + 결과 바로 아래 + 하단 선택조건
 */
function OptionB() {
  const [selectedGenes, setSelectedGenes] = useState<string[]>(['PLAG1', 'NT5E', 'SCD'])
  const [pinnedGenes, setPinnedGenes] = useState<string[]>(['PLAG1', 'NT5E'])
  const [selectedTraits, setSelectedTraits] = useState<string[]>(['도체중', '등심단면적'])
  const [pinnedTraits, setPinnedTraits] = useState<string[]>(['도체중'])
  const [traitWeights, setTraitWeights] = useState<Record<string, number>>({ '도체중': 7, '등심단면적': 5 })
  const [searchQuery, setSearchQuery] = useState('')
  const [quantityOpen, setQuantityOpen] = useState(false)
  const [qualityOpen, setQualityOpen] = useState(false)
  const [economicOpen, setEconomicOpen] = useState(false)

  const toggleGene = (geneId: string) => {
    if (selectedGenes.includes(geneId)) {
      setSelectedGenes(prev => prev.filter(g => g !== geneId))
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else {
      setSelectedGenes(prev => [...prev, geneId])
    }
  }

  const toggleGenePin = (geneId: string) => {
    if (pinnedGenes.includes(geneId)) {
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else if (pinnedGenes.length < 5) {
      setPinnedGenes(prev => [...prev, geneId])
    }
  }

  const toggleTrait = (traitId: string) => {
    if (selectedTraits.includes(traitId)) {
      setSelectedTraits(prev => prev.filter(t => t !== traitId))
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
      setTraitWeights(prev => {
        const newWeights = { ...prev }
        delete newWeights[traitId]
        return newWeights
      })
    } else {
      setSelectedTraits(prev => [...prev, traitId])
      setTraitWeights(prev => ({ ...prev, [traitId]: 5 }))
    }
  }

  const toggleTraitPin = (traitId: string) => {
    if (pinnedTraits.includes(traitId)) {
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
    } else if (pinnedTraits.length < 5) {
      setPinnedTraits(prev => [...prev, traitId])
    }
  }

  // 검색 필터링
  const filteredQuantityGenes = SAMPLE_GENES.quantity.filter(g =>
    !searchQuery || g.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    g.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
    '육량형'.includes(searchQuery)
  )
  const filteredQualityGenes = SAMPLE_GENES.quality.filter(g =>
    !searchQuery || g.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    g.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
    '육질형'.includes(searchQuery)
  )
  const filteredEconomicTraits = SAMPLE_TRAITS.economic.filter(t =>
    !searchQuery || t.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    t.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
    '경제형질'.includes(searchQuery)
  )

  const shouldShowQuantity = !searchQuery || filteredQuantityGenes.length > 0
  const shouldShowQuality = !searchQuery || filteredQualityGenes.length > 0
  const shouldShowEconomic = !searchQuery || filteredEconomicTraits.length > 0

  // 정렬
  const sortedSelectedGenes = [
    ...pinnedGenes.filter(g => selectedGenes.includes(g)),
    ...selectedGenes.filter(g => !pinnedGenes.includes(g))
  ]
  const sortedSelectedTraits = [
    ...pinnedTraits.filter(t => selectedTraits.includes(t)),
    ...selectedTraits.filter(t => !pinnedTraits.includes(t))
  ]

  return (
    <Card className="bg-white border shadow-sm rounded-2xl">
      <CardHeader className="pb-4">
        <CardTitle className="flex items-center gap-2 text-lg">
          <Filter className="w-5 h-5" />
          시안 B: 통합검색 + 하단 선택조건 (권장)
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          통합검색 → 바로 아래 결과 → 맨 아래서 선택 조건 및 고정/순서 관리
        </p>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 통합 검색창 */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
          <Input
            placeholder="유전자, 형질 통합 검색..."
            className="pl-9 h-11"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>

        {/* 유전자 섹션 */}
        <div className="space-y-2">
          <h4 className="font-semibold text-foreground flex items-center gap-2">
            <Dna className="w-4 h-4" />
            유전자 선택
          </h4>

          {shouldShowQuantity && (
            <Collapsible open={quantityOpen || !!searchQuery} onOpenChange={setQuantityOpen}>
              <CollapsibleTrigger className="w-full">
                <div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-100">
                  <span className="font-medium text-blue-700">육량형</span>
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className="text-blue-600">{filteredQuantityGenes.length}개</Badge>
                    {(quantityOpen || !!searchQuery) ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                  </div>
                </div>
              </CollapsibleTrigger>
              <CollapsibleContent className="mt-2 space-y-1">
                {filteredQuantityGenes.map(gene => (
                  <div
                    key={gene.id}
                    className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                      selectedGenes.includes(gene.id) ? 'bg-blue-100 border border-blue-200' : 'bg-white border hover:bg-slate-50'
                    }`}
                    onClick={() => toggleGene(gene.id)}
                  >
                    <div className="flex items-center gap-2">
                      <Checkbox checked={selectedGenes.includes(gene.id)} />
                      <span className="font-medium">{gene.name}</span>
                      <span className="text-xs text-muted-foreground">{gene.description}</span>
                    </div>
                    {selectedGenes.includes(gene.id) && (
                      <button
                        onClick={(e) => { e.stopPropagation(); toggleGenePin(gene.id); }}
                        className={`p-1 rounded ${pinnedGenes.includes(gene.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                      >
                        <Pin className="w-4 h-4" fill={pinnedGenes.includes(gene.id) ? 'currentColor' : 'none'} />
                      </button>
                    )}
                  </div>
                ))}
              </CollapsibleContent>
            </Collapsible>
          )}

          {shouldShowQuality && (
            <Collapsible open={qualityOpen || !!searchQuery} onOpenChange={setQualityOpen}>
              <CollapsibleTrigger className="w-full">
                <div className="flex items-center justify-between p-3 bg-orange-50 rounded-lg border border-orange-100">
                  <span className="font-medium text-orange-700">육질형</span>
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className="text-orange-600">{filteredQualityGenes.length}개</Badge>
                    {(qualityOpen || !!searchQuery) ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                  </div>
                </div>
              </CollapsibleTrigger>
              <CollapsibleContent className="mt-2 space-y-1">
                {filteredQualityGenes.map(gene => (
                  <div
                    key={gene.id}
                    className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                      selectedGenes.includes(gene.id) ? 'bg-orange-100 border border-orange-200' : 'bg-white border hover:bg-slate-50'
                    }`}
                    onClick={() => toggleGene(gene.id)}
                  >
                    <div className="flex items-center gap-2">
                      <Checkbox checked={selectedGenes.includes(gene.id)} />
                      <span className="font-medium">{gene.name}</span>
                      <span className="text-xs text-muted-foreground">{gene.description}</span>
                    </div>
                    {selectedGenes.includes(gene.id) && (
                      <button
                        onClick={(e) => { e.stopPropagation(); toggleGenePin(gene.id); }}
                        className={`p-1 rounded ${pinnedGenes.includes(gene.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                      >
                        <Pin className="w-4 h-4" fill={pinnedGenes.includes(gene.id) ? 'currentColor' : 'none'} />
                      </button>
                    )}
                  </div>
                ))}
              </CollapsibleContent>
            </Collapsible>
          )}
        </div>

        {/* 형질 섹션 */}
        <div className="space-y-2">
          <h4 className="font-semibold text-foreground flex items-center gap-2">
            <BarChart3 className="w-4 h-4" />
            형질 가중치 설정
          </h4>

          {shouldShowEconomic && (
            <Collapsible open={economicOpen || !!searchQuery} onOpenChange={setEconomicOpen}>
              <CollapsibleTrigger className="w-full">
                <div className="flex items-center justify-between p-3 bg-emerald-50 rounded-lg border border-emerald-100">
                  <span className="font-medium text-emerald-700">경제형질</span>
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className="text-emerald-600">{filteredEconomicTraits.length}개</Badge>
                    {(economicOpen || !!searchQuery) ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                  </div>
                </div>
              </CollapsibleTrigger>
              <CollapsibleContent className="mt-2 space-y-1">
                {filteredEconomicTraits.map(trait => (
                  <div
                    key={trait.id}
                    className={`p-2 rounded-lg transition-colors ${
                      selectedTraits.includes(trait.id) ? 'bg-emerald-50 border border-emerald-200' : 'bg-white border hover:bg-slate-50'
                    }`}
                  >
                    <div
                      className="flex items-center justify-between cursor-pointer"
                      onClick={() => toggleTrait(trait.id)}
                    >
                      <div className="flex items-center gap-2">
                        <Checkbox checked={selectedTraits.includes(trait.id)} />
                        <span className="font-medium">{trait.name}</span>
                        <span className="text-xs text-muted-foreground">{trait.description}</span>
                      </div>
                      {selectedTraits.includes(trait.id) && (
                        <button
                          onClick={(e) => { e.stopPropagation(); toggleTraitPin(trait.id); }}
                          className={`p-1 rounded ${pinnedTraits.includes(trait.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                        >
                          <Pin className="w-4 h-4" fill={pinnedTraits.includes(trait.id) ? 'currentColor' : 'none'} />
                        </button>
                      )}
                    </div>
                    {selectedTraits.includes(trait.id) && (
                      <div className="flex items-center gap-3 mt-2 pl-6">
                        <Slider
                          value={[traitWeights[trait.id] || 0]}
                          onValueChange={([v]) => setTraitWeights(prev => ({ ...prev, [trait.id]: v }))}
                          max={10}
                          step={1}
                          className="flex-1"
                        />
                        <span className="text-sm font-medium w-8">{traitWeights[trait.id] || 0}점</span>
                      </div>
                    )}
                  </div>
                ))}
              </CollapsibleContent>
            </Collapsible>
          )}
        </div>

        {/* 선택한 필터 조건 (하단) */}
        <div className="p-4 bg-slate-50 rounded-xl border space-y-3">
          <h4 className="font-semibold text-foreground flex items-center gap-2">
            선택한 필터 조건
            <Badge variant="secondary">{selectedGenes.length + selectedTraits.length}개</Badge>
          </h4>

          {/* 유전자 */}
          {sortedSelectedGenes.length > 0 && (
            <div className="space-y-2">
              <div className="flex items-center gap-2 text-sm">
                <Dna className="w-4 h-4 text-blue-500" />
                <span className="font-medium">유전자</span>
              </div>
              <div className="space-y-1">
                {sortedSelectedGenes.map(geneId => (
                  <DraggableItem
                    key={geneId}
                    id={geneId}
                    label={geneId}
                    isPinned={pinnedGenes.includes(geneId)}
                    onTogglePin={() => toggleGenePin(geneId)}
                    onRemove={() => toggleGene(geneId)}
                  />
                ))}
              </div>
            </div>
          )}

          {/* 형질 */}
          {sortedSelectedTraits.length > 0 && (
            <div className="space-y-2">
              <div className="flex items-center gap-2 text-sm">
                <BarChart3 className="w-4 h-4 text-emerald-500" />
                <span className="font-medium">형질</span>
              </div>
              <div className="space-y-1">
                {sortedSelectedTraits.map(traitId => (
                  <DraggableItem
                    key={traitId}
                    id={traitId}
                    label={traitId}
                    isPinned={pinnedTraits.includes(traitId)}
                    onTogglePin={() => toggleTraitPin(traitId)}
                    onRemove={() => toggleTrait(traitId)}
                    showWeight={true}
                    weight={traitWeights[traitId]}
                    onWeightChange={(v) => setTraitWeights(prev => ({ ...prev, [traitId]: v }))}
                  />
                ))}
              </div>
            </div>
          )}
        </div>

        <div className="flex gap-2">
          <Button className="flex-1">적용</Button>
          <Button variant="outline">초기화</Button>
        </div>
      </CardContent>
    </Card>
  )
}

/**
 * 시안 C: 현재 방식 (선택조건 상단 고정)
 */
function OptionC() {
  const [selectedGenes, setSelectedGenes] = useState<string[]>(['PLAG1', 'NT5E', 'SCD'])
  const [pinnedGenes, setPinnedGenes] = useState<string[]>(['PLAG1', 'NT5E'])
  const [selectedTraits, setSelectedTraits] = useState<string[]>(['도체중', '등심단면적'])
  const [pinnedTraits, setPinnedTraits] = useState<string[]>(['도체중'])
  const [traitWeights, setTraitWeights] = useState<Record<string, number>>({ '도체중': 7, '등심단면적': 5 })
  const [searchQuery, setSearchQuery] = useState('')
  const [filterConditionOpen, setFilterConditionOpen] = useState(true)
  const [quantityOpen, setQuantityOpen] = useState(false)
  const [qualityOpen, setQualityOpen] = useState(false)
  const [economicOpen, setEconomicOpen] = useState(false)

  const toggleGene = (geneId: string) => {
    if (selectedGenes.includes(geneId)) {
      setSelectedGenes(prev => prev.filter(g => g !== geneId))
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else {
      setSelectedGenes(prev => [...prev, geneId])
    }
  }

  const toggleGenePin = (geneId: string) => {
    if (pinnedGenes.includes(geneId)) {
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else if (pinnedGenes.length < 5) {
      setPinnedGenes(prev => [...prev, geneId])
    }
  }

  const toggleTrait = (traitId: string) => {
    if (selectedTraits.includes(traitId)) {
      setSelectedTraits(prev => prev.filter(t => t !== traitId))
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
      setTraitWeights(prev => {
        const newWeights = { ...prev }
        delete newWeights[traitId]
        return newWeights
      })
    } else {
      setSelectedTraits(prev => [...prev, traitId])
      setTraitWeights(prev => ({ ...prev, [traitId]: 5 }))
    }
  }

  const toggleTraitPin = (traitId: string) => {
    if (pinnedTraits.includes(traitId)) {
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
    } else if (pinnedTraits.length < 5) {
      setPinnedTraits(prev => [...prev, traitId])
    }
  }

  const sortedSelectedGenes = [
    ...pinnedGenes.filter(g => selectedGenes.includes(g)),
    ...selectedGenes.filter(g => !pinnedGenes.includes(g))
  ]
  const sortedSelectedTraits = [
    ...pinnedTraits.filter(t => selectedTraits.includes(t)),
    ...selectedTraits.filter(t => !pinnedTraits.includes(t))
  ]

  return (
    <Card className="bg-white border shadow-sm rounded-2xl">
      <CardHeader className="pb-4">
        <CardTitle className="flex items-center gap-2 text-lg">
          <Filter className="w-5 h-5" />
          시안 C: 현재 방식 (선택조건 상단)
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          현재 구현된 방식 - 선택 조건이 검색창 위에 고정 (고정/순서 기능 추가)
        </p>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 선택한 필터 조건 (상단 고정) */}
        <Collapsible open={filterConditionOpen} onOpenChange={setFilterConditionOpen}>
          <CollapsibleTrigger className="w-full">
            <div className="flex items-center justify-between p-3 bg-slate-50 rounded-lg border">
              <span className="font-semibold">선택한 필터 조건</span>
              <div className="flex items-center gap-2">
                <Badge variant="secondary">{selectedGenes.length + selectedTraits.length}개</Badge>
                {filterConditionOpen ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
              </div>
            </div>
          </CollapsibleTrigger>
          <CollapsibleContent className="mt-2">
            <div className="p-4 bg-slate-50 rounded-xl border space-y-3">
              {/* 유전자 */}
              {sortedSelectedGenes.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm">
                    <Dna className="w-4 h-4 text-blue-500" />
                    <span className="font-medium">유전자</span>
                  </div>
                  <div className="space-y-1">
                    {sortedSelectedGenes.map(geneId => (
                      <DraggableItem
                        key={geneId}
                        id={geneId}
                        label={geneId}
                        isPinned={pinnedGenes.includes(geneId)}
                        onTogglePin={() => toggleGenePin(geneId)}
                        onRemove={() => toggleGene(geneId)}
                      />
                    ))}
                  </div>
                </div>
              )}

              {/* 형질 */}
              {sortedSelectedTraits.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm">
                    <BarChart3 className="w-4 h-4 text-emerald-500" />
                    <span className="font-medium">형질</span>
                  </div>
                  <div className="space-y-1">
                    {sortedSelectedTraits.map(traitId => (
                      <DraggableItem
                        key={traitId}
                        id={traitId}
                        label={traitId}
                        isPinned={pinnedTraits.includes(traitId)}
                        onTogglePin={() => toggleTraitPin(traitId)}
                        onRemove={() => toggleTrait(traitId)}
                        showWeight={true}
                        weight={traitWeights[traitId]}
                        onWeightChange={(v) => setTraitWeights(prev => ({ ...prev, [traitId]: v }))}
                      />
                    ))}
                  </div>
                </div>
              )}
            </div>
          </CollapsibleContent>
        </Collapsible>

        {/* 통합 검색창 */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
          <Input
            placeholder="유전자, 형질 통합 검색..."
            className="pl-9 h-11"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>

        {/* 유전자 섹션 */}
        <div className="space-y-2">
          <h4 className="font-semibold text-foreground flex items-center gap-2">
            <Dna className="w-4 h-4" />
            유전자 선택
          </h4>

          <Collapsible open={quantityOpen} onOpenChange={setQuantityOpen}>
            <CollapsibleTrigger className="w-full">
              <div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-100">
                <span className="font-medium text-blue-700">육량형</span>
                {quantityOpen ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
              </div>
            </CollapsibleTrigger>
            <CollapsibleContent className="mt-2 space-y-1">
              {SAMPLE_GENES.quantity.map(gene => (
                <div
                  key={gene.id}
                  className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                    selectedGenes.includes(gene.id) ? 'bg-blue-100 border border-blue-200' : 'bg-white border hover:bg-slate-50'
                  }`}
                  onClick={() => toggleGene(gene.id)}
                >
                  <div className="flex items-center gap-2">
                    <Checkbox checked={selectedGenes.includes(gene.id)} />
                    <span className="font-medium">{gene.name}</span>
                    <span className="text-xs text-muted-foreground">{gene.description}</span>
                  </div>
                  {selectedGenes.includes(gene.id) && (
                    <button
                      onClick={(e) => { e.stopPropagation(); toggleGenePin(gene.id); }}
                      className={`p-1 rounded ${pinnedGenes.includes(gene.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                    >
                      <Pin className="w-4 h-4" fill={pinnedGenes.includes(gene.id) ? 'currentColor' : 'none'} />
                    </button>
                  )}
                </div>
              ))}
            </CollapsibleContent>
          </Collapsible>

          <Collapsible open={qualityOpen} onOpenChange={setQualityOpen}>
            <CollapsibleTrigger className="w-full">
              <div className="flex items-center justify-between p-3 bg-orange-50 rounded-lg border border-orange-100">
                <span className="font-medium text-orange-700">육질형</span>
                {qualityOpen ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
              </div>
            </CollapsibleTrigger>
            <CollapsibleContent className="mt-2 space-y-1">
              {SAMPLE_GENES.quality.map(gene => (
                <div
                  key={gene.id}
                  className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                    selectedGenes.includes(gene.id) ? 'bg-orange-100 border border-orange-200' : 'bg-white border hover:bg-slate-50'
                  }`}
                  onClick={() => toggleGene(gene.id)}
                >
                  <div className="flex items-center gap-2">
                    <Checkbox checked={selectedGenes.includes(gene.id)} />
                    <span className="font-medium">{gene.name}</span>
                    <span className="text-xs text-muted-foreground">{gene.description}</span>
                  </div>
                  {selectedGenes.includes(gene.id) && (
                    <button
                      onClick={(e) => { e.stopPropagation(); toggleGenePin(gene.id); }}
                      className={`p-1 rounded ${pinnedGenes.includes(gene.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                    >
                      <Pin className="w-4 h-4" fill={pinnedGenes.includes(gene.id) ? 'currentColor' : 'none'} />
                    </button>
                  )}
                </div>
              ))}
            </CollapsibleContent>
          </Collapsible>
        </div>

        {/* 형질 섹션 */}
        <div className="space-y-2">
          <h4 className="font-semibold text-foreground flex items-center gap-2">
            <BarChart3 className="w-4 h-4" />
            형질 가중치 설정
          </h4>

          <Collapsible open={economicOpen} onOpenChange={setEconomicOpen}>
            <CollapsibleTrigger className="w-full">
              <div className="flex items-center justify-between p-3 bg-emerald-50 rounded-lg border border-emerald-100">
                <span className="font-medium text-emerald-700">경제형질</span>
                {economicOpen ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
              </div>
            </CollapsibleTrigger>
            <CollapsibleContent className="mt-2 space-y-1">
              {SAMPLE_TRAITS.economic.map(trait => (
                <div
                  key={trait.id}
                  className={`p-2 rounded-lg transition-colors ${
                    selectedTraits.includes(trait.id) ? 'bg-emerald-50 border border-emerald-200' : 'bg-white border hover:bg-slate-50'
                  }`}
                >
                  <div
                    className="flex items-center justify-between cursor-pointer"
                    onClick={() => toggleTrait(trait.id)}
                  >
                    <div className="flex items-center gap-2">
                      <Checkbox checked={selectedTraits.includes(trait.id)} />
                      <span className="font-medium">{trait.name}</span>
                      <span className="text-xs text-muted-foreground">{trait.description}</span>
                    </div>
                    {selectedTraits.includes(trait.id) && (
                      <button
                        onClick={(e) => { e.stopPropagation(); toggleTraitPin(trait.id); }}
                        className={`p-1 rounded ${pinnedTraits.includes(trait.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                      >
                        <Pin className="w-4 h-4" fill={pinnedTraits.includes(trait.id) ? 'currentColor' : 'none'} />
                      </button>
                    )}
                  </div>
                  {selectedTraits.includes(trait.id) && (
                    <div className="flex items-center gap-3 mt-2 pl-6">
                      <Slider
                        value={[traitWeights[trait.id] || 0]}
                        onValueChange={([v]) => setTraitWeights(prev => ({ ...prev, [trait.id]: v }))}
                        max={10}
                        step={1}
                        className="flex-1"
                      />
                      <span className="text-sm font-medium w-8">{traitWeights[trait.id] || 0}점</span>
                    </div>
                  )}
                </div>
              ))}
            </CollapsibleContent>
          </Collapsible>
        </div>

        <div className="flex gap-2">
          <Button className="flex-1">적용</Button>
          <Button variant="outline">초기화</Button>
        </div>
      </CardContent>
    </Card>
  )
}

/**
 * 시안 D: 스텝(단계별) 방식
 */
function OptionD() {
  const [currentStep, setCurrentStep] = useState(1)
  const [selectedGenes, setSelectedGenes] = useState<string[]>(['PLAG1', 'NT5E', 'SCD'])
  const [pinnedGenes, setPinnedGenes] = useState<string[]>(['PLAG1', 'NT5E'])
  const [selectedTraits, setSelectedTraits] = useState<string[]>(['도체중', '등심단면적'])
  const [pinnedTraits, setPinnedTraits] = useState<string[]>(['도체중'])
  const [traitWeights, setTraitWeights] = useState<Record<string, number>>({ '도체중': 7, '등심단면적': 5 })
  const [geneSearch, setGeneSearch] = useState('')
  const [traitSearch, setTraitSearch] = useState('')

  const toggleGene = (geneId: string) => {
    if (selectedGenes.includes(geneId)) {
      setSelectedGenes(prev => prev.filter(g => g !== geneId))
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else {
      setSelectedGenes(prev => [...prev, geneId])
    }
  }

  const toggleGenePin = (geneId: string) => {
    if (pinnedGenes.includes(geneId)) {
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else if (pinnedGenes.length < 5) {
      setPinnedGenes(prev => [...prev, geneId])
    }
  }

  const toggleTrait = (traitId: string) => {
    if (selectedTraits.includes(traitId)) {
      setSelectedTraits(prev => prev.filter(t => t !== traitId))
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
      setTraitWeights(prev => {
        const newWeights = { ...prev }
        delete newWeights[traitId]
        return newWeights
      })
    } else {
      setSelectedTraits(prev => [...prev, traitId])
      setTraitWeights(prev => ({ ...prev, [traitId]: 5 }))
    }
  }

  const toggleTraitPin = (traitId: string) => {
    if (pinnedTraits.includes(traitId)) {
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
    } else if (pinnedTraits.length < 5) {
      setPinnedTraits(prev => [...prev, traitId])
    }
  }

  const allGenes = [...SAMPLE_GENES.quantity, ...SAMPLE_GENES.quality]
  const allTraits = [...SAMPLE_TRAITS.economic, ...SAMPLE_TRAITS.growth, ...SAMPLE_TRAITS.body]

  const filteredGenes = allGenes.filter(g =>
    g.name.toLowerCase().includes(geneSearch.toLowerCase()) ||
    g.description.toLowerCase().includes(geneSearch.toLowerCase())
  )

  const filteredTraits = allTraits.filter(t =>
    t.name.toLowerCase().includes(traitSearch.toLowerCase()) ||
    t.description.toLowerCase().includes(traitSearch.toLowerCase())
  )

  const sortedSelectedGenes = [
    ...pinnedGenes.filter(g => selectedGenes.includes(g)),
    ...selectedGenes.filter(g => !pinnedGenes.includes(g))
  ]
  const sortedSelectedTraits = [
    ...pinnedTraits.filter(t => selectedTraits.includes(t)),
    ...selectedTraits.filter(t => !pinnedTraits.includes(t))
  ]

  return (
    <Card className="bg-white border shadow-sm rounded-2xl">
      <CardHeader className="pb-4">
        <CardTitle className="flex items-center gap-2 text-lg">
          <Filter className="w-5 h-5" />
          시안 D: 스텝(단계별) 방식
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          Step 1: 유전자 선택 → Step 2: 형질 선택 → Step 3: 확인
        </p>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 스텝 인디케이터 */}
        <div className="flex items-center justify-center gap-2">
          {[1, 2, 3].map((step) => (
            <div key={step} className="flex items-center">
              <button
                onClick={() => setCurrentStep(step)}
                className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors ${
                  currentStep === step
                    ? 'bg-blue-500 text-white'
                    : currentStep > step
                    ? 'bg-blue-100 text-blue-600'
                    : 'bg-slate-100 text-slate-400'
                }`}
              >
                {step}
              </button>
              {step < 3 && (
                <div className={`w-12 h-1 mx-1 rounded ${currentStep > step ? 'bg-blue-500' : 'bg-slate-200'}`} />
              )}
            </div>
          ))}
        </div>
        <div className="text-center text-sm text-muted-foreground">
          {currentStep === 1 && '유전자 선택'}
          {currentStep === 2 && '형질 선택'}
          {currentStep === 3 && '최종 확인'}
        </div>

        {/* Step 1: 유전자 선택 */}
        {currentStep === 1 && (
          <div className="space-y-3">
            {/* 선택된 유전자 (고정/순서) */}
            {sortedSelectedGenes.length > 0 && (
              <div className="p-3 bg-blue-50 rounded-lg border border-blue-100 space-y-2">
                <div className="text-xs font-semibold text-blue-600">선택됨 ({sortedSelectedGenes.length}개)</div>
                {sortedSelectedGenes.map(geneId => (
                  <DraggableItem
                    key={geneId}
                    id={geneId}
                    label={geneId}
                    isPinned={pinnedGenes.includes(geneId)}
                    onTogglePin={() => toggleGenePin(geneId)}
                    onRemove={() => toggleGene(geneId)}
                  />
                ))}
              </div>
            )}

            {/* 검색 */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <Input
                placeholder="유전자 검색..."
                className="pl-9"
                value={geneSearch}
                onChange={(e) => setGeneSearch(e.target.value)}
              />
            </div>

            {/* 유전자 목록 */}
            <div className="max-h-64 overflow-y-auto space-y-1 p-1">
              <div className="text-xs font-semibold text-blue-600 py-1">육량형</div>
              {filteredGenes.filter(g => SAMPLE_GENES.quantity.some(q => q.id === g.id)).map(gene => (
                <div
                  key={gene.id}
                  className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                    selectedGenes.includes(gene.id) ? 'bg-blue-100 border border-blue-200' : 'bg-white border hover:bg-slate-50'
                  }`}
                  onClick={() => toggleGene(gene.id)}
                >
                  <div className="flex items-center gap-2">
                    <Checkbox checked={selectedGenes.includes(gene.id)} />
                    <span className="font-medium">{gene.name}</span>
                    <span className="text-xs text-muted-foreground">{gene.description}</span>
                  </div>
                </div>
              ))}
              <div className="text-xs font-semibold text-orange-600 py-1 mt-2">육질형</div>
              {filteredGenes.filter(g => SAMPLE_GENES.quality.some(q => q.id === g.id)).map(gene => (
                <div
                  key={gene.id}
                  className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                    selectedGenes.includes(gene.id) ? 'bg-orange-100 border border-orange-200' : 'bg-white border hover:bg-slate-50'
                  }`}
                  onClick={() => toggleGene(gene.id)}
                >
                  <div className="flex items-center gap-2">
                    <Checkbox checked={selectedGenes.includes(gene.id)} />
                    <span className="font-medium">{gene.name}</span>
                    <span className="text-xs text-muted-foreground">{gene.description}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Step 2: 형질 선택 */}
        {currentStep === 2 && (
          <div className="space-y-3">
            {/* 선택된 형질 (고정/순서/가중치) */}
            {sortedSelectedTraits.length > 0 && (
              <div className="p-3 bg-emerald-50 rounded-lg border border-emerald-100 space-y-2">
                <div className="text-xs font-semibold text-emerald-600">선택됨 ({sortedSelectedTraits.length}개)</div>
                {sortedSelectedTraits.map(traitId => (
                  <DraggableItem
                    key={traitId}
                    id={traitId}
                    label={traitId}
                    isPinned={pinnedTraits.includes(traitId)}
                    onTogglePin={() => toggleTraitPin(traitId)}
                    onRemove={() => toggleTrait(traitId)}
                    showWeight={true}
                    weight={traitWeights[traitId]}
                    onWeightChange={(v) => setTraitWeights(prev => ({ ...prev, [traitId]: v }))}
                  />
                ))}
              </div>
            )}

            {/* 검색 */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <Input
                placeholder="형질 검색..."
                className="pl-9"
                value={traitSearch}
                onChange={(e) => setTraitSearch(e.target.value)}
              />
            </div>

            {/* 형질 목록 */}
            <div className="max-h-64 overflow-y-auto space-y-1 p-1">
              <div className="text-xs font-semibold text-emerald-600 py-1">경제형질</div>
              {filteredTraits.filter(t => SAMPLE_TRAITS.economic.some(e => e.id === t.id)).map(trait => (
                <div
                  key={trait.id}
                  className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                    selectedTraits.includes(trait.id) ? 'bg-emerald-100 border border-emerald-200' : 'bg-white border hover:bg-slate-50'
                  }`}
                  onClick={() => toggleTrait(trait.id)}
                >
                  <div className="flex items-center gap-2">
                    <Checkbox checked={selectedTraits.includes(trait.id)} />
                    <span className="font-medium">{trait.name}</span>
                    <span className="text-xs text-muted-foreground">{trait.description}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Step 3: 최종 확인 */}
        {currentStep === 3 && (
          <div className="space-y-4">
            <div className="p-4 bg-slate-50 rounded-xl border space-y-4">
              <h4 className="font-semibold">최종 선택 확인</h4>

              {/* 유전자 */}
              <div className="space-y-2">
                <div className="flex items-center gap-2 text-sm">
                  <Dna className="w-4 h-4 text-blue-500" />
                  <span className="font-medium">유전자 ({sortedSelectedGenes.length}개)</span>
                </div>
                <div className="space-y-1">
                  {sortedSelectedGenes.map(geneId => (
                    <DraggableItem
                      key={geneId}
                      id={geneId}
                      label={geneId}
                      isPinned={pinnedGenes.includes(geneId)}
                      onTogglePin={() => toggleGenePin(geneId)}
                      onRemove={() => toggleGene(geneId)}
                    />
                  ))}
                </div>
              </div>

              {/* 형질 */}
              <div className="space-y-2">
                <div className="flex items-center gap-2 text-sm">
                  <BarChart3 className="w-4 h-4 text-emerald-500" />
                  <span className="font-medium">형질 ({sortedSelectedTraits.length}개)</span>
                </div>
                <div className="space-y-1">
                  {sortedSelectedTraits.map(traitId => (
                    <DraggableItem
                      key={traitId}
                      id={traitId}
                      label={traitId}
                      isPinned={pinnedTraits.includes(traitId)}
                      onTogglePin={() => toggleTraitPin(traitId)}
                      onRemove={() => toggleTrait(traitId)}
                      showWeight={true}
                      weight={traitWeights[traitId]}
                      onWeightChange={(v) => setTraitWeights(prev => ({ ...prev, [traitId]: v }))}
                    />
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 네비게이션 버튼 */}
        <div className="flex gap-2">
          {currentStep > 1 && (
            <Button variant="outline" onClick={() => setCurrentStep(prev => prev - 1)}>
              <ChevronLeft className="w-4 h-4 mr-1" />
              이전
            </Button>
          )}
          <div className="flex-1" />
          {currentStep < 3 ? (
            <Button onClick={() => setCurrentStep(prev => prev + 1)}>
              다음
              <ChevronRight className="w-4 h-4 ml-1" />
            </Button>
          ) : (
            <Button className="flex-1">적용</Button>
          )}
        </div>
      </CardContent>
    </Card>
  )
}

/**
 * 시안 E: 탭 분리 방식
 */
function OptionE() {
  const [innerTab, setInnerTab] = useState('genes')
  const [selectedGenes, setSelectedGenes] = useState<string[]>(['PLAG1', 'NT5E', 'SCD'])
  const [pinnedGenes, setPinnedGenes] = useState<string[]>(['PLAG1', 'NT5E'])
  const [selectedTraits, setSelectedTraits] = useState<string[]>(['도체중', '등심단면적'])
  const [pinnedTraits, setPinnedTraits] = useState<string[]>(['도체중'])
  const [traitWeights, setTraitWeights] = useState<Record<string, number>>({ '도체중': 7, '등심단면적': 5 })
  const [geneSearch, setGeneSearch] = useState('')
  const [traitSearch, setTraitSearch] = useState('')

  const toggleGene = (geneId: string) => {
    if (selectedGenes.includes(geneId)) {
      setSelectedGenes(prev => prev.filter(g => g !== geneId))
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else {
      setSelectedGenes(prev => [...prev, geneId])
    }
  }

  const toggleGenePin = (geneId: string) => {
    if (pinnedGenes.includes(geneId)) {
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else if (pinnedGenes.length < 5) {
      setPinnedGenes(prev => [...prev, geneId])
    }
  }

  const toggleTrait = (traitId: string) => {
    if (selectedTraits.includes(traitId)) {
      setSelectedTraits(prev => prev.filter(t => t !== traitId))
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
      setTraitWeights(prev => {
        const newWeights = { ...prev }
        delete newWeights[traitId]
        return newWeights
      })
    } else {
      setSelectedTraits(prev => [...prev, traitId])
      setTraitWeights(prev => ({ ...prev, [traitId]: 5 }))
    }
  }

  const toggleTraitPin = (traitId: string) => {
    if (pinnedTraits.includes(traitId)) {
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
    } else if (pinnedTraits.length < 5) {
      setPinnedTraits(prev => [...prev, traitId])
    }
  }

  const allGenes = [...SAMPLE_GENES.quantity, ...SAMPLE_GENES.quality]
  const filteredGenes = allGenes.filter(g =>
    g.name.toLowerCase().includes(geneSearch.toLowerCase()) ||
    g.description.toLowerCase().includes(geneSearch.toLowerCase())
  )

  const allTraits = [...SAMPLE_TRAITS.economic, ...SAMPLE_TRAITS.growth, ...SAMPLE_TRAITS.body]
  const filteredTraits = allTraits.filter(t =>
    t.name.toLowerCase().includes(traitSearch.toLowerCase()) ||
    t.description.toLowerCase().includes(traitSearch.toLowerCase())
  )

  const sortedSelectedGenes = [
    ...pinnedGenes.filter(g => selectedGenes.includes(g)),
    ...selectedGenes.filter(g => !pinnedGenes.includes(g))
  ]
  const sortedSelectedTraits = [
    ...pinnedTraits.filter(t => selectedTraits.includes(t)),
    ...selectedTraits.filter(t => !pinnedTraits.includes(t))
  ]

  return (
    <Card className="bg-white border shadow-sm rounded-2xl">
      <CardHeader className="pb-4">
        <CardTitle className="flex items-center gap-2 text-lg">
          <Filter className="w-5 h-5" />
          시안 E: 탭 분리 방식
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          유전자 / 형질 / 선택조건을 탭으로 분리하여 넓은 공간 활용
        </p>
      </CardHeader>
      <CardContent className="space-y-4">
        <Tabs value={innerTab} onValueChange={setInnerTab}>
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="genes" className="flex items-center gap-1">
              <Dna className="w-4 h-4" />
              유전자
              {selectedGenes.length > 0 && <Badge variant="secondary" className="ml-1">{selectedGenes.length}</Badge>}
            </TabsTrigger>
            <TabsTrigger value="traits" className="flex items-center gap-1">
              <BarChart3 className="w-4 h-4" />
              형질
              {selectedTraits.length > 0 && <Badge variant="secondary" className="ml-1">{selectedTraits.length}</Badge>}
            </TabsTrigger>
            <TabsTrigger value="summary" className="flex items-center gap-1">
              선택조건
            </TabsTrigger>
          </TabsList>

          {/* 유전자 탭 */}
          <TabsContent value="genes" className="mt-4 space-y-3">
            {/* 선택된 유전자 */}
            {sortedSelectedGenes.length > 0 && (
              <div className="p-3 bg-blue-50 rounded-lg border border-blue-100 space-y-2">
                <div className="text-xs font-semibold text-blue-600">선택됨 (드래그로 순서 변경)</div>
                {sortedSelectedGenes.map(geneId => (
                  <DraggableItem
                    key={geneId}
                    id={geneId}
                    label={geneId}
                    isPinned={pinnedGenes.includes(geneId)}
                    onTogglePin={() => toggleGenePin(geneId)}
                    onRemove={() => toggleGene(geneId)}
                  />
                ))}
              </div>
            )}

            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <Input
                placeholder="유전자 검색..."
                className="pl-9"
                value={geneSearch}
                onChange={(e) => setGeneSearch(e.target.value)}
              />
            </div>

            <div className="space-y-1">
              <div className="text-xs font-semibold text-blue-600 py-1">육량형</div>
              {filteredGenes.filter(g => SAMPLE_GENES.quantity.some(q => q.id === g.id)).map(gene => (
                <div
                  key={gene.id}
                  className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                    selectedGenes.includes(gene.id) ? 'bg-blue-100 border border-blue-200' : 'bg-white border hover:bg-slate-50'
                  }`}
                  onClick={() => toggleGene(gene.id)}
                >
                  <div className="flex items-center gap-2">
                    <Checkbox checked={selectedGenes.includes(gene.id)} />
                    <span className="font-medium">{gene.name}</span>
                    <span className="text-xs text-muted-foreground">{gene.description}</span>
                  </div>
                  {selectedGenes.includes(gene.id) && (
                    <button
                      onClick={(e) => { e.stopPropagation(); toggleGenePin(gene.id); }}
                      className={`p-1 rounded ${pinnedGenes.includes(gene.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                    >
                      <Pin className="w-4 h-4" fill={pinnedGenes.includes(gene.id) ? 'currentColor' : 'none'} />
                    </button>
                  )}
                </div>
              ))}
              <div className="text-xs font-semibold text-orange-600 py-1 mt-2">육질형</div>
              {filteredGenes.filter(g => SAMPLE_GENES.quality.some(q => q.id === g.id)).map(gene => (
                <div
                  key={gene.id}
                  className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                    selectedGenes.includes(gene.id) ? 'bg-orange-100 border border-orange-200' : 'bg-white border hover:bg-slate-50'
                  }`}
                  onClick={() => toggleGene(gene.id)}
                >
                  <div className="flex items-center gap-2">
                    <Checkbox checked={selectedGenes.includes(gene.id)} />
                    <span className="font-medium">{gene.name}</span>
                    <span className="text-xs text-muted-foreground">{gene.description}</span>
                  </div>
                  {selectedGenes.includes(gene.id) && (
                    <button
                      onClick={(e) => { e.stopPropagation(); toggleGenePin(gene.id); }}
                      className={`p-1 rounded ${pinnedGenes.includes(gene.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                    >
                      <Pin className="w-4 h-4" fill={pinnedGenes.includes(gene.id) ? 'currentColor' : 'none'} />
                    </button>
                  )}
                </div>
              ))}
            </div>
          </TabsContent>

          {/* 형질 탭 */}
          <TabsContent value="traits" className="mt-4 space-y-3">
            {/* 선택된 형질 */}
            {sortedSelectedTraits.length > 0 && (
              <div className="p-3 bg-emerald-50 rounded-lg border border-emerald-100 space-y-2">
                <div className="text-xs font-semibold text-emerald-600">선택됨 (드래그로 순서 변경)</div>
                {sortedSelectedTraits.map(traitId => (
                  <DraggableItem
                    key={traitId}
                    id={traitId}
                    label={traitId}
                    isPinned={pinnedTraits.includes(traitId)}
                    onTogglePin={() => toggleTraitPin(traitId)}
                    onRemove={() => toggleTrait(traitId)}
                    showWeight={true}
                    weight={traitWeights[traitId]}
                    onWeightChange={(v) => setTraitWeights(prev => ({ ...prev, [traitId]: v }))}
                  />
                ))}
              </div>
            )}

            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <Input
                placeholder="형질 검색..."
                className="pl-9"
                value={traitSearch}
                onChange={(e) => setTraitSearch(e.target.value)}
              />
            </div>

            <div className="space-y-1">
              <div className="text-xs font-semibold text-emerald-600 py-1">경제형질</div>
              {filteredTraits.filter(t => SAMPLE_TRAITS.economic.some(e => e.id === t.id)).map(trait => (
                <div
                  key={trait.id}
                  className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                    selectedTraits.includes(trait.id) ? 'bg-emerald-100 border border-emerald-200' : 'bg-white border hover:bg-slate-50'
                  }`}
                  onClick={() => toggleTrait(trait.id)}
                >
                  <div className="flex items-center gap-2">
                    <Checkbox checked={selectedTraits.includes(trait.id)} />
                    <span className="font-medium">{trait.name}</span>
                    <span className="text-xs text-muted-foreground">{trait.description}</span>
                  </div>
                  {selectedTraits.includes(trait.id) && (
                    <button
                      onClick={(e) => { e.stopPropagation(); toggleTraitPin(trait.id); }}
                      className={`p-1 rounded ${pinnedTraits.includes(trait.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                    >
                      <Pin className="w-4 h-4" fill={pinnedTraits.includes(trait.id) ? 'currentColor' : 'none'} />
                    </button>
                  )}
                </div>
              ))}
              <div className="text-xs font-semibold text-purple-600 py-1 mt-2">성장형질</div>
              {filteredTraits.filter(t => SAMPLE_TRAITS.growth.some(g => g.id === t.id)).map(trait => (
                <div
                  key={trait.id}
                  className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                    selectedTraits.includes(trait.id) ? 'bg-purple-100 border border-purple-200' : 'bg-white border hover:bg-slate-50'
                  }`}
                  onClick={() => toggleTrait(trait.id)}
                >
                  <div className="flex items-center gap-2">
                    <Checkbox checked={selectedTraits.includes(trait.id)} />
                    <span className="font-medium">{trait.name}</span>
                    <span className="text-xs text-muted-foreground">{trait.description}</span>
                  </div>
                  {selectedTraits.includes(trait.id) && (
                    <button
                      onClick={(e) => { e.stopPropagation(); toggleTraitPin(trait.id); }}
                      className={`p-1 rounded ${pinnedTraits.includes(trait.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                    >
                      <Pin className="w-4 h-4" fill={pinnedTraits.includes(trait.id) ? 'currentColor' : 'none'} />
                    </button>
                  )}
                </div>
              ))}
              <div className="text-xs font-semibold text-cyan-600 py-1 mt-2">체형형질</div>
              {filteredTraits.filter(t => SAMPLE_TRAITS.body.some(b => b.id === t.id)).map(trait => (
                <div
                  key={trait.id}
                  className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                    selectedTraits.includes(trait.id) ? 'bg-cyan-100 border border-cyan-200' : 'bg-white border hover:bg-slate-50'
                  }`}
                  onClick={() => toggleTrait(trait.id)}
                >
                  <div className="flex items-center gap-2">
                    <Checkbox checked={selectedTraits.includes(trait.id)} />
                    <span className="font-medium">{trait.name}</span>
                    <span className="text-xs text-muted-foreground">{trait.description}</span>
                  </div>
                  {selectedTraits.includes(trait.id) && (
                    <button
                      onClick={(e) => { e.stopPropagation(); toggleTraitPin(trait.id); }}
                      className={`p-1 rounded ${pinnedTraits.includes(trait.id) ? 'text-amber-500' : 'text-slate-400 hover:text-amber-500'}`}
                    >
                      <Pin className="w-4 h-4" fill={pinnedTraits.includes(trait.id) ? 'currentColor' : 'none'} />
                    </button>
                  )}
                </div>
              ))}
            </div>
          </TabsContent>

          {/* 선택조건 탭 */}
          <TabsContent value="summary" className="mt-4 space-y-3">
            <div className="p-4 bg-slate-50 rounded-xl border space-y-4">
              <h4 className="font-semibold">선택한 필터 조건</h4>

              {/* 유전자 */}
              {sortedSelectedGenes.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm">
                    <Dna className="w-4 h-4 text-blue-500" />
                    <span className="font-medium">유전자 ({sortedSelectedGenes.length}개)</span>
                  </div>
                  <div className="space-y-1">
                    {sortedSelectedGenes.map(geneId => (
                      <DraggableItem
                        key={geneId}
                        id={geneId}
                        label={geneId}
                        isPinned={pinnedGenes.includes(geneId)}
                        onTogglePin={() => toggleGenePin(geneId)}
                        onRemove={() => toggleGene(geneId)}
                      />
                    ))}
                  </div>
                </div>
              )}

              {/* 형질 */}
              {sortedSelectedTraits.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm">
                    <BarChart3 className="w-4 h-4 text-emerald-500" />
                    <span className="font-medium">형질 ({sortedSelectedTraits.length}개)</span>
                  </div>
                  <div className="space-y-1">
                    {sortedSelectedTraits.map(traitId => (
                      <DraggableItem
                        key={traitId}
                        id={traitId}
                        label={traitId}
                        isPinned={pinnedTraits.includes(traitId)}
                        onTogglePin={() => toggleTraitPin(traitId)}
                        onRemove={() => toggleTrait(traitId)}
                        showWeight={true}
                        weight={traitWeights[traitId]}
                        onWeightChange={(v) => setTraitWeights(prev => ({ ...prev, [traitId]: v }))}
                      />
                    ))}
                  </div>
                </div>
              )}

              {sortedSelectedGenes.length === 0 && sortedSelectedTraits.length === 0 && (
                <div className="text-center text-muted-foreground py-4">
                  선택된 필터 조건이 없습니다
                </div>
              )}
            </div>
          </TabsContent>
        </Tabs>

        <div className="flex gap-2">
          <Button className="flex-1">적용</Button>
          <Button variant="outline">초기화</Button>
        </div>
      </CardContent>
    </Card>
  )
}

/**
 * 시안 H: 칩(Chip) 기반 방식
 * 태그/칩 형태로 선택 항목을 표시하고 관리
 */
function OptionH() {
  const [selectedGenes, setSelectedGenes] = useState<string[]>(['PLAG1', 'NT5E', 'SCD'])
  const [pinnedGenes, setPinnedGenes] = useState<string[]>(['PLAG1', 'NT5E'])
  const [selectedTraits, setSelectedTraits] = useState<string[]>(['도체중', '등심단면적'])
  const [pinnedTraits, setPinnedTraits] = useState<string[]>(['도체중'])
  const [traitWeights, setTraitWeights] = useState<Record<string, number>>({ '도체중': 7, '등심단면적': 5 })
  const [showGeneSelector, setShowGeneSelector] = useState(false)
  const [showTraitSelector, setShowTraitSelector] = useState(false)
  const [geneSearch, setGeneSearch] = useState('')
  const [traitSearch, setTraitSearch] = useState('')

  const toggleGene = (geneId: string) => {
    if (selectedGenes.includes(geneId)) {
      setSelectedGenes(prev => prev.filter(g => g !== geneId))
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else {
      setSelectedGenes(prev => [...prev, geneId])
    }
  }

  const toggleGenePin = (geneId: string) => {
    if (pinnedGenes.includes(geneId)) {
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else if (pinnedGenes.length < 5) {
      setPinnedGenes(prev => [...prev, geneId])
    }
  }

  const toggleTrait = (traitId: string) => {
    if (selectedTraits.includes(traitId)) {
      setSelectedTraits(prev => prev.filter(t => t !== traitId))
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
      setTraitWeights(prev => {
        const newWeights = { ...prev }
        delete newWeights[traitId]
        return newWeights
      })
    } else {
      setSelectedTraits(prev => [...prev, traitId])
      setTraitWeights(prev => ({ ...prev, [traitId]: 5 }))
    }
  }

  const toggleTraitPin = (traitId: string) => {
    if (pinnedTraits.includes(traitId)) {
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
    } else if (pinnedTraits.length < 5) {
      setPinnedTraits(prev => [...prev, traitId])
    }
  }

  const allGenes = [...SAMPLE_GENES.quantity, ...SAMPLE_GENES.quality]
  const filteredGenes = allGenes.filter(g =>
    g.name.toLowerCase().includes(geneSearch.toLowerCase()) ||
    g.description.toLowerCase().includes(geneSearch.toLowerCase())
  )

  const allTraits = [...SAMPLE_TRAITS.economic, ...SAMPLE_TRAITS.growth, ...SAMPLE_TRAITS.body]
  const filteredTraits = allTraits.filter(t =>
    t.name.toLowerCase().includes(traitSearch.toLowerCase()) ||
    t.description.toLowerCase().includes(traitSearch.toLowerCase())
  )

  // 고정된 것 먼저 정렬
  const sortedSelectedGenes = [
    ...pinnedGenes.filter(g => selectedGenes.includes(g)),
    ...selectedGenes.filter(g => !pinnedGenes.includes(g))
  ]
  const sortedSelectedTraits = [
    ...pinnedTraits.filter(t => selectedTraits.includes(t)),
    ...selectedTraits.filter(t => !pinnedTraits.includes(t))
  ]

  return (
    <Card className="bg-white border shadow-sm rounded-2xl">
      <CardHeader className="pb-4">
        <CardTitle className="flex items-center gap-2 text-lg">
          <Filter className="w-5 h-5" />
          시안 H: 칩(Chip) 기반 방식
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          태그/칩 형태로 선택 항목 표시 + 추가 버튼으로 새 항목 선택
        </p>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 유전자 칩 영역 */}
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <h4 className="font-semibold text-foreground flex items-center gap-2">
              <Dna className="w-4 h-4 text-blue-500" />
              유전자
            </h4>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowGeneSelector(!showGeneSelector)}
              className="h-7"
            >
              <Plus className="w-3 h-3 mr-1" />
              추가
            </Button>
          </div>

          {/* 선택된 유전자 칩 */}
          <div className="flex flex-wrap gap-2 min-h-[40px] p-2 bg-slate-50 rounded-lg border">
            {sortedSelectedGenes.length === 0 ? (
              <span className="text-sm text-muted-foreground">유전자를 선택해주세요</span>
            ) : (
              sortedSelectedGenes.map(geneId => {
                const isPinned = pinnedGenes.includes(geneId)
                const isQuantity = SAMPLE_GENES.quantity.some(g => g.id === geneId)
                return (
                  <div
                    key={geneId}
                    className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-sm font-medium transition-colors cursor-grab ${
                      isPinned
                        ? 'bg-amber-100 text-amber-800 border border-amber-300'
                        : isQuantity
                        ? 'bg-blue-100 text-blue-800 border border-blue-200'
                        : 'bg-orange-100 text-orange-800 border border-orange-200'
                    }`}
                  >
                    <GripVertical className="w-3 h-3 opacity-50" />
                    {isPinned && <Pin className="w-3 h-3" fill="currentColor" />}
                    <span>{geneId}</span>
                    <button
                      onClick={() => toggleGenePin(geneId)}
                      className={`p-0.5 rounded hover:bg-black/10 ${isPinned ? '' : 'opacity-50 hover:opacity-100'}`}
                      title={isPinned ? '고정 해제' : '고정'}
                    >
                      <Pin className="w-3 h-3" fill={isPinned ? 'currentColor' : 'none'} />
                    </button>
                    <button
                      onClick={() => toggleGene(geneId)}
                      className="p-0.5 rounded hover:bg-black/10"
                    >
                      <X className="w-3 h-3" />
                    </button>
                  </div>
                )
              })
            )}
          </div>

          {/* 유전자 선택 패널 */}
          {showGeneSelector && (
            <div className="p-3 bg-white rounded-lg border shadow-lg space-y-2">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                <Input
                  placeholder="유전자 검색..."
                  className="pl-9 h-9"
                  value={geneSearch}
                  onChange={(e) => setGeneSearch(e.target.value)}
                />
              </div>
              <div className="max-h-48 overflow-y-auto space-y-1">
                <div className="text-xs font-semibold text-blue-600 py-1">육량형</div>
                {filteredGenes.filter(g => SAMPLE_GENES.quantity.some(q => q.id === g.id)).map(gene => (
                  <div
                    key={gene.id}
                    className={`flex items-center gap-2 p-2 rounded cursor-pointer transition-colors ${
                      selectedGenes.includes(gene.id) ? 'bg-blue-100' : 'hover:bg-slate-50'
                    }`}
                    onClick={() => toggleGene(gene.id)}
                  >
                    <Checkbox checked={selectedGenes.includes(gene.id)} />
                    <span className="font-medium">{gene.name}</span>
                    <span className="text-xs text-muted-foreground">{gene.description}</span>
                  </div>
                ))}
                <div className="text-xs font-semibold text-orange-600 py-1 mt-2">육질형</div>
                {filteredGenes.filter(g => SAMPLE_GENES.quality.some(q => q.id === g.id)).map(gene => (
                  <div
                    key={gene.id}
                    className={`flex items-center gap-2 p-2 rounded cursor-pointer transition-colors ${
                      selectedGenes.includes(gene.id) ? 'bg-orange-100' : 'hover:bg-slate-50'
                    }`}
                    onClick={() => toggleGene(gene.id)}
                  >
                    <Checkbox checked={selectedGenes.includes(gene.id)} />
                    <span className="font-medium">{gene.name}</span>
                    <span className="text-xs text-muted-foreground">{gene.description}</span>
                  </div>
                ))}
              </div>
              <Button
                variant="outline"
                size="sm"
                className="w-full"
                onClick={() => setShowGeneSelector(false)}
              >
                닫기
              </Button>
            </div>
          )}
        </div>

        {/* 형질 칩 영역 */}
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <h4 className="font-semibold text-foreground flex items-center gap-2">
              <BarChart3 className="w-4 h-4 text-emerald-500" />
              형질
            </h4>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowTraitSelector(!showTraitSelector)}
              className="h-7"
            >
              <Plus className="w-3 h-3 mr-1" />
              추가
            </Button>
          </div>

          {/* 선택된 형질 칩 */}
          <div className="flex flex-wrap gap-2 min-h-[40px] p-2 bg-slate-50 rounded-lg border">
            {sortedSelectedTraits.length === 0 ? (
              <span className="text-sm text-muted-foreground">형질을 선택해주세요</span>
            ) : (
              sortedSelectedTraits.map(traitId => {
                const isPinned = pinnedTraits.includes(traitId)
                return (
                  <div
                    key={traitId}
                    className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-sm font-medium transition-colors cursor-grab ${
                      isPinned
                        ? 'bg-amber-100 text-amber-800 border border-amber-300'
                        : 'bg-emerald-100 text-emerald-800 border border-emerald-200'
                    }`}
                  >
                    <GripVertical className="w-3 h-3 opacity-50" />
                    {isPinned && <Pin className="w-3 h-3" fill="currentColor" />}
                    <span>{traitId}</span>
                    <span className="text-xs opacity-70">({traitWeights[traitId] || 0}점)</span>
                    <button
                      onClick={() => toggleTraitPin(traitId)}
                      className={`p-0.5 rounded hover:bg-black/10 ${isPinned ? '' : 'opacity-50 hover:opacity-100'}`}
                      title={isPinned ? '고정 해제' : '고정'}
                    >
                      <Pin className="w-3 h-3" fill={isPinned ? 'currentColor' : 'none'} />
                    </button>
                    <button
                      onClick={() => toggleTrait(traitId)}
                      className="p-0.5 rounded hover:bg-black/10"
                    >
                      <X className="w-3 h-3" />
                    </button>
                  </div>
                )
              })
            )}
          </div>

          {/* 형질 가중치 조절 */}
          {sortedSelectedTraits.length > 0 && (
            <div className="p-3 bg-emerald-50 rounded-lg border border-emerald-100 space-y-2">
              <div className="text-xs font-semibold text-emerald-600">가중치 조절</div>
              {sortedSelectedTraits.map(traitId => (
                <div key={traitId} className="flex items-center gap-2">
                  <span className="text-sm font-medium w-24">{traitId}</span>
                  <Slider
                    value={[traitWeights[traitId] || 0]}
                    onValueChange={([v]) => setTraitWeights(prev => ({ ...prev, [traitId]: v }))}
                    max={10}
                    step={1}
                    className="flex-1"
                  />
                  <span className="text-sm w-8">{traitWeights[traitId] || 0}점</span>
                </div>
              ))}
            </div>
          )}

          {/* 형질 선택 패널 */}
          {showTraitSelector && (
            <div className="p-3 bg-white rounded-lg border shadow-lg space-y-2">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                <Input
                  placeholder="형질 검색..."
                  className="pl-9 h-9"
                  value={traitSearch}
                  onChange={(e) => setTraitSearch(e.target.value)}
                />
              </div>
              <div className="max-h-48 overflow-y-auto space-y-1">
                <div className="text-xs font-semibold text-emerald-600 py-1">경제형질</div>
                {filteredTraits.filter(t => SAMPLE_TRAITS.economic.some(e => e.id === t.id)).map(trait => (
                  <div
                    key={trait.id}
                    className={`flex items-center gap-2 p-2 rounded cursor-pointer transition-colors ${
                      selectedTraits.includes(trait.id) ? 'bg-emerald-100' : 'hover:bg-slate-50'
                    }`}
                    onClick={() => toggleTrait(trait.id)}
                  >
                    <Checkbox checked={selectedTraits.includes(trait.id)} />
                    <span className="font-medium">{trait.name}</span>
                    <span className="text-xs text-muted-foreground">{trait.description}</span>
                  </div>
                ))}
                <div className="text-xs font-semibold text-purple-600 py-1 mt-2">성장형질</div>
                {filteredTraits.filter(t => SAMPLE_TRAITS.growth.some(g => g.id === t.id)).map(trait => (
                  <div
                    key={trait.id}
                    className={`flex items-center gap-2 p-2 rounded cursor-pointer transition-colors ${
                      selectedTraits.includes(trait.id) ? 'bg-purple-100' : 'hover:bg-slate-50'
                    }`}
                    onClick={() => toggleTrait(trait.id)}
                  >
                    <Checkbox checked={selectedTraits.includes(trait.id)} />
                    <span className="font-medium">{trait.name}</span>
                    <span className="text-xs text-muted-foreground">{trait.description}</span>
                  </div>
                ))}
                <div className="text-xs font-semibold text-cyan-600 py-1 mt-2">체형형질</div>
                {filteredTraits.filter(t => SAMPLE_TRAITS.body.some(b => b.id === t.id)).map(trait => (
                  <div
                    key={trait.id}
                    className={`flex items-center gap-2 p-2 rounded cursor-pointer transition-colors ${
                      selectedTraits.includes(trait.id) ? 'bg-cyan-100' : 'hover:bg-slate-50'
                    }`}
                    onClick={() => toggleTrait(trait.id)}
                  >
                    <Checkbox checked={selectedTraits.includes(trait.id)} />
                    <span className="font-medium">{trait.name}</span>
                    <span className="text-xs text-muted-foreground">{trait.description}</span>
                  </div>
                ))}
              </div>
              <Button
                variant="outline"
                size="sm"
                className="w-full"
                onClick={() => setShowTraitSelector(false)}
              >
                닫기
              </Button>
            </div>
          )}
        </div>

        <div className="flex gap-2">
          <Button className="flex-1">적용</Button>
          <Button variant="outline">초기화</Button>
        </div>
      </CardContent>
    </Card>
  )
}

/**
 * 시안 F: 모달 선택 방식 (추천)
 * 평소엔 선택 결과만 보이고, 클릭하면 모달/패널에서 선택
 */
function OptionF() {
  const [selectedGenes, setSelectedGenes] = useState<string[]>(['PLAG1', 'NT5E', 'SCD'])
  const [pinnedGenes, setPinnedGenes] = useState<string[]>(['PLAG1', 'NT5E'])
  const [selectedTraits, setSelectedTraits] = useState<string[]>(['도체중', '등심단면적'])
  const [pinnedTraits, setPinnedTraits] = useState<string[]>(['도체중'])
  const [traitWeights, setTraitWeights] = useState<Record<string, number>>({ '도체중': 7, '등심단면적': 5 })

  const [showGeneModal, setShowGeneModal] = useState(false)
  const [showTraitModal, setShowTraitModal] = useState(false)
  const [geneSearch, setGeneSearch] = useState('')
  const [traitSearch, setTraitSearch] = useState('')
  const [activeGeneCategory, setActiveGeneCategory] = useState<string | null>(null)
  const [activeTraitCategory, setActiveTraitCategory] = useState<string | null>(null)
  const [openCategories, setOpenCategories] = useState<Record<string, boolean>>({})

  const toggleGene = (geneId: string) => {
    if (selectedGenes.includes(geneId)) {
      setSelectedGenes(prev => prev.filter(g => g !== geneId))
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else {
      setSelectedGenes(prev => [...prev, geneId])
    }
  }

  const toggleGenePin = (geneId: string) => {
    if (pinnedGenes.includes(geneId)) {
      setPinnedGenes(prev => prev.filter(g => g !== geneId))
    } else if (pinnedGenes.length < 5) {
      setPinnedGenes(prev => [...prev, geneId])
    }
  }

  const toggleTrait = (traitId: string) => {
    if (selectedTraits.includes(traitId)) {
      setSelectedTraits(prev => prev.filter(t => t !== traitId))
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
      setTraitWeights(prev => {
        const newWeights = { ...prev }
        delete newWeights[traitId]
        return newWeights
      })
    } else {
      setSelectedTraits(prev => [...prev, traitId])
      setTraitWeights(prev => ({ ...prev, [traitId]: 5 }))
    }
  }

  const toggleTraitPin = (traitId: string) => {
    if (pinnedTraits.includes(traitId)) {
      setPinnedTraits(prev => prev.filter(t => t !== traitId))
    } else if (pinnedTraits.length < 5) {
      setPinnedTraits(prev => [...prev, traitId])
    }
  }

  const allGenes = [...SAMPLE_GENES.quantity, ...SAMPLE_GENES.quality]
  const allTraits = [...SAMPLE_TRAITS.growth, ...SAMPLE_TRAITS.economic, ...SAMPLE_TRAITS.body, ...SAMPLE_TRAITS.weight, ...SAMPLE_TRAITS.rate]

  // 형질 카테고리 정보
  const traitCategories = [
    { id: 'growth', name: '성장형질', color: 'purple', traits: SAMPLE_TRAITS.growth },
    { id: 'economic', name: '경제형질', color: 'emerald', traits: SAMPLE_TRAITS.economic },
    { id: 'body', name: '체형형질', color: 'cyan', traits: SAMPLE_TRAITS.body },
    { id: 'weight', name: '부위별무게', color: 'amber', traits: SAMPLE_TRAITS.weight },
    { id: 'rate', name: '부위별비율', color: 'rose', traits: SAMPLE_TRAITS.rate },
  ]

  // 카테고리 필터링
  const getFilteredGenes = () => {
    let genes = allGenes
    if (activeGeneCategory === 'quantity') {
      genes = SAMPLE_GENES.quantity
    } else if (activeGeneCategory === 'quality') {
      genes = SAMPLE_GENES.quality
    }
    if (geneSearch) {
      genes = genes.filter(g =>
        g.name.toLowerCase().includes(geneSearch.toLowerCase()) ||
        g.description.toLowerCase().includes(geneSearch.toLowerCase())
      )
    }
    return genes
  }

  const getFilteredTraits = () => {
    const category = traitCategories.find(c => c.id === activeTraitCategory)
    let traits = category ? category.traits : allTraits
    if (traitSearch) {
      traits = traits.filter(t =>
        t.name.toLowerCase().includes(traitSearch.toLowerCase()) ||
        t.description.toLowerCase().includes(traitSearch.toLowerCase())
      )
    }
    return traits
  }

  // 형질이 어떤 카테고리에 속하는지 찾기
  const getTraitCategory = (traitId: string) => {
    for (const cat of traitCategories) {
      if (cat.traits.some(t => t.id === traitId)) {
        return cat
      }
    }
    return null
  }

  // 정렬: 고정된 것 먼저
  const sortedSelectedGenes = [
    ...pinnedGenes.filter(g => selectedGenes.includes(g)),
    ...selectedGenes.filter(g => !pinnedGenes.includes(g))
  ]
  const sortedSelectedTraits = [
    ...pinnedTraits.filter(t => selectedTraits.includes(t)),
    ...selectedTraits.filter(t => !pinnedTraits.includes(t))
  ]

  return (
    <Card className="bg-white border shadow-sm rounded-2xl">
      <CardHeader className="pb-4">
        <CardTitle className="flex items-center gap-2 text-lg">
          <Filter className="w-5 h-5" />
          시안 F: 모달 선택 방식 (추천)
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          평소엔 선택 결과만 보이고, 클릭하면 모달에서 카테고리/검색으로 선택
        </p>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 유전자 선택 버튼 */}
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <h4 className="font-semibold text-foreground flex items-center gap-2">
              <Dna className="w-4 h-4 text-blue-500" />
              유전자
            </h4>
          </div>
          <button
            onClick={() => setShowGeneModal(true)}
            className="w-full p-3 border-2 border-dashed border-slate-300 rounded-lg text-slate-500 hover:border-blue-400 hover:text-blue-500 hover:bg-blue-50 transition-colors flex items-center justify-center gap-2"
          >
            <Plus className="w-4 h-4" />
            {selectedGenes.length > 0 ? `유전자 수정 (${selectedGenes.length}개 선택됨)` : '유전자를 선택해주세요'}
          </button>
        </div>

        {/* 유전체 형질 선택 버튼 */}
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <h4 className="font-semibold text-foreground flex items-center gap-2">
              <BarChart3 className="w-4 h-4 text-emerald-500" />
              유전체 형질
            </h4>
          </div>
          <button
            onClick={() => setShowTraitModal(true)}
            className="w-full p-3 border-2 border-dashed border-slate-300 rounded-lg text-slate-500 hover:border-emerald-400 hover:text-emerald-500 hover:bg-emerald-50 transition-colors flex items-center justify-center gap-2"
          >
            <Plus className="w-4 h-4" />
            {selectedTraits.length > 0 ? `형질 수정 (${selectedTraits.length}개 선택됨)` : '형질을 선택해주세요'}
          </button>
        </div>

        {/* 선택한 조건 표시 */}
        <div className="p-4 bg-slate-50 rounded-xl border space-y-4">
          <h4 className="font-semibold text-foreground">
            선택한 조건 ({selectedGenes.length + selectedTraits.length}개)
          </h4>

          {/* 유전자 */}
          {sortedSelectedGenes.length > 0 && (
            <div className="space-y-2">
              <div className="text-sm font-medium">유전자</div>
              <div className="flex flex-wrap gap-2">
                {sortedSelectedGenes.map(geneId => {
                  const isPinned = pinnedGenes.includes(geneId)
                  return (
                    <div
                      key={geneId}
                      className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-sm font-medium bg-slate-100 text-slate-700 border border-slate-200"
                    >
                      {isPinned && <Pin className="w-4 h-4" fill="currentColor" />}
                      <span>{geneId}</span>
                      <button
                        onClick={() => toggleGenePin(geneId)}
                        className="p-0.5 rounded hover:bg-black/10"
                        title={isPinned ? '고정 해제' : '고정 (최대 5개)'}
                      >
                        <Pin className="w-4 h-4" fill={isPinned ? 'currentColor' : 'none'} />
                      </button>
                      <button
                        onClick={() => toggleGene(geneId)}
                        className="p-0.5 rounded hover:bg-black/10"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </div>
                  )
                })}
              </div>
            </div>
          )}

          {/* 유전체 형질 */}
          {sortedSelectedTraits.length > 0 && (
            <div className="space-y-2">
              <div className="text-sm font-medium">유전체 형질</div>
              <div className="flex flex-wrap gap-2">
                {sortedSelectedTraits.map(traitId => {
                  const isPinned = pinnedTraits.includes(traitId)
                  return (
                    <div
                      key={traitId}
                      className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-sm font-medium bg-slate-100 text-slate-700 border border-slate-200"
                    >
                      {isPinned && <Pin className="w-4 h-4" fill="currentColor" />}
                      <span>{traitId}</span>
                      <span className="text-xs opacity-70">({traitWeights[traitId]}점)</span>
                      <button
                        onClick={() => toggleTraitPin(traitId)}
                        className="p-0.5 rounded hover:bg-black/10"
                        title={isPinned ? '고정 해제' : '고정 (최대 5개)'}
                      >
                        <Pin className="w-4 h-4" fill={isPinned ? 'currentColor' : 'none'} />
                      </button>
                      <button
                        onClick={() => toggleTrait(traitId)}
                        className="p-0.5 rounded hover:bg-black/10"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </div>
                  )
                })}
              </div>

              {/* 가중치 조절 */}
              <div className="mt-3 p-3 bg-white rounded-lg border space-y-2">
                <div className="text-xs font-semibold text-slate-600">가중치 조절</div>
                {sortedSelectedTraits.map(traitId => (
                  <div key={traitId} className="flex items-center justify-between">
                    <span className="text-sm font-medium truncate flex-1">{traitId}</span>
                    <div className="flex items-center gap-1">
                      <Button
                        variant="outline"
                        size="sm"
                        className="h-7 w-7 p-0"
                        onClick={() => {
                          const current = traitWeights[traitId] || 0
                          if (current > 0) {
                            setTraitWeights(prev => ({ ...prev, [traitId]: current - 1 }))
                          }
                        }}
                        disabled={(traitWeights[traitId] || 0) <= 0}
                      >
                        -
                      </Button>
                      <span className="text-sm font-bold w-8 text-center">{traitWeights[traitId] || 0}점</span>
                      <Button
                        variant="outline"
                        size="sm"
                        className="h-7 w-7 p-0"
                        onClick={() => {
                          const current = traitWeights[traitId] || 0
                          if (current < 10) {
                            setTraitWeights(prev => ({ ...prev, [traitId]: current + 1 }))
                          }
                        }}
                        disabled={(traitWeights[traitId] || 0) >= 10}
                      >
                        +
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {selectedGenes.length === 0 && selectedTraits.length === 0 && (
            <div className="text-center text-muted-foreground py-4">
              선택된 조건이 없습니다
            </div>
          )}
        </div>

        <div className="flex gap-2">
          <Button className="flex-1">적용</Button>
          <Button variant="outline">초기화</Button>
        </div>

        {/* 유전자 선택 모달 */}
        {showGeneModal && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-2xl w-full max-w-lg max-h-[80vh] flex flex-col">
              <div className="flex items-center justify-between p-4 border-b">
                <h3 className="font-semibold text-lg">유전자 선택</h3>
                <button
                  onClick={() => setShowGeneModal(false)}
                  className="p-2 hover:bg-slate-100 rounded-lg"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <div className="p-4 space-y-3 flex-1 overflow-y-auto">
                {/* 검색창 */}
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    placeholder="유전자 검색..."
                    className="pl-9"
                    value={geneSearch}
                    onChange={(e) => setGeneSearch(e.target.value)}
                  />
                </div>

                {/* 유전자 목록 - 카테고리별 아코디언 */}
                <div className="space-y-2">
                  {/* 육량형 */}
                  {(() => {
                    const genes = SAMPLE_GENES.quantity
                    const selectedCount = genes.filter(g => selectedGenes.includes(g.id)).length
                    const isAllSelected = selectedCount === genes.length
                    const hasSelected = selectedCount > 0

                    // 검색어가 카테고리 이름과 매칭되는지 확인
                    const isCategoryMatch = geneSearch && '육량형'.includes(geneSearch.toLowerCase())

                    // 검색 필터링
                    const filteredGenes = geneSearch
                      ? isCategoryMatch
                        ? genes
                        : genes.filter(g =>
                            g.name.toLowerCase().includes(geneSearch.toLowerCase()) ||
                            g.description.toLowerCase().includes(geneSearch.toLowerCase())
                          )
                      : genes

                    if (geneSearch && filteredGenes.length === 0) return null

                    const isExpanded = geneSearch ? true : (openCategories['quantity'] ?? false)

                    return (
                      <Collapsible
                        open={isExpanded}
                        onOpenChange={(open) => setOpenCategories(prev => ({ ...prev, quantity: open }))}
                      >
                        <div className={`rounded-lg border ${hasSelected ? 'border-blue-200 bg-blue-50' : 'border-slate-200 bg-slate-50'}`}>
                          <div className="flex items-center justify-between p-3">
                            <div className="flex items-center gap-2">
                              <Checkbox
                                checked={isAllSelected}
                                onCheckedChange={(checked) => {
                                  if (checked) {
                                    const newGenes = [...selectedGenes]
                                    genes.forEach(g => {
                                      if (!newGenes.includes(g.id)) newGenes.push(g.id)
                                    })
                                    setSelectedGenes(newGenes)
                                  } else {
                                    setSelectedGenes(prev => prev.filter(id => !genes.some(g => g.id === id)))
                                    setPinnedGenes(prev => prev.filter(id => !genes.some(g => g.id === id)))
                                  }
                                }}
                                className="h-4 w-4"
                              />
                              <span className={`font-semibold text-sm ${hasSelected ? 'text-blue-700' : 'text-slate-700'}`}>
                                육량형
                              </span>
                              <Badge variant="secondary" className={`text-xs ${hasSelected ? 'bg-blue-100 text-blue-700' : ''}`}>
                                {selectedCount}/{genes.length}
                              </Badge>
                            </div>
                            <CollapsibleTrigger asChild>
                              <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                                {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                              </Button>
                            </CollapsibleTrigger>
                          </div>
                          <CollapsibleContent>
                            <div className="px-3 pb-3 space-y-1">
                              {filteredGenes.map(gene => {
                                const isSelected = selectedGenes.includes(gene.id)
                                return (
                                  <div
                                    key={gene.id}
                                    className={`p-2 rounded-lg transition-colors cursor-pointer ${
                                      isSelected ? 'bg-white border border-blue-200' : 'hover:bg-white/50'
                                    }`}
                                    onClick={() => toggleGene(gene.id)}
                                  >
                                    <div className="flex items-center gap-3">
                                      <Checkbox checked={isSelected} />
                                      <div className="flex-1">
                                        <span className="font-medium text-sm">{gene.name}</span>
                                        <span className="text-xs text-muted-foreground ml-2">{gene.description}</span>
                                      </div>
                                    </div>
                                  </div>
                                )
                              })}
                            </div>
                          </CollapsibleContent>
                        </div>
                      </Collapsible>
                    )
                  })()}

                  {/* 육질형 */}
                  {(() => {
                    const genes = SAMPLE_GENES.quality
                    const selectedCount = genes.filter(g => selectedGenes.includes(g.id)).length
                    const isAllSelected = selectedCount === genes.length
                    const hasSelected = selectedCount > 0

                    const isCategoryMatch = geneSearch && '육질형'.includes(geneSearch.toLowerCase())

                    const filteredGenes = geneSearch
                      ? isCategoryMatch
                        ? genes
                        : genes.filter(g =>
                            g.name.toLowerCase().includes(geneSearch.toLowerCase()) ||
                            g.description.toLowerCase().includes(geneSearch.toLowerCase())
                          )
                      : genes

                    if (geneSearch && filteredGenes.length === 0) return null

                    const isExpanded = geneSearch ? true : (openCategories['quality'] ?? false)

                    return (
                      <Collapsible
                        open={isExpanded}
                        onOpenChange={(open) => setOpenCategories(prev => ({ ...prev, quality: open }))}
                      >
                        <div className={`rounded-lg border ${hasSelected ? 'border-orange-200 bg-orange-50' : 'border-slate-200 bg-slate-50'}`}>
                          <div className="flex items-center justify-between p-3">
                            <div className="flex items-center gap-2">
                              <Checkbox
                                checked={isAllSelected}
                                onCheckedChange={(checked) => {
                                  if (checked) {
                                    const newGenes = [...selectedGenes]
                                    genes.forEach(g => {
                                      if (!newGenes.includes(g.id)) newGenes.push(g.id)
                                    })
                                    setSelectedGenes(newGenes)
                                  } else {
                                    setSelectedGenes(prev => prev.filter(id => !genes.some(g => g.id === id)))
                                    setPinnedGenes(prev => prev.filter(id => !genes.some(g => g.id === id)))
                                  }
                                }}
                                className="h-4 w-4"
                              />
                              <span className={`font-semibold text-sm ${hasSelected ? 'text-orange-700' : 'text-slate-700'}`}>
                                육질형
                              </span>
                              <Badge variant="secondary" className={`text-xs ${hasSelected ? 'bg-orange-100 text-orange-700' : ''}`}>
                                {selectedCount}/{genes.length}
                              </Badge>
                            </div>
                            <CollapsibleTrigger asChild>
                              <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                                {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                              </Button>
                            </CollapsibleTrigger>
                          </div>
                          <CollapsibleContent>
                            <div className="px-3 pb-3 space-y-1">
                              {filteredGenes.map(gene => {
                                const isSelected = selectedGenes.includes(gene.id)
                                return (
                                  <div
                                    key={gene.id}
                                    className={`p-2 rounded-lg transition-colors cursor-pointer ${
                                      isSelected ? 'bg-white border border-orange-200' : 'hover:bg-white/50'
                                    }`}
                                    onClick={() => toggleGene(gene.id)}
                                  >
                                    <div className="flex items-center gap-3">
                                      <Checkbox checked={isSelected} />
                                      <div className="flex-1">
                                        <span className="font-medium text-sm">{gene.name}</span>
                                        <span className="text-xs text-muted-foreground ml-2">{gene.description}</span>
                                      </div>
                                    </div>
                                  </div>
                                )
                              })}
                            </div>
                          </CollapsibleContent>
                        </div>
                      </Collapsible>
                    )
                  })()}
                </div>
              </div>

              <div className="p-4 border-t flex gap-2">
                <Button
                  variant="outline"
                  className="flex-1"
                  onClick={() => setShowGeneModal(false)}
                >
                  취소
                </Button>
                <Button
                  className="flex-1"
                  onClick={() => setShowGeneModal(false)}
                >
                  완료 ({selectedGenes.length}개 선택)
                </Button>
              </div>
            </div>
          </div>
        )}

        {/* 유전체 형질 선택 모달 */}
        {showTraitModal && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-2xl w-full max-w-lg max-h-[80vh] flex flex-col">
              <div className="flex items-center justify-between p-4 border-b">
                <h3 className="font-semibold text-lg">유전체 형질 선택</h3>
                <button
                  onClick={() => setShowTraitModal(false)}
                  className="p-2 hover:bg-slate-100 rounded-lg"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <div className="p-4 space-y-3 flex-1 overflow-y-auto">
                {/* 검색창 */}
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    placeholder="형질 검색..."
                    className="pl-9"
                    value={traitSearch}
                    onChange={(e) => setTraitSearch(e.target.value)}
                  />
                </div>

                {/* 형질 목록 - 카테고리별 아코디언 */}
                <div className="space-y-2">
                  {traitCategories.map(cat => {
                    const selectedCount = cat.traits.filter(t => selectedTraits.includes(t.id)).length
                    const isAllSelected = selectedCount === cat.traits.length && cat.traits.length > 0
                    const hasSelected = selectedCount > 0

                    // 검색어가 카테고리 이름과 매칭되는지 확인
                    const isCategoryMatch = traitSearch && cat.name.toLowerCase().includes(traitSearch.toLowerCase())

                    // 검색 필터링: 카테고리 이름 매칭이면 전체 표시, 아니면 개별 형질 필터링
                    const filteredTraits = traitSearch
                      ? isCategoryMatch
                        ? cat.traits
                        : cat.traits.filter(t =>
                            t.name.toLowerCase().includes(traitSearch.toLowerCase()) ||
                            t.description.toLowerCase().includes(traitSearch.toLowerCase())
                          )
                      : cat.traits

                    // 검색 결과가 없으면 카테고리 숨기기
                    if (traitSearch && filteredTraits.length === 0) return null

                    const colorClasses: Record<string, { bg: string; text: string; border: string }> = {
                      purple: { bg: 'bg-purple-50', text: 'text-purple-700', border: 'border-purple-200' },
                      emerald: { bg: 'bg-emerald-50', text: 'text-emerald-700', border: 'border-emerald-200' },
                      cyan: { bg: 'bg-cyan-50', text: 'text-cyan-700', border: 'border-cyan-200' },
                      amber: { bg: 'bg-amber-50', text: 'text-amber-700', border: 'border-amber-200' },
                      rose: { bg: 'bg-rose-50', text: 'text-rose-700', border: 'border-rose-200' },
                    }
                    const colors = colorClasses[cat.color]

                    // 검색 중이거나 선택된 항목이 있으면 자동으로 펼침
                    const isExpanded = traitSearch ? true : (openCategories[cat.id] ?? false)

                    return (
                      <Collapsible
                        key={cat.id}
                        open={isExpanded}
                        onOpenChange={(open) => setOpenCategories(prev => ({ ...prev, [cat.id]: open }))}
                      >
                        <div className={`rounded-lg border ${hasSelected ? colors.border : 'border-slate-200'} ${hasSelected ? colors.bg : 'bg-slate-50'}`}>
                          {/* 카테고리 헤더 */}
                          <div className="flex items-center justify-between p-3">
                            <div className="flex items-center gap-2">
                              <Checkbox
                                checked={isAllSelected}
                                onCheckedChange={(checked) => {
                                  if (checked) {
                                    const newTraits = [...selectedTraits]
                                    const newWeights = { ...traitWeights }
                                    cat.traits.forEach(t => {
                                      if (!newTraits.includes(t.id)) {
                                        newTraits.push(t.id)
                                        newWeights[t.id] = 5
                                      }
                                    })
                                    setSelectedTraits(newTraits)
                                    setTraitWeights(newWeights)
                                  } else {
                                    setSelectedTraits(prev => prev.filter(id => !cat.traits.some(t => t.id === id)))
                                    setTraitWeights(prev => {
                                      const newWeights = { ...prev }
                                      cat.traits.forEach(t => delete newWeights[t.id])
                                      return newWeights
                                    })
                                  }
                                }}
                                className="h-4 w-4"
                              />
                              <span className={`font-semibold text-sm ${hasSelected ? colors.text : 'text-slate-700'}`}>
                                {cat.name}
                              </span>
                              <Badge variant="secondary" className={`text-xs ${hasSelected ? `${colors.bg} ${colors.text}` : ''}`}>
                                {selectedCount}/{cat.traits.length}
                              </Badge>
                            </div>
                            <CollapsibleTrigger asChild>
                              <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                                {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                              </Button>
                            </CollapsibleTrigger>
                          </div>

                          {/* 형질 목록 */}
                          <CollapsibleContent>
                            <div className="px-3 pb-3 space-y-1">
                              {filteredTraits.map(trait => {
                                const isSelected = selectedTraits.includes(trait.id)
                                return (
                                  <div
                                    key={trait.id}
                                    className={`p-2 rounded-lg transition-colors ${
                                      isSelected ? 'bg-white border border-primary/20' : 'hover:bg-white/50'
                                    }`}
                                  >
                                    <div
                                      className="flex items-center gap-3 cursor-pointer"
                                      onClick={() => toggleTrait(trait.id)}
                                    >
                                      <Checkbox checked={isSelected} />
                                      <div className="flex-1">
                                        <span className="font-medium text-sm">{trait.name}</span>
                                        <span className="text-xs text-muted-foreground ml-2">{trait.description}</span>
                                      </div>
                                    </div>
                                    {isSelected && (
                                      <div className="flex items-center gap-2 mt-2 pl-7">
                                        <span className="text-xs text-muted-foreground">가중치</span>
                                        <div className="flex items-center gap-1">
                                          <Button
                                            variant="outline"
                                            size="sm"
                                            className="h-7 w-7 p-0"
                                            onClick={(e) => {
                                              e.stopPropagation()
                                              const current = traitWeights[trait.id] || 0
                                              if (current > 0) {
                                                setTraitWeights(prev => ({ ...prev, [trait.id]: current - 1 }))
                                              }
                                            }}
                                            disabled={(traitWeights[trait.id] || 0) <= 0}
                                          >
                                            -
                                          </Button>
                                          <span className="text-sm font-bold w-8 text-center">{traitWeights[trait.id] || 0}점</span>
                                          <Button
                                            variant="outline"
                                            size="sm"
                                            className="h-7 w-7 p-0"
                                            onClick={(e) => {
                                              e.stopPropagation()
                                              const current = traitWeights[trait.id] || 0
                                              if (current < 10) {
                                                setTraitWeights(prev => ({ ...prev, [trait.id]: current + 1 }))
                                              }
                                            }}
                                            disabled={(traitWeights[trait.id] || 0) >= 10}
                                          >
                                            +
                                          </Button>
                                        </div>
                                      </div>
                                    )}
                                  </div>
                                )
                              })}
                            </div>
                          </CollapsibleContent>
                        </div>
                      </Collapsible>
                    )
                  })}
                </div>
              </div>

              <div className="p-4 border-t flex gap-2">
                <Button
                  variant="outline"
                  className="flex-1"
                  onClick={() => setShowTraitModal(false)}
                >
                  취소
                </Button>
                <Button
                  className="flex-1"
                  onClick={() => setShowTraitModal(false)}
                >
                  완료 ({selectedTraits.length}개 선택)
                </Button>
              </div>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  )
}