'use client'

import { useState, useEffect, useMemo } from 'react'
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Drawer,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
} from "@/components/ui/drawer"
import { ComparisonAveragesDto, TraitComparisonAveragesDto } from "@/lib/api/genome.api"
import { Pencil, X, RotateCcw } from 'lucide-react'
import {
  PolarAngleAxis,
  PolarGrid,
  PolarRadiusAxis,
  Radar,
  RadarChart,
  Tooltip as RechartsTooltip,
  ResponsiveContainer
} from 'recharts'
import { useMediaQuery } from "@/hooks/use-media-query"
import { DEFAULT_TRAITS, ALL_TRAITS, TRAIT_CATEGORIES, getTraitDisplayName, TRAIT_DISPLAY_NAMES } from "@/constants/traits"
import { GenomeCowTraitDto } from "@/types/genome.types"

interface CategoryStat {
  category: string
  avgBreedVal: number
  avgPercentile: number
  count: number
}

interface CategoryEvaluationCardProps {
  categoryStats: CategoryStat[]
  comparisonAverages: ComparisonAveragesDto | null
  traitComparisonAverages?: TraitComparisonAveragesDto | null  // 형질별 평균 비교 데이터 (폴리곤 차트용)
  regionAvgZ: number
  farmAvgZ: number
  allTraits?: GenomeCowTraitDto[]
  cowNo?: string
  hideTraitCards?: boolean  // 형질 카드 숨김 여부
}

// 개체번호 포맷팅 (뒷 4자리)
const formatCowNoShort = (no?: string) => {
  if (!no) return '개체'
  const numOnly = no.replace(/^KOR/i, '')
  return numOnly.slice(-4)
}

// 개체번호 포맷팅 (뒷 4자리 + 개체 - 차트 범례용)
const formatCowNo = (no?: string) => {
  if (!no) return '개체'
  const numOnly = no.replace(/^KOR/i, '')
  return `${numOnly.slice(-4)} 개체`
}

