'use client'

import { useState } 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, FarmTraitComparisonDto, TraitComparisonAveragesDto } from "@/lib/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"

// 디폴트로 표시할 주요 형질 목록
const DEFAULT_TRAITS = ['도체중', '등심단면적', '등지방두께', '근내지방도', '체장', '체고', '등심weight']

// 전체 형질 목록 (35개)
const ALL_TRAITS = [
  // 성장형질 (1개)
  '12개월령체중',
  // 경제형질 (4개)
  '도체중', '등심단면적', '등지방두께', '근내지방도',
  // 체형형질 (10개)
  '체고', '십자', '체장', '흉심', '흉폭', '고장', '요각폭', '좌골폭', '곤폭', '흉위',
  // 부위별무게 (10개)
  '안심weight', '등심weight', '채끝weight', '목심weight', '앞다리weight',
  '우둔weight', '설도weight', '사태weight', '양지weight', '갈비weight',
  // 부위별비율 (10개)
  '안심rate', '등심rate', '채끝rate', '목심rate', '앞다리rate',
  '우둔rate', '설도rate', '사태rate', '양지rate', '갈비rate',
]

// 형질 카테고리 (백엔드 API와 일치: 성장, 생산, 체형, 무게, 비율)
const TRAIT_CATEGORIES: Record<string, string[]> = {
  '성장': ['12개월령체중'],
  '생산': ['도체중', '등심단면적', '등지방두께', '근내지방도'],
  '체형': ['체고', '십자', '체장', '흉심', '흉폭', '고장', '요각폭', '좌골폭', '곤폭', '흉위'],
  '무게': ['안심weight', '등심weight', '채끝weight', '목심weight', '앞다리weight', '우둔weight', '설도weight', '사태weight', '양지weight', '갈비weight'],
  '비율': ['안심rate', '등심rate', '채끝rate', '목심rate', '앞다리rate', '우둔rate', '설도rate', '사태rate', '양지rate', '갈비rate'],
}

// 형질명 표시 (전체 이름)
const TRAIT_SHORT_NAMES: Record<string, string> = {
  '도체중': '도체중',
  '등심단면적': '등심단면적',
  '등지방두께': '등지방두께',
  '근내지방도': '근내지방도',
  '체장': '체장',
  '체고': '체고',
  '등심weight': '등심중량',
  '12개월령체중': '12개월령체중',
  '십자': '십자',
  '흉심': '흉심',
  '흉폭': '흉폭',
  '고장': '고장',
  '요각폭': '요각폭',
  '좌골폭': '좌골폭',
  '곤폭': '곤폭',
  '흉위': '흉위',
  '안심weight': '안심무게',
  '채끝weight': '채끝무게',
  '목심weight': '목심무게',
  '앞다리weight': '앞다리무게',
  '우둔weight': '우둔무게',
  '설도weight': '설도무게',
  '사태weight': '사태무게',
  '양지weight': '양지무게',
  '갈비weight': '갈비무게',
  '안심rate': '안심비율',
  '등심rate': '등심비율',
  '채끝rate': '채끝비율',
  '목심rate': '목심비율',
  '앞다리rate': '앞다리비율',
  '우둔rate': '우둔비율',
  '설도rate': '설도비율',
  '사태rate': '사태비율',
  '양지rate': '양지비율',
  '갈비rate': '갈비비율',
}

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

interface TraitData {
  id: number
  name: string
  category: string
  breedVal: number      // 표준화육종가 (σ 단위)
  percentile: number
  actualValue: number   // EPD (예상후대차이) 원래 값
  unit: string
  description: string
  importance: string
}