export function CategoryEvaluationCard({
  categoryStats,
  comparisonAverages,
  traitComparisonAverages,
  regionAvgZ,
  farmAvgZ,
  allTraits = [],
  cowNo,
  hideTraitCards = false,
}: CategoryEvaluationCardProps) {
  // 차트에 표시할 형질 목록 (커스텀 가능)
  const [chartTraits, setChartTraits] = useState<string[]>([...DEFAULT_TRAITS])

  // 활성화된 형질 목록 (차트에 표시할 형질)
  const [activeTraits, setActiveTraits] = useState<Set<string>>(new Set([...DEFAULT_TRAITS]))

  // 형질 추가 모달/드로어 상태
  const [isTraitSelectorOpen, setIsTraitSelectorOpen] = useState(false)

  // 선택된 형질 (터치/클릭 시 정보 표시용)
  const [selectedTraitName, setSelectedTraitName] = useState<string | null>(null)

  // 차트 로딩 상태
  const [isChartLoading, setIsChartLoading] = useState(false)

  // 모바일 여부 확인
  const isDesktop = useMediaQuery("(min-width: 768px)")

  // 형질 활성화/비활성화 토글
  const toggleTraitActive = (traitName: string) => {
    setActiveTraits(prev => {
      const newSet = new Set(prev)
      if (newSet.has(traitName)) {
        // 비활성화 시 제한 없음 (2개 이하일 때 차트 비활성화로 처리)
        newSet.delete(traitName)
      } else {
        newSet.add(traitName)
      }
      return newSet
    })
  }

  // 차트 데이터 변경 시 로딩 처리
  useEffect(() => {
    setIsChartLoading(true)
    const timer = setTimeout(() => {
      setIsChartLoading(false)
    }, 300) // 차트 렌더링 시뮬레이션
    return () => clearTimeout(timer)
  }, [activeTraits])

  // 형질 제거
  const removeTrait = (traitName: string) => {
    if (chartTraits.length > 3) { // 최소 3개는 유지
      setChartTraits(prev => prev.filter(t => t !== traitName))
      setActiveTraits(prev => {
        const newSet = new Set(prev)
        newSet.delete(traitName)
        return newSet
      })
    }
  }

  // 형질 추가
  const addTrait = (traitName: string) => {
    if (chartTraits.length < 7 && !chartTraits.includes(traitName)) { // 최대 7개
      setChartTraits(prev => [...prev, traitName])
      setActiveTraits(prev => new Set([...prev, traitName]))
    }
  }

  // 기본값으로 초기화
  const resetToDefault = () => {
    setChartTraits([...DEFAULT_TRAITS])
    setActiveTraits(new Set([...DEFAULT_TRAITS]))
  }

  // 폴리곤 차트용 데이터 생성 (활성화된 형질만 포함) - 보은군, 농가, 이 개체 비교
  const traitChartData = useMemo(() => {
    return chartTraits
      .filter(traitName => activeTraits.has(traitName))
      .map(traitName => {
    const trait = allTraits.find((t: GenomeCowTraitDto) => t.traitName === traitName)

    // 형질별 평균 데이터에서 해당 형질 찾기
    const traitAvgRegion = traitComparisonAverages?.region?.find(t => t.traitName === traitName)
    const traitAvgFarm = traitComparisonAverages?.farm?.find(t => t.traitName === traitName)

    // 보은군/농가 형질별 평균 (데이터 없으면 0)
    const regionTraitAvg = traitAvgRegion?.avgEbv ?? 0
    const farmTraitAvg = traitAvgFarm?.avgEbv ?? 0
    // 보은군/농가 형질별 EPD(육종가) 평균
    const regionEpdAvg = traitAvgRegion?.avgEpd ?? 0
    const farmEpdAvg = traitAvgFarm?.avgEpd ?? 0

    return {
      name: traitName,
      shortName: getTraitDisplayName(traitName),
      breedVal: trait?.breedVal ?? 0,        // 이 개체 표준화육종가 (σ)
      epd: trait?.traitVal ?? 0,          // 이 개체 EPD (육종가)
      regionVal: regionTraitAvg,              // 보은군 평균 (표준화육종가)
      farmVal: farmTraitAvg,                  // 농가 평균 (표준화육종가)
      regionEpd: regionEpdAvg,                // 보은군 평균 (육종가)
      farmEpd: farmEpdAvg,                    // 농가 평균 (육종가)
      percentile: trait?.percentile ?? 50,
      category: trait?.traitCategory ?? '체형',
      diff: trait?.breedVal ?? 0,
      hasData: !!trait
    }
    })
  }, [chartTraits, activeTraits, allTraits, traitComparisonAverages])

  // 가장 높은 형질 찾기 (이 개체 기준)
  const bestTraitName = traitChartData.reduce((best, current) =>
    current.breedVal > best.breedVal ? current : best
    , traitChartData[0])?.shortName

  // 동적 스케일 계산 (실제 데이터 범위를 기반으로, min/max 각각에 5% 여유분만 추가)
  // useMemo를 사용하는 이유: traitChartData가 변경될 때만 재계산하여 성능 최적화
  // - traitChartData는 activeTraits, chartTraits, allTraits, traitComparisonAverages에 의존
  // - 이 값들이 변경될 때마다 스케일을 다시 계산해야 함
  // - useMemo를 사용하면 의존성이 변경되지 않으면 이전 계산 결과를 재사용
  const dynamicDomain = useMemo(() => {
    if (traitChartData.length === 0) return [-0.3, 0.3]
    
    // 모든 값 수집 (breedVal, regionVal, farmVal)
    const allValues = traitChartData.flatMap(d => [d.breedVal, d.regionVal, d.farmVal])
    
    // 실제 데이터의 최소값과 최대값 찾기
    const minValue = Math.min(...allValues)
    const maxValue = Math.max(...allValues)
    
    // 데이터 범위 계산
    const dataRange = maxValue - minValue
    
    // 데이터 범위가 너무 작으면 최소 범위 보장 (0.3)
    const effectiveRange = Math.max(dataRange, 0.3)
    
    // min/max 각각에 범위의 10%만큼 여유분 추가 (대칭 처리하지 않음)
    const padding = effectiveRange * 0.10
    let domainMin = minValue - padding
    let domainMax = maxValue + padding
    
    // 소수점 첫째자리까지 반올림
    domainMin = Math.floor(domainMin * 10) / 10
    domainMax = Math.ceil(domainMax * 10) / 10
    
    return [domainMin, domainMax]
  }, [traitChartData])

  // 활성화된 형질 개수
  const activeTraitsCount = activeTraits.size
  const hasEnoughTraits = activeTraitsCount >= 3

  // 형질 이름으로 원본 형질명 찾기 (shortName -> name)
  const findTraitNameByShortName = (shortName: string) => {
    const entry = Object.entries(TRAIT_DISPLAY_NAMES).find(([, short]) => short === shortName)
    return entry ? entry[0] : shortName
  }

  // 커스텀 Tick 컴포넌트 (클릭 시 강조)
  const CustomAngleTick = ({ x, y, cx, cy, payload }: { x: number; y: number; cx: number; cy: number; payload: { value: string } }) => {
    const isSelected = selectedTraitName === findTraitNameByShortName(payload.value)
    const textWidth = payload.value.length * 11 + 20
    const textHeight = 28

    // 차트 중심에서 바깥 방향으로 offset 추가
    const offset = 12
    const dx = x - cx
    const dy = y - cy
    const distance = Math.sqrt(dx * dx + dy * dy) || 1
    const newX = x + (dx / distance) * offset
    const newY = y + (dy / distance) * offset

    const handleClick = () => {
      const traitName = findTraitNameByShortName(payload.value)
      setSelectedTraitName(prev => prev === traitName ? null : traitName)
    }

    return (
      <g
        transform={`translate(${newX},${newY})`}
        onClick={handleClick}
        style={{ cursor: 'pointer' }}
      >
        {isSelected && (
          <rect
            x={-textWidth / 2}
            y={-textHeight / 2}
            width={textWidth}
            height={textHeight}
            rx={6}
            fill="#1482B0"
          />
        )}
        <text
          x={0}
          y={0}
          dy={5}
          textAnchor="middle"
          fontSize={isDesktop ? 17 : 15}
          fontWeight={isSelected ? 700 : 600}
          fill={isSelected ? '#ffffff' : '#334155'}
        >
          {payload.value}
        </text>
      </g>
    )
  }

  // 형질 선택 UI 컴포넌트
  const TraitSelectorContent = () => (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-muted-foreground">
          형질을 선택하세요 (최소 3개, 최대 7개)
        </p>
        <span className="text-sm font-medium text-primary">{chartTraits.length}/7</span>
      </div>

      {Object.entries(TRAIT_CATEGORIES).map(([category, traits]) => (
        <div key={category} className="space-y-2">
          <h4 className="text-sm font-semibold text-foreground">{category}</h4>
          <div className="flex flex-wrap gap-2">
            {traits.map(trait => {
              const isSelected = chartTraits.includes(trait)
              const traitData = allTraits.find((t: GenomeCowTraitDto) => t.traitName === trait)
              return (
                <button
                  key={trait}
                  onClick={() => isSelected ? removeTrait(trait) : addTrait(trait)}
                  disabled={!isSelected && chartTraits.length >= 7}
                  className={`px-3 py-1.5 rounded-full text-sm font-medium transition-all ${isSelected
                    ? 'bg-primary text-primary-foreground'
                    : 'bg-muted text-muted-foreground hover:bg-muted/80 disabled:opacity-50'
                    }`}
                >
                  {getTraitDisplayName(trait)}
                  {/* 육종가(EBV) 값 표시 (주석 처리) */}
                  {/* {traitData && traitData.breedVal !== undefined && (
                    <span className={`ml-1 text-xs ${isSelected ? 'text-primary-foreground/80' : 'text-muted-foreground'}`}>
                      ({traitData.breedVal > 0 ? '+' : ''}{traitData.breedVal.toFixed(1)})
                    </span>
                  )} */}
                </button>
              )
            })}
          </div>
        </div>
      ))}

      <div className="pt-4 border-t border-border space-y-2">
        <Button
          onClick={() => setIsTraitSelectorOpen(false)}
          className="w-full"
        >
          확인
        </Button>
        <Button
          variant="outline"
          size="sm"
          onClick={resetToDefault}
          className="w-full"
        >
          <RotateCcw className="w-4 h-4 mr-2" />
          기본값으로 초기화
        </Button>
      </div>
    </div>
  )

  // 카테고리별 차트 데이터 (향후 사용 예정)
  void categoryStats.map(stat => {
    const regionCat = comparisonAverages?.region?.find(c => c.category === stat.category)
    const farmCat = comparisonAverages?.farm?.find(c => c.category === stat.category)
    return {
      ...stat,
      nationwide: 0,
      region: regionCat?.avgEbv ?? regionAvgZ,
      farm: farmCat?.avgEbv ?? farmAvgZ,
      cow: stat.avgBreedVal,
      diff: stat.avgBreedVal - (regionCat?.avgEbv ?? regionAvgZ)
    }
  })

  // 평균 차이 계산 (주요 형질 기준) - 향후 사용 예정
  const validTraitDiffs = traitChartData.filter(d => !isNaN(d.breedVal))
  void (validTraitDiffs.length > 0
    ? validTraitDiffs.reduce((sum, d) => sum + d.breedVal, 0) / validTraitDiffs.length
    : 0)

  return (
    <div className="bg-white rounded-xl border border-border overflow-hidden">
      {/* 2열 레이아웃: 왼쪽 차트 + 오른쪽 카드 */}
      <div className="p-4 lg:p-6 lg:pb-0">
        {/* 형질 선택 칩 영역 */}
        <div className="mb-4 lg:mb-2">
          <div className="flex items-center justify-between mb-2 lg:mb-0">
            <div className="flex items-center justify-between gap-2 flex-wrap">
              <div className="text-lg lg:text-base font-medium text-muted-foreground">비교 형질을 선택해주세요 :</div>
              <div className="flex flex-wrap gap-1.5 lg:gap-2">
                {chartTraits.map(trait => {
                  const isActive = activeTraits.has(trait)
                  return (
                    <div
                      key={trait}
                      className={`inline-flex items-center gap-1 lg:gap-1.5 px-2.5 lg:px-3.5 py-1 lg:py-1.5 rounded-full text-sm lg:text-base font-medium transition-all cursor-pointer ${
                        isActive
                          ? 'bg-primary text-primary-foreground'
                          : 'bg-primary/10 text-primary opacity-50'
                      }`}
                      onClick={() => toggleTraitActive(trait)}
                    >
                      <span className="text-md font-bold">{getTraitDisplayName(trait)}</span>
                      {chartTraits.length > 3 && (
                        <span
                          onClick={(e) => {
                            e.stopPropagation()
                            removeTrait(trait)
                            setActiveTraits(prev => {
                              const newSet = new Set(prev)
                              newSet.delete(trait)
                              return newSet
                            })
                          }}
                          className="w-4 h-4 lg:w-5 lg:h-5 rounded-full hover:bg-primary/20 flex items-center justify-center opacity-60 hover:opacity-100 transition-opacity cursor-pointer"
                        >
                          <X className="w-3 h-3 lg:w-4 lg:h-4" />
                        </span>
                      )}
                    </div>
                  )
                })}
              </div>
            </div>
            <button onClick={() => setIsTraitSelectorOpen(true)} className="text-sm lg:text-base text-primary flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-primary/30 hover:bg-primary/10 hover:border-primary/50 transition-colors">
              <Pencil className="w-4 h-4 lg:w-5 lg:h-5" />
              편집
            </button>
          </div>

          {/* 형질 편집 모달 - 웹: Dialog, 모바일: Drawer */}
          {isDesktop ? (
            <Dialog open={isTraitSelectorOpen} onOpenChange={setIsTraitSelectorOpen}>
              <DialogContent className="max-w-lg max-h-[80vh] overflow-y-auto">
                <DialogHeader>
                  <DialogTitle>비교 형질 선택</DialogTitle>
                </DialogHeader>
                <TraitSelectorContent />
              </DialogContent>
            </Dialog>
          ) : (
            <Drawer open={isTraitSelectorOpen} onOpenChange={setIsTraitSelectorOpen}>
              <DrawerContent>
                <DrawerHeader>
                  <DrawerTitle>비교 형질 선택</DrawerTitle>
                </DrawerHeader>
                <div className="px-4 pb-6 max-h-[60vh] overflow-y-auto">
                  <TraitSelectorContent />
                </div>
              </DrawerContent>
            </Drawer>
          )}
        </div>

        <div className={`flex flex-col ${hideTraitCards ? '' : 'lg:flex-row'} gap-6`}>
          {/* 폴리곤 차트 */}
          <div className={hideTraitCards ? 'w-full' : 'lg:w-1/2'}>
            <div className="bg-muted/20 rounded-xl h-full relative">
              <div className={hideTraitCards ? 'h-[95vw] max-h-[520px] sm:h-[420px]' : 'h-[95vw] max-h-[520px] sm:h-[440px]'}>
                {/* 범례 - 좌측 상단 */}
                <div className="absolute top-2 left-2 z-20 flex items-center gap-2 sm:gap-3 flex-wrap">
                  <div className="flex items-center gap-1.5 sm:gap-2">
                    <div className="w-3 h-3 sm:w-3.5 sm:h-3.5 rounded" style={{ backgroundColor: '#10b981' }}></div>
                    <span className="text-lg sm:text-base font-medium text-muted-foreground">보은군 평균</span>
                  </div>
                  <div className="flex items-center gap-1.5 sm:gap-2">
                    <div className="w-3 h-3 sm:w-3.5 sm:h-3.5 rounded" style={{ backgroundColor: '#1F3A8F' }}></div>
                    <span className="text-lg sm:text-base font-medium text-muted-foreground">농가 평균</span>
                  </div>
                  <div className="flex items-center gap-1.5 sm:gap-2">
                    <div className="w-3 h-3 sm:w-3.5 sm:h-3.5 rounded" style={{ backgroundColor: '#1482B0' }}></div>
                    <span className="text-lg sm:text-base font-medium text-foreground">{formatCowNoShort(cowNo)} 개체</span>
                  </div>
                </div>

                {/* 로딩 상태 또는 최소 형질 개수 미달 */}
                {(isChartLoading || !hasEnoughTraits) ? (
                  <div className="absolute inset-0 flex flex-col items-center justify-center bg-slate-50/80 rounded-xl z-10">
                    {isChartLoading ? (
                      <>
                        <div className="animate-spin rounded-full h-12 w-12 border-4 border-primary border-t-transparent mb-4"></div>
                        <p className="text-sm text-muted-foreground font-medium">차트 데이터 로딩 중...</p>
                      </>
                    ) : (
                      <p className="text-lg text-muted-foreground font-bold">비교 형질 3개 이상 선택해주세요.</p>
                    )}
                  </div>
                ) : (
                  <ResponsiveContainer width="100%" height="100%">
                    <RadarChart data={traitChartData} margin={{ top: 40, right: 0, bottom: 0, left: 0 }}>
                    <PolarGrid
                      stroke="#e2e8f0"
                      strokeWidth={1}
                    />
                    <PolarRadiusAxis
                      angle={90}
                      domain={dynamicDomain}
                      tick={{ fontSize: isDesktop ? 16 : 15, fill: '#64748b', fontWeight: 700 }}
                      tickCount={5}
                      axisLine={false}
                    />
                    {/* 보은군 평균 - Green */}
                    <Radar
                      name="보은군 평균"
                      dataKey="regionVal"
                      stroke="#10b981"
                      // fill="#10b981"
                      // fillOpacity={0.2}
                      fill="transparent"
                      strokeWidth={2}
                      dot={false}
                    />
                    {/* 농가 평균 - Navy Blue (중간) */}
                    <Radar
                      name="농가 평균"
                      dataKey="farmVal"
                      stroke="#1F3A8F"
                      // fill="#1F3A8F"
                      // fillOpacity={0.3}
                      fill="transparent"
                      strokeWidth={2.5}
                      dot={false}
                    />
                    {/* 이 개체 - Cyan (가장 앞, 강조) */}
                    <Radar
                      name={formatCowNo(cowNo)}
                      dataKey="breedVal"
                      stroke="#1482B0"
                      // fill="#1482B0"
                      // fillOpacity={0.35}
                      fill="transparent"
                      strokeWidth={isDesktop ? 3 : 2}
                      dot={{
                        fill: '#1482B0',
                        strokeWidth: 1,
                        stroke: '#fff',
                        r: isDesktop ? 3 : 2
                      }}
                    />
                    {/* PolarAngleAxis를 Radar 뒤에 배치하여 tick이 차트 위에 표시되도록 함 */}
                    <PolarAngleAxis
                      dataKey="shortName"
                      tick={CustomAngleTick}
                      tickLine={false}
                    />
                    <RechartsTooltip
                      animationDuration={0}
                      content={({ active, payload }) => {
                        if (active && payload && payload.length) {
                          const item = payload[0]?.payload
                          const epd = item?.epd ?? 0
                          const regionEpd = item?.regionEpd ?? 0
                          const farmEpd = item?.farmEpd ?? 0

                          return (
                            <div className="bg-foreground px-4 py-3 rounded-lg text-sm shadow-lg">
                              <p className="text-white font-bold mb-2 text-lg">{item?.name}</p>
                              <div className="space-y-1.5 text-lg">
                                <div className="flex items-center justify-between gap-4">
                                  <span className="flex items-center gap-1.5">
                                    <span className="w-2 h-2 rounded" style={{ backgroundColor: '#10b981' }}></span>
                                    <span className="text-slate-300">보은군 평균</span>
                                  </span>
                                  <span className="text-white font-semibold">{regionEpd > 0 ? '+' : ''}{regionEpd.toFixed(2)}</span>
                                </div>
                                <div className="flex items-center justify-between gap-4">
                                  <span className="flex items-center gap-1.5">
                                    <span className="w-2 h-2 rounded" style={{ backgroundColor: '#1F3A8F' }}></span>
                                    <span className="text-slate-300">농가 평균</span>
                                  </span>
                                  <span className="text-white font-semibold">{farmEpd > 0 ? '+' : ''}{farmEpd.toFixed(2)}</span>
                                </div>
                                <div className="flex items-center justify-between gap-4">
                                  <span className="flex items-center gap-1.5">
                                    <span className="w-2.5 h-2.5 rounded" style={{ backgroundColor: '#1482B0' }}></span>
                                    <span className="text-white font-medium">{formatCowNoShort(cowNo)} 개체</span>
                                  </span>
                                  <span className="text-white font-bold">{epd > 0 ? '+' : ''}{epd.toFixed(2)}</span>
                                </div>
                              </div>
                            </div>
                          )
                        }
                        return null
                      }}
                    />
                  </RadarChart>
                </ResponsiveContainer>
                )}
              </div>

              {/* 선택된 형질 정보 표시 - 육종가(EPD) 값으로 표시 */}
              {selectedTraitName && (() => {
                const selectedTrait = traitChartData.find(t => t.name === selectedTraitName)
                if (!selectedTrait) return null
                return (
                  <div className="mx-2 mb-4 p-3 bg-slate-50 rounded-xl border border-slate-200 animate-fade-in">
                    {/* 헤더: 형질명 + 닫기 */}
                    <div className="flex items-center justify-between mb-3">
                      <span className="px-4 py-1.5 bg-slate-200 text-slate-700 text-sm font-bold rounded-full">
                        {selectedTrait.shortName} 조회 기준
                      </span>
                      <button
                        onClick={() => setSelectedTraitName(null)}
                        className="text-muted-foreground hover:text-foreground p-1 hover:bg-slate-200 rounded-full transition-colors"
                      >
                        <X className="w-5 h-5" />
                      </button>
                    </div>
                    {/* 3개 카드 그리드 */}
                    <div className="grid grid-cols-3 gap-2">
                      {/* 보은군 카드 */}
                      <div className="flex flex-col items-center justify-center px-3 py-4 bg-white rounded-xl border-2 border-emerald-300 shadow-sm">
                        <span className="text-xs text-slate-600 mb-1 font-semibold whitespace-nowrap">보은군 평균</span>
                        <span className="text-xl font-bold text-emerald-600">
                          {selectedTrait.regionEpd?.toFixed(2) ?? '-'}
                        </span>
                      </div>
                      {/* 농가 카드 */}
                      <div className="flex flex-col items-center justify-center px-3 py-4 bg-white rounded-xl border-2 border-[#1F3A8F]/30 shadow-sm">
                        <span className="text-xs text-slate-600 mb-1 font-semibold whitespace-nowrap">농가 평균</span>
                        <span className="text-xl font-bold text-[#1F3A8F]">
                          {selectedTrait.farmEpd?.toFixed(2) ?? '-'}
                        </span>
                      </div>
                      {/* 개체 카드 */}
                      <div className="flex flex-col items-center justify-center px-3 py-4 bg-white rounded-xl border-2 border-[#1482B0]/30 shadow-sm">
                        <span className="text-xs text-slate-600 mb-1 font-semibold whitespace-nowrap">내 개체</span>
                        <span className="text-xl font-bold text-[#1482B0]">
                          {selectedTrait.epd?.toFixed(2) ?? '-'}
                        </span>
                      </div>
                    </div>
                  </div>
                )
              })()}
            </div>
          </div>

          {/* 오른쪽: 7개 형질 카드 (hideTraitCards가 false일 때만 표시) */}
          {!hideTraitCards && (
            <div className="lg:w-1/2">
              <div className="grid grid-cols-2 gap-3 h-full content-start">
                {traitChartData.map((trait) => {
                  // 카테고리별 배지 색상 (백엔드 API와 일치: 성장, 생산, 체형, 무게, 비율)
                  const categoryColors: Record<string, { bg: string; text: string }> = {
                    '성장': { bg: 'bg-amber-100', text: 'text-amber-700' },
                    '생산': { bg: 'bg-emerald-100', text: 'text-emerald-700' },
                    '체형': { bg: 'bg-blue-100', text: 'text-blue-700' },
                    '무게': { bg: 'bg-purple-100', text: 'text-purple-700' },
                    '비율': { bg: 'bg-rose-100', text: 'text-rose-700' },
                  }
                  const catColor = categoryColors[trait.category] || { bg: 'bg-slate-100', text: 'text-slate-700' }

                  return (
                    <div
                      key={trait.name}
                      className="p-3 lg:p-4 rounded-xl border border-border bg-white hover:shadow-md hover:border-primary/30 transition-all duration-200"
                    >
                      {/* 형질명 + 카테고리 배지 */}
                      <div className="flex items-center justify-between mb-2 lg:mb-3">
                        <span className="text-sm lg:text-base font-bold text-foreground">{trait.shortName}</span>
                        <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${catColor.bg} ${catColor.text}`}>
                          {trait.category}
                        </span>
                      </div>

                      {/* 카드 개체 표시(4자리 번호) */}
                      <div className="flex items-center justify-between mb-2 lg:mb-3 pb-2 lg:pb-3 border-b border-border">
                        <span className="flex items-center gap-1.5 lg:gap-2">
                          <span className="w-2.5 h-2.5 lg:w-3 lg:h-3 rounded" style={{ backgroundColor: '#1482B0' }}></span>
                          <span className="text-sm lg:text-base text-foreground">{formatCowNoShort(cowNo)} 개체</span>
                        </span>
                        <span className={`font-bold text-lg lg:text-xl ${trait.breedVal >= 0 ? 'text-primary' : 'text-red-500'}`}>
                          {trait.breedVal > 0 ? '+' : ''}{trait.breedVal.toFixed(2)}
                        </span>
                      </div>

                      {/* 보은군, 농가 비교 */}
                      <div className="space-y-1.5 lg:space-y-2">
                        <div className="flex items-center justify-between text-sm lg:text-base">
                          <span className="flex items-center gap-1.5 lg:gap-2">
                            <span className="w-2 h-2 lg:w-2.5 lg:h-2.5 rounded" style={{ backgroundColor: '#10b981' }}></span>
                            <span className="text-muted-foreground">보은군</span>
                          </span>
                          <span className="text-foreground font-medium">{trait.regionVal > 0 ? '+' : ''}{trait.regionVal.toFixed(2)}</span>
                        </div>
                        <div className="flex items-center justify-between text-sm lg:text-base">
                          <span className="flex items-center gap-1.5 lg:gap-2">
                            <span className="w-2 h-2 lg:w-2.5 lg:h-2.5 rounded" style={{ backgroundColor: '#1F3A8F' }}></span>
                            <span className="text-muted-foreground">농가</span>
                          </span>
                          <span className="text-foreground font-medium">{trait.farmVal > 0 ? '+' : ''}{trait.farmVal.toFixed(2)}</span>
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