interface CategoryEvaluationCardProps {
  categoryStats: CategoryStat[]
  comparisonAverages: ComparisonAveragesDto | null
  traitComparisonAverages?: TraitComparisonAveragesDto | null  // 형질별 평균 비교 데이터 (폴리곤 차트용)
  regionAvgZ: number
  farmAvgZ: number
  allTraits?: TraitData[]
  cowNo?: string
  traitAverages?: FarmTraitComparisonDto | null  // 형질별 평균 비교 데이터 (기존)
  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,
  traitAverages,
  hideTraitCards = false,
}: CategoryEvaluationCardProps) {
  // 차트에 표시할 형질 목록 (커스텀 가능)
  const [chartTraits, setChartTraits] = useState<string[]>(DEFAULT_TRAITS)

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

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

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

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

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

  // 기본값으로 초기화
  const resetToDefault = () => {
    setChartTraits(DEFAULT_TRAITS)
  }

  // 폴리곤 차트용 데이터 생성 (선택된 형질 기반) - 보은군, 농가, 이 개체 비교
  const traitChartData = chartTraits.map(traitName => {
    const trait = allTraits.find((t: TraitData) => t.name === 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: TRAIT_SHORT_NAMES[traitName] || traitName,
      breedVal: trait?.breedVal ?? 0,        // 이 개체 표준화육종가 (σ)
      epd: trait?.actualValue ?? 0,          // 이 개체 EPD (육종가)
      regionVal: regionTraitAvg,              // 보은군 평균 (표준화육종가)
      farmVal: farmTraitAvg,                  // 농가 평균 (표준화육종가)
      regionEpd: regionEpdAvg,                // 보은군 평균 (육종가)
      farmEpd: farmEpdAvg,                    // 농가 평균 (육종가)
      percentile: trait?.percentile ?? 50,
      category: trait?.category ?? '체형',
      diff: trait?.breedVal ?? 0,
      hasData: !!trait
    }
  })

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

  // 동적 스케일 계산 (모든 값의 최대 절대값 기준)
  const allValues = traitChartData.flatMap(d => [d.breedVal, d.regionVal, d.farmVal])
  const maxAbsValue = Math.max(...allValues.map(Math.abs), 0.3) // 최소 0.3
  const dynamicDomain = Math.ceil(maxAbsValue * 1.2 * 10) / 10 // 20% 여유

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

  // 커스텀 Tick 컴포넌트 (가장 좋은 형질에 배경색 + 클릭 가능)
  const CustomAngleTick = ({ x, y, payload }: { x: number; y: number; payload: { value: string } }) => {
    const isBest = payload.value === bestTraitName
    const isSelected = selectedTraitName === findTraitNameByShortName(payload.value)
    const textWidth = payload.value.length * 11 + 20
    const textHeight = 28

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

    return (
      <g
        transform={`translate(${x},${y})`}
        onClick={handleClick}
        style={{ cursor: 'pointer' }}
      >
        {(isBest || isSelected) && (
          <rect
            x={-textWidth / 2}
            y={-textHeight / 2}
            width={textWidth}
            height={textHeight}
            rx={6}
            fill={isSelected ? '#1F3A8F' : '#1482B0'}
          />
        )}
        <text
          x={0}
          y={0}
          dy={5}
          textAnchor="middle"
          fontSize={15}
          fontWeight={(isBest || isSelected) ? 700 : 600}
          fill={(isBest || 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: TraitData) => t.name === 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'
                    }`}
                >
                  {TRAIT_SHORT_NAMES[trait] || trait}
                  {traitData && (
                    <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">
        {/* 형질 선택 칩 영역 */}
        <div className="mb-4 lg:mb-6">
          <div className="flex items-center justify-between mb-2 lg:mb-3">
            <span className="text-sm lg:text-base font-medium text-muted-foreground">비교 형질을 선택해주세요</span>
            <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>
          <div className="flex flex-wrap gap-1.5 lg:gap-2">
            {chartTraits.map(trait => (
              <span
                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 bg-primary/10 text-primary rounded-full text-sm lg:text-base font-medium group"
              >
                {TRAIT_SHORT_NAMES[trait] || trait}
                {chartTraits.length > 3 && (
                  <button
                    onClick={() => removeTrait(trait)}
                    className="w-4 h-4 lg:w-5 lg:h-5 rounded-full hover:bg-primary/20 flex items-center justify-center opacity-60 group-hover:opacity-100 transition-opacity"
                  >
                    <X className="w-3 h-3 lg:w-4 lg:h-4" />
                  </button>
                )}
              </span>
            ))}

          </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">
              <div className={hideTraitCards ? 'h-[95vw] max-h-[520px] sm:h-[420px]' : 'h-[95vw] max-h-[520px] sm:h-[440px]'}>
                <ResponsiveContainer width="100%" height="100%">
                  <RadarChart data={traitChartData} margin={{ top: 25, right: 30, bottom: 25, left: 30 }}>
                    <PolarGrid
                      stroke="#e2e8f0"
                      strokeWidth={1}
                    />
                    <PolarAngleAxis
                      dataKey="shortName"
                      tick={<CustomAngleTick x={0} y={0} payload={{ value: '' }} />}
                      tickLine={false}
                    />
                    <PolarRadiusAxis
                      angle={90}
                      domain={[-dynamicDomain, dynamicDomain]}
                      tick={{ fontSize: 12, fill: '#64748b', fontWeight: 500 }}
                      tickCount={5}
                      axisLine={false}
                    />
                    {/* 보은군 평균 - Green */}
                    <Radar
                      name="보은군 평균"
                      dataKey="regionVal"
                      stroke="#10b981"
                      fill="#10b981"
                      fillOpacity={0.2}
                      strokeWidth={2}
                      dot={false}
                    />
                    {/* 농가 평균 - Navy Blue (중간) */}
                    <Radar
                      name="농가 평균"
                      dataKey="farmVal"
                      stroke="#1F3A8F"
                      fill="#1F3A8F"
                      fillOpacity={0.3}
                      strokeWidth={2.5}
                      dot={false}
                    />
                    {/* 이 개체 - Cyan (가장 앞, 강조) */}
                    <Radar
                      name={formatCowNo(cowNo)}
                      dataKey="breedVal"
                      stroke="#1482B0"
                      fill="#1482B0"
                      fillOpacity={0.35}
                      strokeWidth={isDesktop ? 3 : 2}
                      dot={{
                        fill: '#1482B0',
                        strokeWidth: 1,
                        stroke: '#fff',
                        r: isDesktop ? 3 : 2
                      }}
                    />
                    <RechartsTooltip
                      content={({ active, payload }) => {
                        if (active && payload && payload.length) {
                          const item = payload[0]?.payload
                          const epd = item?.epd ?? 0
                          const regionEpd = (item?.regionVal ?? 0) * (item?.epd / (item?.breedVal || 1)) || 0
                          const farmEpd = (item?.farmVal ?? 0) * (item?.epd / (item?.breedVal || 1)) || 0

                          return (
                            <div className="bg-foreground px-4 py-3 rounded-lg text-sm shadow-lg">
                              <p className="text-white font-bold mb-2">{item?.name}</p>
                              <div className="space-y-1.5 text-xs">
                                <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>

              {/* 범례 */}
              <div className="flex items-center justify-center gap-5 sm:gap-8 py-3 border-t border-border">
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 rounded" style={{ backgroundColor: '#10b981' }}></div>
                  <span className="text-base text-muted-foreground">보은군 평균</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 rounded" style={{ backgroundColor: '#1F3A8F' }}></div>
                  <span className="text-base text-muted-foreground">농가 평균</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-4 h-4 rounded" style={{ backgroundColor: '#1482B0' }}></div>
                  <span className="text-base font-semibold text-foreground">{formatCowNoShort(cowNo)} 개체</span>
                </div>
              </div>

              {/* 선택된 형질 정보 표시 - 육종가(EPD) 값으로 표시 */}
              {selectedTraitName && (() => {
                const selectedTrait = traitChartData.find(t => t.name === selectedTraitName)
                if (!selectedTrait) return null
                return (
                  <div className="mx-4 mb-4 p-4 bg-slate-50 rounded-xl border border-slate-200 animate-fade-in">
                    {/* 헤더: 형질명 + 닫기 */}
                    <div className="flex items-center justify-between mb-4">
                      <span className="px-4 py-1.5 bg-slate-200 text-slate-700 text-base 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-3">
                      {/* 보은군 카드 */}
                      <div className="flex flex-col items-center justify-center p-3 bg-white rounded-xl border-2 border-emerald-300 shadow-sm">
                        <span className="text-xs text-muted-foreground mb-1 font-medium">보은군 평균</span>
                        <span className="text-lg font-bold text-emerald-600">
                          {selectedTrait.regionEpd?.toFixed(2) ?? '-'}
                        </span>
                      </div>
                      {/* 농가 카드 */}
                      <div className="flex flex-col items-center justify-center p-3 bg-white rounded-xl border-2 border-[#1F3A8F]/30 shadow-sm">
                        <span className="text-xs text-muted-foreground mb-1 font-medium">농가 평균</span>
                        <span className="text-lg font-bold text-[#1F3A8F]">
                          {selectedTrait.farmEpd?.toFixed(2) ?? '-'}
                        </span>
                      </div>
                      {/* 개체 카드 */}
                      <div className="flex flex-col items-center justify-center p-3 bg-white rounded-xl border-2 border-[#1482B0]/30 shadow-sm">
                        <span className="text-xs text-muted-foreground mb-1 font-medium">내 개체</span>
                        <span className="text-lg 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>
  )
}
