'use client'

import { Card, CardContent } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { NEGATIVE_TRAITS } from "@/constants/traits"
import { genomeApi, TraitRankDto } from "@/lib/api/genome.api"
import { useFilterStore } from "@/store/filter-store"
import { Maximize2 } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import {
  Area,
  ComposedChart,
  Customized,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis
} from 'recharts'

// 형질 카테고리별 색상 매핑
const CATEGORY_COLORS: Record<string, string> = {
  '성장': '#3b82f6',    // 블루
  '생산': '#f59e0b',    // 앰버
  '체형': '#10b981',    // 에메랄드
  '무게': '#8b5cf6',    // 바이올렛
  '비율': '#ec4899'     // 핑크
}



/** 유전체 형질 데이터 타입 */
interface GenomicTrait {
  id?: number
  traitName?: string          // 형질명 (예: 도체중, 등지방두께)
  traitCategory?: string      // 형질 카테고리 (성장/생산/체형/무게/비율)
  breedVal?: number           // 육종가 값
  percentile?: number         // 백분위 순위
  traitVal?: number           // 형질 값 (EPD)
}

/** 형질별 농가/보은군 비교 데이터 */
interface TraitComparison {
  trait: string        // 형질명
  shortName: string    // 짧은 형질명 (차트 표시용)
  myFarm: number       // 농가 평균 값
  region: number       // 보은군 평균 값
  diff: number         // 농가와 보은군 간 차이
}

interface NormalDistributionChartProps {
  // 분포 데이터
  multiDistribution: any[]
  // 개체 정보
  cowName: string
  cowNo?: string  // 개체번호 (API 호출용)
  overallScore: number
  overallPercentile: number
  // 비교 그룹 평균 (선발지수)
  regionAvgZ: number
  farmAvgZ: number
  // 분포 표시 옵션
  showNationwide: boolean
  showRegion: boolean
  showFarm: boolean
  // 형질 관련
  allTraits: GenomicTrait[]
  selectedTraitData: GenomicTrait[]
  selectedTraitsCount: number
  showAllTraits: boolean
  // 가중치 정보 (형질명 -> 가중치)
  traitWeights?: Record<string, number>
  // 콜백
  onOpenTraitSheet: () => void
  onToggleTraitSelection: (traitId: number) => void
  onClearSelectedTraits: () => void
  onOpenChartModal: () => void
  // 히스토그램용 분포 데이터 (선택적)
  distributionData?: { range: string; count: number; farmCount?: number; min: number; max: number }[]
  totalCowCount?: number
  // 형질별 농가/보은군 비교 데이터
  traitComparisons?: TraitComparison[]
  // 개체/농가/보은군 EPD 평균 (카드 표시용, 선택적)
  cowEpd?: number | null
  farmAvgEpd?: number | null
  regionAvgEpd?: number | null
  // 농가/보은군 백분위 (선택적)
  farmPercentile?: number | null
  regionPercentile?: number | null
  // 실제 순위 데이터 (백엔드에서 계산된 값)
  farmRank?: number | null
  farmTotal?: number | null
  regionRank?: number | null
  regionTotal?: number | null
  // 하이라이트 모드 (농가/보은군 비교 강조)
  highlightMode?: 'farm' | 'region' | null
  onHighlightModeChange?: (mode: 'farm' | 'region' | null) => void
  // 차트 필터 형질 선택 콜백 (외부 연동용)
  chartFilterTrait?: string
  onChartFilterTraitChange?: (trait: string) => void
  // 전체 선발지수 히스토그램 (실제 분포 데이터)
  selectionIndexHistogram?: { bin: number; count: number; farmCount: number }[]
}

export function NormalDistributionChart({
  multiDistribution,
  cowName,
  cowNo,
  overallScore,
  overallPercentile,
  regionAvgZ,
  farmAvgZ,
  showNationwide,
  showRegion,
  showFarm,
  allTraits,
  selectedTraitData,
  selectedTraitsCount,
  showAllTraits,
  traitWeights = {},
  onOpenTraitSheet,
  onToggleTraitSelection,
  onClearSelectedTraits,
  onOpenChartModal,
  distributionData,
  totalCowCount = 0,
  traitComparisons = [],
  cowEpd = null,
  farmAvgEpd = null,
  regionAvgEpd = null,
  farmPercentile = null,
  regionPercentile = null,
  farmRank = null,
  farmTotal = null,
  regionRank = null,
  regionTotal = null,
  highlightMode = null,
  onHighlightModeChange,
  chartFilterTrait: externalChartFilterTrait,
  onChartFilterTraitChange,
  selectionIndexHistogram = []
}: NormalDistributionChartProps) {
  const { filters } = useFilterStore()

  // 필터에서 고정된 첫 번째 형질 (없으면 첫 번째 선택된 형질, 없으면 '도체중')
  const firstPinnedTrait = filters.pinnedTraits?.[0] || selectedTraitData[0]?.traitName || '도체중'

  // 차트 필터 - 선택된 형질 또는 전체 선발지수 (외부 제어 가능)
  // 필터 비활성 시 기본값은 첫 번째 고정 형질
  const [internalChartFilterTrait, setInternalChartFilterTrait] = useState<string>(() => {
    return filters.isActive ? 'overall' : firstPinnedTrait
  })

  // 필터 활성 상태 변경 시 기본값 업데이트
  useEffect(() => {
    if (!filters.isActive && internalChartFilterTrait === 'overall') {
      setInternalChartFilterTrait(firstPinnedTrait)
    }
  }, [filters.isActive, firstPinnedTrait])

  // 외부에서 제어하면 외부 값 사용, 아니면 내부 상태 사용
  const chartFilterTrait = externalChartFilterTrait ?? internalChartFilterTrait
  const setChartFilterTrait = (trait: string) => {
    if (onChartFilterTraitChange) {
      onChartFilterTraitChange(trait)
    } else {
      setInternalChartFilterTrait(trait)
    }
  }

  // 형질별 순위 데이터 (API에서 조회)
  const [traitRankData, setTraitRankData] = useState<TraitRankDto | null>(null)
  const [traitRankLoading, setTraitRankLoading] = useState(false)

  // 형질 선택 시 순위 API 호출
  useEffect(() => {
    const fetchTraitRank = async () => {
      if (chartFilterTrait === 'overall' || !cowNo) {
        setTraitRankData(null)
        return
      }

      setTraitRankLoading(true)
      try {
        const rankData = await genomeApi.getTraitRank(cowNo, chartFilterTrait)
        setTraitRankData(rankData)
      } catch (error) {
        console.error('[형질순위] 데이터 로드 실패:', error)
        setTraitRankData(null)
      } finally {
        setTraitRankLoading(false)
      }
    }

    fetchTraitRank()
  }, [chartFilterTrait, cowNo])

  // 모바일 여부 감지
  const [isMobileView, setIsMobileView] = useState(false)
  useEffect(() => {
    const checkMobile = () => setIsMobileView(window.innerWidth < 640)
    checkMobile()
    window.addEventListener('resize', checkMobile)
    return () => window.removeEventListener('resize', checkMobile)
  }, [])

  // 개체번호에서 KOR 제외한 002로 시작하는 번호 추출
  const displayCowNumber = useMemo(() => {
    if (!cowName) return '개체'
    // KOR002123456789 -> 002123456789
    const match = cowName.match(/002\d+/)
    return match ? match[0] : cowName
  }, [cowName])

  // 차트 필터에 따른 표시 값 계산 (개체/농가/보은군 모두)
  // "내 개체 중심" 방식: 개체를 0에 고정하고 농가/보은군을 상대 위치로 표시
  // - 전체 선발지수: 선발지수 값 사용
  // - 개별 형질: 육종가(EPD) 값 사용
  const chartDisplayValues = useMemo(() => {
    let baseScore = overallScore
    let basePercentile = overallPercentile
    let baseLabel = '전체 선발지수'
    let baseFarmScore = farmAvgZ
    let baseRegionScore = regionAvgZ

    if (chartFilterTrait !== 'overall') {
      // 모든 형질에서 찾기 (selectedTraitData는 선택된 형질만 포함하므로 allTraits에서 찾아야 함)
      const selectedTrait = allTraits.find(t => t.traitName === chartFilterTrait)

      if (selectedTrait) {
        // 개별 형질 선택 시: 육종가(EPD) 값 사용
        baseScore = selectedTrait.traitVal ?? 0  // 개체 육종가
        basePercentile = selectedTrait.percentile ?? 50
        baseLabel = selectedTrait.traitName ?? '알 수 없음'
        // API에서 가져온 형질별 농가/보은군 평균 육종가(EPD) 사용
        baseFarmScore = traitRankData?.farmAvgEpd ?? 0
        baseRegionScore = traitRankData?.regionAvgEpd ?? 0
      }
    }

    // "내 개체 중심" 방식: 개체를 0에 고정
    // 농가/보은군은 개체 대비 상대 위치로 표시 (음수 = 개체보다 뒤처짐)
    let cowVsFarm = baseScore - baseFarmScore    // 농가 대비 개체 차이
    let cowVsRegion = baseScore - baseRegionScore // 보은군 대비 개체 차이

    // 등지방두께 등 낮을수록 좋은 형질은 부호 반전
    // (개체가 농가보다 낮으면 실제로는 더 좋은 것이므로 양수로 표시)
    if (NEGATIVE_TRAITS.includes(chartFilterTrait)) {
      cowVsFarm = -cowVsFarm
      cowVsRegion = -cowVsRegion
    }

    return {
      score: 0,  // 개체는 항상 0 (중심)
      percentile: basePercentile,
      label: baseLabel,
      farmScore: -cowVsFarm,    // 농가 위치 (개체 기준)
      regionScore: -cowVsRegion, // 보은군 위치 (개체 기준)
      // 원본 값도 저장 (라벨 표시용)
      originalScore: baseScore,
      originalFarmScore: baseFarmScore,
      originalRegionScore: baseRegionScore,
      // 대비값 저장
      cowVsFarm,
      cowVsRegion
    }
  }, [chartFilterTrait, overallScore, overallPercentile, allTraits, traitRankData, farmAvgZ, regionAvgZ])

  // X축 범위 및 간격 계산 (실제 데이터에 맞게 조정, 중앙 정렬)
  const xAxisConfig = useMemo(() => {
    const cowScore = chartDisplayValues.originalScore
    
    // 전체 선발지수: selectionIndexHistogram 사용
    if (chartFilterTrait === 'overall' && selectionIndexHistogram.length > 0) {
      const bins = selectionIndexHistogram.map(item => item.bin - cowScore)
      // 내 개체(0), 농가 평균, 보은군 평균도 범위에 포함
      const allValues = [...bins, 0, chartDisplayValues.farmScore, chartDisplayValues.regionScore]
      const minData = Math.min(...allValues)
      const maxData = Math.max(...allValues)
      
      // 데이터의 중심점 계산
      const center = (minData + maxData) / 2
      // 데이터 범위에 20% 여유 추가
      const dataRange = maxData - minData
      const padding = dataRange * 0.2
      // 중심점 기준으로 좌우 대칭 범위 설정
      const halfRange = (dataRange / 2) + padding
      
      const min = Math.floor(center - halfRange)
      const max = Math.ceil(center + halfRange)
      const range = max - min
      
      let step: number
      if (range <= 5) {
        step = 0.5
      } else if (range <= 20) {
        step = 2
      } else if (range <= 50) {
        step = 5
      } else if (range <= 100) {
        step = 10
      } else {
        step = 20
      }
      
      return { min, max, step }
    }
    
    // 형질별: traitRankData.histogram 사용
    if (chartFilterTrait !== 'overall' && traitRankData?.histogram && traitRankData.histogram.length > 0) {
      const bins = traitRankData.histogram.map(item => item.bin - cowScore)
      // 내 개체(0), 농가 평균, 보은군 평균도 범위에 포함
      const allValues = [...bins, 0, chartDisplayValues.farmScore, chartDisplayValues.regionScore]
      const minData = Math.min(...allValues)
      const maxData = Math.max(...allValues)
      
      console.log(`[${chartFilterTrait}] X축 범위 계산:`, {
        bins: `${bins[0].toFixed(2)} ~ ${bins[bins.length-1].toFixed(2)}`,
        내개체: 0,
        농가평균위치: chartDisplayValues.farmScore.toFixed(2),
        보은군평균위치: chartDisplayValues.regionScore.toFixed(2),
        allValues범위: `${minData.toFixed(2)} ~ ${maxData.toFixed(2)}`,
      })
      
      // 데이터의 중심점 계산
      const center = (minData + maxData) / 2
      // 데이터 범위에 20% 여유 추가
      const dataRange = maxData - minData
      const padding = dataRange * 0.2
      // 중심점 기준으로 좌우 대칭 범위 설정
      const halfRange = (dataRange / 2) + padding
      
      const min = Math.floor(center - halfRange)
      const max = Math.ceil(center + halfRange)
      const range = max - min
      
      let step: number
      if (range <= 5) {
        step = 0.5
      } else if (range <= 20) {
        step = 2
      } else if (range <= 50) {
        step = 5
      } else if (range <= 100) {
        step = 10
      } else {
        step = 20
      }
      
      return { min, max, step }
    }
    
    // 히스토그램 데이터가 없으면 평균 대비 차이로 범위 계산 (폴백)
    const { cowVsFarm, cowVsRegion } = chartDisplayValues
    const maxDiff = Math.max(Math.abs(cowVsFarm), Math.abs(cowVsRegion))
    const targetRange = maxDiff / 0.7

    let step: number
    if (targetRange <= 1) {
      step = 0.2
    } else if (targetRange <= 3) {
      step = 0.5
    } else if (targetRange <= 10) {
      step = 1
    } else if (targetRange <= 30) {
      step = 5
    } else {
      step = 10
    }

    const minRange = step * 3
    const range = Math.max(minRange, Math.ceil(targetRange / step) * step)

    return { min: -range, max: range, step }
  }, [chartFilterTrait, selectionIndexHistogram, traitRankData, chartDisplayValues])

  // X축 틱 계산 (동적 간격)
  const xTicks = useMemo(() => {
    const ticks: number[] = []
    const { min, max, step } = xAxisConfig
    for (let t = min; t <= max; t += step) {
      ticks.push(Math.round(t * 10) / 10) // 부동소수점 오차 방지
    }
    return ticks
  }, [xAxisConfig])

  // 히스토그램 데이터 생성 (실제 데이터 분포 사용)
  const histogramData = useMemo(() => {
    // 전체 선발지수: selectionIndexHistogram 사용
    if (chartFilterTrait === 'overall' && selectionIndexHistogram.length > 0) {
      const histogram = selectionIndexHistogram
      const totalCount = histogram.reduce((sum, item) => sum + item.count, 0)
      
      const bins = histogram.map(item => {
        const cowScore = chartDisplayValues.originalScore
        const relativeBin = item.bin - cowScore
        const percent = (item.count / totalCount) * 100
        const farmPercent = totalCount > 0 ? (item.farmCount / totalCount) * 100 : 0
        
        return {
          midPoint: relativeBin,
          regionPercent: percent,
          percent: percent,
          farmPercent: farmPercent,
          count: item.count,
          farmCount: item.farmCount
        }
      })
      
      // 🔍 실제 히스토그램 데이터 콘솔 로그
      const dataMinMax = { min: Math.min(...bins.map(b => b.midPoint)), max: Math.max(...bins.map(b => b.midPoint)) }
      const percentMinMax = { min: Math.min(...bins.map(b => b.percent)), max: Math.max(...bins.map(b => b.percent)) }
      const calculatedYMax = Math.max(5, Math.ceil(percentMinMax.max * 1.2))
      
      console.log('📊 [전체 선발지수 - 차트 범위 자동 조정]', {
        형질명: '전체 선발지수',
        전체개체수: totalCount,
        '📏 X축': {
          데이터범위: `${dataMinMax.min.toFixed(1)} ~ ${dataMinMax.max.toFixed(1)}`,
          차트범위: `${xAxisConfig.min} ~ ${xAxisConfig.max}`,
          범위크기: `${(xAxisConfig.max - xAxisConfig.min).toFixed(1)}`
        },
        '📏 Y축': {
          데이터최대: `${percentMinMax.max.toFixed(1)}%`,
          차트최대: `${calculatedYMax}%`,
          여유공간: `${((calculatedYMax - percentMinMax.max) / percentMinMax.max * 100).toFixed(0)}%`
        },
        총데이터개수: bins.length,
        샘플: { 첫5개: bins.slice(0, 5), 마지막5개: bins.slice(-5) }
      })
      
      return bins
    }
    
    // 형질별 데이터가 있으면 실제 히스토그램 사용
    if (chartFilterTrait !== 'overall' && traitRankData?.histogram && traitRankData.histogram.length > 0) {
      const histogram = traitRankData.histogram
      const totalCount = histogram.reduce((sum, item) => sum + item.count, 0)
      
      // 백엔드에서 받은 히스토그램을 차트 데이터로 변환
      const bins = histogram.map(item => {
        // bin 값은 구간의 시작값 (예: 110, 115, 120...)
        // 개체 점수 대비 상대 위치로 변환 (내 개체 = 0 기준)
        const cowScore = chartDisplayValues.originalScore
        const relativeBin = item.bin - cowScore
        
        // 백분율 계산
        const percent = (item.count / totalCount) * 100
        const farmPercent = totalCount > 0 ? (item.farmCount / totalCount) * 100 : 0
        
        return {
          midPoint: relativeBin,
          regionPercent: percent,
          percent: percent,
          farmPercent: farmPercent,
          count: item.count,
          farmCount: item.farmCount
        }
      })
      
      // 🔍 실제 히스토그램 데이터 콘솔 로그
      const dataMinMax = { min: Math.min(...bins.map(b => b.midPoint)), max: Math.max(...bins.map(b => b.midPoint)) }
      const percentMinMax = { min: Math.min(...bins.map(b => b.percent)), max: Math.max(...bins.map(b => b.percent)) }
      const calculatedYMax = Math.max(5, Math.ceil(percentMinMax.max * 1.2))
      
      console.log(`📊 [${chartFilterTrait} - 차트 범위 자동 조정]`, {
        형질명: chartFilterTrait,
        전체개체수: totalCount,
        '📏 X축': {
          데이터범위: `${dataMinMax.min.toFixed(1)} ~ ${dataMinMax.max.toFixed(1)}`,
          차트범위: `${xAxisConfig.min} ~ ${xAxisConfig.max}`,
          범위크기: `${(xAxisConfig.max - xAxisConfig.min).toFixed(1)}`
        },
        '📏 Y축': {
          데이터최대: `${percentMinMax.max.toFixed(1)}%`,
          차트최대: `${calculatedYMax}%`,
          여유공간: `${((calculatedYMax - percentMinMax.max) / percentMinMax.max * 100).toFixed(0)}%`
        },
        총데이터개수: bins.length,
        샘플: { 첫5개: bins.slice(0, 5), 마지막5개: bins.slice(-5) }
      })
      
      return bins
    }
    
    // 히스토그램 데이터가 없을 때만 정규분포 곡선 사용 (폴백)
    const range = xAxisConfig.max - xAxisConfig.min
    const std = range / 4

    const normalPDF = (x: number, mean: number = 0) => {
      const exponent = -Math.pow(x - mean, 2) / (2 * Math.pow(std, 2))
      return Math.exp(exponent)
    }

    const bins = []
    const stepSize = range / 100
    for (let x = xAxisConfig.min; x <= xAxisConfig.max; x += stepSize) {
      const pdfValue = normalPDF(x) * 40
      bins.push({
        midPoint: x,
        regionPercent: pdfValue,
        percent: pdfValue
      })
    }

    // 🔍 정규분포 곡선 데이터 콘솔 로그
    console.log('📊 [정규분포 곡선 데이터 - 폴백]', {
      총데이터개수: bins.length,
      X축범위: `${xAxisConfig.min} ~ ${xAxisConfig.max}`,
      표준편차: std,
      첫5개: bins.slice(0, 5),
      마지막5개: bins.slice(-5)
    })

    return bins
  }, [xAxisConfig, chartFilterTrait, traitRankData, chartDisplayValues.originalScore, selectionIndexHistogram])

  // Y축 범위 (실제 데이터에 맞게 조정 - 개체수 기준)
  const maxCount = useMemo(() => {
    if (histogramData.length === 0) return 100
    
    const maxValue = Math.max(...histogramData.map(d => ('count' in d ? d.count : 0) || 0))
    
    // 실제 최대값에 20% 여유만 추가 (너무 빡빡하지 않게)
    const calculatedMax = Math.ceil(maxValue * 1.2)
    
    // 최소 10개체 보장 (데이터가 너무 작을 때만)
    return Math.max(10, calculatedMax)
  }, [histogramData])


  return (
    <Card className="bg-white border border-border rounded-xl">
      <CardContent className="relative p-4 lg:p-6">
        {/* 형질 필터 + 확대 버튼 */}
        <div className="flex items-center justify-between gap-2 mb-4">
          {/* 형질 선택 필터 */}
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-muted-foreground hidden sm:inline">분포 기준:</span>
            <Select
              value={chartFilterTrait}
              onValueChange={(value) => {
                // 같은 값 선택 시 해제 (전체 선발지수로 돌아감)
                if (value === chartFilterTrait && value !== 'overall') {
                  setChartFilterTrait('overall')
                } else {
                  setChartFilterTrait(value)
                }
              }}
            >
              <SelectTrigger className="w-[140px] sm:w-[180px] h-9 text-sm">
                <SelectValue placeholder="전체 선발지수" />
              </SelectTrigger>
              <SelectContent>
                {filters.isActive && (
                  <SelectItem value="overall">전체 선발지수</SelectItem>
                )}
                {/* 모든 형질 표시 (필터 설정과 무관) */}
                {allTraits.length > 0 && (
                  <>
                    {/* 카테고리별로 그룹핑 */}
                    {(['성장', '생산', '체형', '무게', '비율'] as const).map((category) => {
                      const categoryTraits = allTraits.filter(t => t.traitCategory === category)
                      if (categoryTraits.length === 0) return null
                      return (
                        <div key={category}>
                          <div
                            className="px-2 py-1.5 text-xs font-semibold border-t mt-1 pt-2"
                            style={{ color: CATEGORY_COLORS[category] }}
                          >
                            {category} ({categoryTraits.length})
                          </div>
                          {categoryTraits.map((trait, idx) => (
                            <SelectItem key={trait.traitName || idx} value={trait.traitName || ''}>
                              {trait.traitName}
                            </SelectItem>
                          ))}
                        </div>
                      )
                    })}
                  </>
                )}
              </SelectContent>
            </Select>
          </div>
          {/* 확대 버튼 */}
          {/* <button
            onClick={onOpenChartModal}
            className="flex items-center gap-1.5 px-2 sm:px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted rounded-lg transition-colors"
            aria-label="차트 확대">
            <Maximize2 className="w-4 h-4" />
            <span className="hidden sm:inline">확대</span>
          </button> */}
        </div>

        {/* 순위 및 평균 대비 요약 (차트 위에 배치) */}
        <div className="mb-3 sm:mb-5 px-4 py-3 sm:p-5 bg-slate-50 rounded-xl border border-slate-200">
          {/* 모바일: 명확한 레이아웃 */}
          <div className="sm:hidden space-y-2.5">
            {/* 상위 % + 조회 기준 표시 */}
            <div className="flex items-center justify-between mb-2">
              <span className="px-3 py-1 bg-slate-200 text-slate-700 text-sm font-bold rounded-full">
                {chartFilterTrait === 'overall' ? '선발지수' : chartFilterTrait} 조회 기준
              </span>
              <span className="px-3 py-1 bg-primary text-white text-sm font-bold rounded-full">
                상위 {chartDisplayValues.percentile?.toFixed(0) || 0}%
              </span>
            </div>

            {/* 농가 카드 */}
            <div className="p-3 bg-white rounded-lg border-2 border-[#1F3A8F]/30">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-bold text-[#1F3A8F]">농가 내 순위</span>
                {traitRankLoading && chartFilterTrait !== 'overall' ? (
                  <span className="text-lg font-bold text-muted-foreground">...</span>
                ) : (
                  <span className="text-lg font-bold text-[#1F3A8F]">
                    {(chartFilterTrait !== 'overall' ? traitRankData?.farmRank : farmRank) || '-'}위
                    <span className="text-sm text-muted-foreground font-normal ml-1">
                      / {(chartFilterTrait !== 'overall' ? traitRankData?.farmTotal : farmTotal) || 0}두
                    </span>
                  </span>
                )}
              </div>
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm text-muted-foreground">상위</span>
                {traitRankLoading && chartFilterTrait !== 'overall' ? (
                  <span className="text-lg font-bold text-muted-foreground">...</span>
                ) : (
                  <span className="px-2.5 py-0.5 bg-[#1F3A8F] text-white text-sm font-bold rounded-full">
                    {(() => {
                      const rank = chartFilterTrait !== 'overall' ? traitRankData?.farmRank : farmRank
                      const total = chartFilterTrait !== 'overall' ? traitRankData?.farmTotal : farmTotal
                      if (rank && total && total > 0) {
                        return `${Math.round((rank / total) * 100)}%`
                      }
                      return '-'
                    })()}
                  </span>
                )}
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">평균 대비</span>
                {traitRankLoading && chartFilterTrait !== 'overall' ? (
                  <span className="text-lg font-bold text-muted-foreground">...</span>
                ) : (
                  <span className={`text-lg font-bold ${(chartDisplayValues.originalScore - chartDisplayValues.originalFarmScore) >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                    {(chartDisplayValues.originalScore - chartDisplayValues.originalFarmScore) >= 0 ? '+' : ''}
                    {(chartDisplayValues.originalScore - chartDisplayValues.originalFarmScore).toFixed(2)}
                    <span className="text-sm ml-1 font-semibold">
                      {(chartDisplayValues.originalScore - chartDisplayValues.originalFarmScore) >= 0 ? '높음' : '낮음'}
                    </span>
                  </span>
                )}
              </div>
            </div>

            {/* 보은군 카드 */}
            <div className="p-3 bg-white rounded-lg border-2 border-slate-300">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-bold text-slate-600">보은군 내 순위</span>
                {traitRankLoading && chartFilterTrait !== 'overall' ? (
                  <span className="text-lg font-bold text-muted-foreground">...</span>
                ) : (
                  <span className="text-lg font-bold text-slate-600">
                    {(chartFilterTrait !== 'overall' ? traitRankData?.regionRank : regionRank) || '-'}위
                    <span className="text-sm text-muted-foreground font-normal ml-1">
                      / {(chartFilterTrait !== 'overall' ? traitRankData?.regionTotal : regionTotal) || 0}두
                    </span>
                  </span>
                )}
              </div>
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm text-muted-foreground">상위</span>
                {traitRankLoading && chartFilterTrait !== 'overall' ? (
                  <span className="text-lg font-bold text-muted-foreground">...</span>
                ) : (
                  <span className="px-2.5 py-0.5 bg-slate-500 text-white text-sm font-bold rounded-full">
                    {(() => {
                      const rank = chartFilterTrait !== 'overall' ? traitRankData?.regionRank : regionRank
                      const total = chartFilterTrait !== 'overall' ? traitRankData?.regionTotal : regionTotal
                      if (rank && total && total > 0) {
                        return `${Math.round((rank / total) * 100)}%`
                      }
                      return '-'
                    })()}
                  </span>
                )}
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">평균 대비</span>
                {traitRankLoading && chartFilterTrait !== 'overall' ? (
                  <span className="text-lg font-bold text-muted-foreground">...</span>
                ) : (
                  <span className={`text-lg font-bold ${(chartDisplayValues.originalScore - chartDisplayValues.originalRegionScore) >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                    {(chartDisplayValues.originalScore - chartDisplayValues.originalRegionScore) >= 0 ? '+' : ''}
                    {(chartDisplayValues.originalScore - chartDisplayValues.originalRegionScore).toFixed(2)}
                    <span className="text-sm ml-1 font-semibold">
                      {(chartDisplayValues.originalScore - chartDisplayValues.originalRegionScore) >= 0 ? '높음' : '낮음'}
                    </span>
                  </span>
                )}
              </div>
            </div>
          </div>

          {/* 데스크탑: 기존 레이아웃 */}
          <div className="hidden sm:block">
            {/* 현재 보고 있는 조회 기준 표시 */}
            {/* <div className="flex items-center justify-center mb-4">
              <span className="px-4 py-1.5 bg-slate-200 text-slate-700 text-base font-bold rounded-full">
                {chartFilterTrait === 'overall' ? '전체 선발지수' : chartFilterTrait} 조회 기준
              </span>
            </div> */}

            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
              {/* 농가 내 순위 */}
              <div className="flex flex-col items-center justify-center p-4 bg-white rounded-xl border-2 border-[#1F3A8F]/30 shadow-sm">
                <span className="text-2xl text-muted-foreground mb-2 font-medium">농가 내 순위</span>
                <div className="flex items-baseline gap-1.5">
                  {traitRankLoading && chartFilterTrait !== 'overall' ? (
                    <span className="text-2xl font-bold text-muted-foreground">...</span>
                  ) : (
                    <>
                      <span className="text-2xl font-bold text-[#1F3A8F]">
                        {(chartFilterTrait !== 'overall' ? traitRankData?.farmRank : farmRank) || '-'}위
                      </span>
                      <span className="text-base text-muted-foreground">
                        / {(chartFilterTrait !== 'overall' ? traitRankData?.farmTotal : farmTotal) || 0}두
                      </span>
                    </>
                  )}
                </div>
                {/* 농가 상위 % */}
                <span className="mt-2 px-3 py-1 bg-[#1F3A8F] text-white text-sm font-bold rounded-full">
                  상위 {(() => {
                    const rank = chartFilterTrait !== 'overall' ? traitRankData?.farmRank : farmRank
                    const total = chartFilterTrait !== 'overall' ? traitRankData?.farmTotal : farmTotal
                    if (rank && total && total > 0) {
                      return Math.round((rank / total) * 100)
                    }
                    return '-'
                  })()}%
                </span>
              </div>

              {/* 보은군 내 순위 */}
              <div className="flex flex-col items-center justify-center p-4 bg-white rounded-xl border-2 border-slate-300 shadow-sm">
                <span className="text-2xl text-muted-foreground mb-2 font-medium">보은군 내 순위</span>
                <div className="flex items-baseline gap-1.5">
                  {traitRankLoading && chartFilterTrait !== 'overall' ? (
                    <span className="text-2xl font-bold text-muted-foreground">...</span>
                  ) : (
                    <>
                      <span className="text-2xl font-bold text-slate-600">
                        {(chartFilterTrait !== 'overall' ? traitRankData?.regionRank : regionRank) || '-'}위
                      </span>
                      <span className="text-base text-muted-foreground">
                        / {(chartFilterTrait !== 'overall' ? traitRankData?.regionTotal : regionTotal) || 0}두
                      </span>
                    </>
                  )}
                </div>
                {/* 보은군 상위 % */}
                <span className="mt-2 px-3 py-1 bg-slate-500 text-white text-sm font-bold rounded-full">
                  상위 {(() => {
                    const rank = chartFilterTrait !== 'overall' ? traitRankData?.regionRank : regionRank
                    const total = chartFilterTrait !== 'overall' ? traitRankData?.regionTotal : regionTotal
                    if (rank && total && total > 0) {
                      return Math.round((rank / total) * 100)
                    }
                    return '-'
                  })()}%
                </span>
              </div>

              {/* 농가 평균 대비 */}
              <div className={`flex flex-col items-center justify-center p-4 bg-white rounded-xl border-2 shadow-sm ${(chartDisplayValues.originalScore - chartDisplayValues.originalFarmScore) >= 0 ? 'border-green-300' : 'border-red-300'}`}>
                <span className="text-2xl text-muted-foreground mb-2 font-medium">농가 평균 대비</span>
                <div className="flex items-baseline gap-1.5">
                  {traitRankLoading && chartFilterTrait !== 'overall' ? (
                    <span className="text-2xl font-bold text-muted-foreground">...</span>
                  ) : (
                    <>
                      <span className={`text-2xl font-bold ${(chartDisplayValues.originalScore - chartDisplayValues.originalFarmScore) >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                        {(chartDisplayValues.originalScore - chartDisplayValues.originalFarmScore) >= 0 ? '+' : ''}
                        {(chartDisplayValues.originalScore - chartDisplayValues.originalFarmScore).toFixed(2)}
                      </span>
                      <span className={`text-base font-semibold ${(chartDisplayValues.originalScore - chartDisplayValues.originalFarmScore) >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                        {(chartDisplayValues.originalScore - chartDisplayValues.originalFarmScore) >= 0 ? '높음' : '낮음'}
                      </span>
                    </>
                  )}
                </div>
              </div>

              {/* 보은군 평균 대비 */}
              <div className={`flex flex-col items-center justify-center p-4 bg-white rounded-xl border-2 shadow-sm ${(chartDisplayValues.originalScore - chartDisplayValues.originalRegionScore) >= 0 ? 'border-green-300' : 'border-red-300'}`}>
                <span className="text-2xl text-muted-foreground mb-2 font-medium">보은군 평균 대비</span>
                <div className="flex items-baseline gap-1.5">
                  {traitRankLoading && chartFilterTrait !== 'overall' ? (
                    <span className="text-2xl font-bold text-muted-foreground">...</span>
                  ) : (
                    <>
                      <span className={`text-2xl font-bold ${(chartDisplayValues.originalScore - chartDisplayValues.originalRegionScore) >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                        {(chartDisplayValues.originalScore - chartDisplayValues.originalRegionScore) >= 0 ? '+' : ''}
                        {(chartDisplayValues.originalScore - chartDisplayValues.originalRegionScore).toFixed(2)}
                      </span>
                      <span className={`text-base font-semibold ${(chartDisplayValues.originalScore - chartDisplayValues.originalRegionScore) >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                        {(chartDisplayValues.originalScore - chartDisplayValues.originalRegionScore) >= 0 ? '높음' : '낮음'}
                      </span>
                    </>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="h-[400px] sm:h-[440px] md:h-[470px] bg-gradient-to-b from-slate-50 to-slate-100 rounded-xl p-2 sm:p-4 relative" role="img" aria-label="농가 및 보은군 내 개체 위치">
          {/* 로딩 상태 */}
          {(traitRankLoading && chartFilterTrait !== 'overall') || histogramData.length === 0 ? (
            <div className="absolute inset-0 flex flex-col items-center justify-center bg-slate-50/80 rounded-xl z-10">
              <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">
                {chartFilterTrait === 'overall' ? '전체 선발지수' : chartFilterTrait} 분포 데이터 로딩 중...
              </p>
            </div>
          ) : (
            <ResponsiveContainer width="100%" height="100%">
              <ComposedChart
                data={histogramData}
                margin={isMobileView ? { top: 110, right: 10, left: 5, bottom: 25 } : { top: 110, right: 20, left: 10, bottom: 45 }}
              >
              <defs>
                {/* 보은군 - Blue */}
                <linearGradient id="regionGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#2563eb" stopOpacity={0.8} />
                  <stop offset="100%" stopColor="#60a5fa" stopOpacity={0.4} />
                </linearGradient>
                {/* 농가 - Amber */}
                <linearGradient id="farmGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#f59e0b" stopOpacity={0.9} />
                  <stop offset="100%" stopColor="#fbbf24" stopOpacity={0.6} />
                </linearGradient>
                {/* 이 개체 구간 강조 - Primary */}
                <linearGradient id="highlightGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#1F3A8F" stopOpacity={1} />
                  <stop offset="100%" stopColor="#1F3A8F" stopOpacity={0.7} />
                </linearGradient>
                {/* 보은군 분포 영역 채우기 - Blue */}
                <linearGradient id="areaFillGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#3b82f6" stopOpacity={0.4} />
                  <stop offset="100%" stopColor="#93c5fd" stopOpacity={0.1} />
                </linearGradient>
                {/* 농가 분포 영역 채우기 - Amber */}
                <linearGradient id="farmAreaGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#f59e0b" stopOpacity={0.4} />
                  <stop offset="100%" stopColor="#fcd34d" stopOpacity={0.1} />
                </linearGradient>
                {/* 내 개체 중심 차트용 화살표 마커는 Customized 내부에서 정의 */}
              </defs>
              <XAxis
                dataKey="midPoint"
                type="number"
                domain={[xAxisConfig.min, xAxisConfig.max]}
                ticks={xTicks}
                tick={{ fontSize: isMobileView ? 16 : 18, fill: '#64748b', fontWeight: 700 }}
                tickLine={false}
                axisLine={{ stroke: '#cbd5e1', strokeWidth: 2 }}
                tickFormatter={(value) => {
                  if (value === 0) {
                    // cowNo의 뒤에서 5번째부터 2번째까지 4자리 추출 (예: KOR002203259861 -> 5986)
                    const shortId = cowNo ? cowNo.slice(-5, -1) : ''
                    return shortId || '0'
                  }
                  return value > 0 ? `+${value}` : `${value}`
                }}
              />
              <YAxis
                axisLine={{ stroke: '#cbd5e1', strokeWidth: 1 }}
                tickLine={false}
                tick={{ fontSize: isMobileView ? 15 : 17, fill: '#64748b', fontWeight: 700 }}
                width={isMobileView ? 45 : 60}
                domain={[0, Math.ceil(maxCount)]}
                tickFormatter={(value) => `${Math.round(value)}`}
              />

              {/* Tooltip */}
              <Tooltip
                content={({ active, payload }) => {
                  if (!active || !payload || payload.length === 0) return null
                  
                  const data = payload[0].payload
                  const cowScore = chartDisplayValues.originalScore
                  const binStart = Math.round((data.midPoint + cowScore) * 100) / 100
                  
                  return (
                    <div className="bg-white p-3 border border-border rounded-lg shadow-lg">
                      <p className="text-sm font-semibold mb-2">
                        구간: {binStart >= 0 ? '+' : ''}{binStart.toFixed(2)}
                      </p>
                      <p className="text-sm text-muted-foreground">
                        개체 수: <span className="font-bold text-foreground">{data.count || 0}마리</span>
                      </p>
                      <p className="text-sm text-muted-foreground">
                        비율: <span className="font-bold text-foreground">{data.percent?.toFixed(1) || 0}%</span>
                      </p>
                      {data.farmCount !== undefined && (
                        <p className="text-sm text-blue-600 mt-1">
                          내 농가: <span className="font-bold">{data.farmCount}마리</span>
                        </p>
                      )}
                    </div>
                  )
                }}
                cursor={{ fill: 'rgba(59, 130, 246, 0.1)' }}
              />

              {/* 실제 데이터 분포 (Area 그래프 + 점 표시) */}
              <Area
                type="linear"
                dataKey="count"
                stroke="#64748b"
                strokeWidth={2.5}
                fill="url(#areaFillGradient)"
                dot={{ r: 4, fill: '#64748b', strokeWidth: 2, stroke: '#fff' }}
                activeDot={{ r: 6, fill: '#3b82f6', strokeWidth: 2, stroke: '#fff' }}
                isAnimationActive={false}
              />

              {/* 보은군 평균 위치 */}
              <ReferenceLine
                x={chartDisplayValues.regionScore}
                stroke="#64748b"
                strokeWidth={3}
                strokeDasharray="6 3"
              />

              {/* 농가 평균 위치 */}
              <ReferenceLine
                x={chartDisplayValues.farmScore}
                stroke="#1F3A8F"
                strokeWidth={3}
                strokeDasharray="6 3"
              />

              {/* 내 개체 위치 (항상 0) */}
              <ReferenceLine
                x={0}
                stroke="#1482B0"
                strokeWidth={4}
              />

              {/* 내 개체 중심 차트 - 배지 + 화살표 */}
              <Customized
                component={(props: any) => {
                  const { xAxisMap, yAxisMap, width: containerWidth } = props
                  if (!xAxisMap || !yAxisMap) return null

                  const xAxis = Object.values(xAxisMap)[0] as any
                  const yAxis = Object.values(yAxisMap)[0] as any
                  if (!xAxis || !yAxis) return null

                  const chartWidth = xAxis.width
                  const chartX = xAxis.x
                  const chartTop = yAxis.y
                  const chartBottom = yAxis.y + yAxis.height
                  const chartHeight = chartBottom - chartTop

                  // 모바일 여부 판단
                  const isMobile = containerWidth < 500

                  // X축 도메인
                  const [domainMin, domainMax] = xAxis.domain || [-1, 1]
                  const domainRange = domainMax - domainMin

                  // σ 값을 X 좌표로 변환
                  const sigmaToX = (sigma: number) => {
                    const ratio = (sigma - domainMin) / domainRange
                    return chartX + ratio * chartWidth
                  }

                  // 대비값
                  const { cowVsFarm, cowVsRegion } = chartDisplayValues

                  // 개체가 앞서는지 뒤처지는지
                  const isAhead = cowVsFarm >= 0 && cowVsRegion >= 0
                  const isBehind = cowVsFarm < 0 && cowVsRegion < 0

                  // 색상 설정
                  const mainColor = isAhead ? '#22c55e' : isBehind ? '#ef4444' : '#f59e0b'

                  // X 좌표 계산
                  const cowX = sigmaToX(0)  // 개체는 항상 0
                  const farmX = sigmaToX(chartDisplayValues.farmScore)
                  const regionX = sigmaToX(chartDisplayValues.regionScore)

                  // 배지 클램핑 함수
                  const clamp = (x: number, halfWidth: number) => {
                    return Math.max(chartX + halfWidth + 5, Math.min(x, chartX + chartWidth - halfWidth - 5))
                  }

                  // 배지 크기 (더 크게) - 모바일에서 텍스트가 한 줄로 나오도록 너비 확보
                  const cowBadgeW = isMobile ? 105 : 135
                  const avgBadgeW = isMobile ? 118 : 135
                  const regionBadgeW = isMobile ? 125 : 145
                  const badgeH = isMobile ? 42 : 48

                  // Y 위치 계산 - 겹치지 않게 배치
                  // 상단: 좋음/나쁨 -> 내 개체 배지
                  // 차트 내부: 농가 배지+화살표 -> 보은군 배지+화살표
                  const cowBadgeY = chartTop - (isMobile ? 68 : 72)

                  // 차트 내부 영역을 3등분해서 배치 (더 넉넉한 간격)
                  const farmBadgeY = chartTop + chartHeight * (isMobile ? 0.04 : 0.02)
                  const farmArrowY = farmBadgeY + badgeH + (isMobile ? 22 : 28)
                  const regionBadgeY = chartTop + chartHeight * (isMobile ? 0.36 : 0.32)
                  const regionArrowY = regionBadgeY + badgeH + (isMobile ? 22 : 28)

                  return (
                    <g>
                      {/* 화살표 마커 정의 */}
                      <defs>
                        {/* 오른쪽 화살표 (→) - markerEnd 용 */}
                        <marker id="arrowGreen" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
                          <path d="M0,0 L0,6 L9,3 z" fill="#22c55e" />
                        </marker>
                        <marker id="arrowRed" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
                          <path d="M0,0 L0,6 L9,3 z" fill="#ef4444" />
                        </marker>
                        {/* 왼쪽 화살표 (←) - markerStart 용 (auto-start-reverse) */}
                        <marker id="arrowRedLeft" markerWidth="10" markerHeight="10" refX="1" refY="3" orient="auto-start-reverse">
                          <path d="M0,0 L0,6 L9,3 z" fill="#ef4444" />
                        </marker>
                      </defs>

                      {/* 좋음/나쁨 표시 - 차트 상단 양쪽 끝 */}
                      <text
                        x={chartX + chartWidth - 5}
                        y={cowBadgeY - 10}
                        textAnchor="end"
                        fill="#22c55e"
                        fontSize={isMobile ? 14 : 16}
                        fontWeight={700}
                      >
                        좋음 →
                      </text>
                      <text
                        x={chartX + 5}
                        y={cowBadgeY - 10}
                        textAnchor="start"
                        fill="#ef4444"
                        fontSize={isMobile ? 14 : 16}
                        fontWeight={700}
                      >
                        ← 나쁨
                      </text>

                      {/* 내 개체 배지 (상단 고정) - 선발지수 값 포함 */}
                      <rect
                        x={clamp(cowX, cowBadgeW / 2) - cowBadgeW / 2}
                        y={cowBadgeY}
                        width={cowBadgeW}
                        height={badgeH}
                        rx={8}
                        fill="#1482B0"
                        filter="drop-shadow(0 2px 6px rgba(0,0,0,0.25))"
                      />
                      <text
                        x={clamp(cowX, cowBadgeW / 2)}
                        y={cowBadgeY + (isMobile ? 16 : 18)}
                        textAnchor="middle"
                        fill="white"
                        fontSize={isMobile ? 13 : 15}
                        fontWeight={600}
                      >
                        {cowNo ? cowNo.slice(-5, -1) : '0'}
                      </text>
                      <text
                        x={clamp(cowX, cowBadgeW / 2)}
                        y={cowBadgeY + (isMobile ? 34 : 40)}
                        textAnchor="middle"
                        fill="white"
                        fontSize={isMobile ? 18 : 22}
                        fontWeight={800}
                      >
                        {chartDisplayValues.originalScore >= 0 ? '+' : ''}{chartDisplayValues.originalScore.toFixed(2)}
                      </text>
                      <line
                        x1={clamp(cowX, cowBadgeW / 2)}
                        y1={cowBadgeY + badgeH}
                        x2={cowX}
                        y2={chartTop}
                        stroke="#1482B0"
                        strokeWidth={2}
                      />

                      {/* 농가 평균 배지 - 선발지수 값 포함 */}
                      <rect
                        x={clamp(farmX, avgBadgeW / 2) - avgBadgeW / 2}
                        y={farmBadgeY}
                        width={avgBadgeW}
                        height={badgeH}
                        rx={8}
                        fill="#1F3A8F"
                        filter="drop-shadow(0 2px 6px rgba(0,0,0,0.2))"
                      />
                      <text
                        x={clamp(farmX, avgBadgeW / 2)}
                        y={farmBadgeY + (isMobile ? 16 : 18)}
                        textAnchor="middle"
                        fill="white"
                        fontSize={isMobile ? 12 : 14}
                        fontWeight={600}
                      >
                        농가 평균
                      </text>
                      <text
                        x={clamp(farmX, avgBadgeW / 2)}
                        y={farmBadgeY + (isMobile ? 34 : 40)}
                        textAnchor="middle"
                        fill="white"
                        fontSize={isMobile ? 17 : 20}
                        fontWeight={800}
                      >
                        {chartDisplayValues.originalFarmScore >= 0 ? '+' : ''}{chartDisplayValues.originalFarmScore.toFixed(2)}
                      </text>
                      <line
                        x1={clamp(farmX, avgBadgeW / 2)}
                        y1={farmBadgeY + badgeH}
                        x2={farmX}
                        y2={farmBadgeY + badgeH + 12}
                        stroke="#1F3A8F"
                        strokeWidth={2}
                      />

                      {/* 보은군 평균 배지 - 선발지수 값 포함 */}
                      <rect
                        x={clamp(regionX, regionBadgeW / 2) - regionBadgeW / 2}
                        y={regionBadgeY}
                        width={regionBadgeW}
                        height={badgeH}
                        rx={8}
                        fill="#64748b"
                        filter="drop-shadow(0 2px 6px rgba(0,0,0,0.2))"
                      />
                      <text
                        x={clamp(regionX, regionBadgeW / 2)}
                        y={regionBadgeY + (isMobile ? 16 : 18)}
                        textAnchor="middle"
                        fill="white"
                        fontSize={isMobile ? 12 : 14}
                        fontWeight={600}
                      >
                        보은군 평균
                      </text>
                      <text
                        x={clamp(regionX, regionBadgeW / 2)}
                        y={regionBadgeY + (isMobile ? 34 : 40)}
                        textAnchor="middle"
                        fill="white"
                        fontSize={isMobile ? 17 : 20}
                        fontWeight={800}
                      >
                        {chartDisplayValues.originalRegionScore >= 0 ? '+' : ''}{chartDisplayValues.originalRegionScore.toFixed(2)}
                      </text>
                      <line
                        x1={clamp(regionX, regionBadgeW / 2)}
                        y1={regionBadgeY + badgeH}
                        x2={regionX}
                        y2={regionBadgeY + badgeH + 12}
                        stroke="#64748b"
                        strokeWidth={2}
                      />

                      {/* 농가 vs 개체 거리 화살표 - 농가 배지 바로 아래 */}
                      {Math.abs(cowVsFarm) > 0.05 && (
                        <g>
                          {/* 화살표 머리 및 막대선 */}
                          {(() => {
                            const arrowBaseOffset = isMobile ? 10 : 16
                            const arrowTipOffset = isMobile ? 10 : 16
                            const arrowHeight = isMobile ? 8 : 12
                            // 화살표 머리 시작점 (막대기 끝점)
                            const arrowHeadStart = cowVsFarm >= 0
                              ? cowX - arrowBaseOffset - arrowTipOffset
                              : cowX + arrowBaseOffset + arrowTipOffset
                            return (
                              <>
                                {/* 막대선: 화살표 머리 시작점까지만 */}
                                <line
                                  x1={cowVsFarm >= 0 ? farmX + 5 : farmX - 5}
                                  y1={farmArrowY}
                                  x2={arrowHeadStart}
                                  y2={farmArrowY}
                                  stroke={cowVsFarm >= 0 ? '#22c55e' : '#ef4444'}
                                  strokeWidth={isMobile ? 3 : 4}
                                />
                                {/* 화살표 머리: 내 개체선에 딱 맞게 */}
                                <polygon
                                  points={cowVsFarm >= 0
                                    ? `${arrowHeadStart},${farmArrowY - arrowHeight} ${arrowHeadStart},${farmArrowY + arrowHeight} ${cowX},${farmArrowY}`
                                    : `${arrowHeadStart},${farmArrowY - arrowHeight} ${arrowHeadStart},${farmArrowY + arrowHeight} ${cowX},${farmArrowY}`
                                  }
                                  fill={cowVsFarm >= 0 ? '#22c55e' : '#ef4444'}
                                />
                              </>
                            )
                          })()}
                          <rect
                            x={(farmX + cowX) / 2 - (isMobile ? 38 : 48)}
                            y={farmArrowY - (isMobile ? 28 : 34)}
                            width={isMobile ? 76 : 96}
                            height={isMobile ? 24 : 30}
                            rx={6}
                            fill={cowVsFarm >= 0 ? '#22c55e' : '#ef4444'}
                          />
                          <text
                            x={(farmX + cowX) / 2}
                            y={farmArrowY - (isMobile ? 11 : 14)}
                            textAnchor="middle"
                            fill="white"
                            fontSize={isMobile ? 15 : 18}
                            fontWeight={800}
                          >
                            {cowVsFarm >= 0 ? '+' : ''}{cowVsFarm.toFixed(2)}
                          </text>
                        </g>
                      )}

                      {/* 보은군 vs 개체 거리 화살표 - 보은군 배지 바로 아래 */}
                      {Math.abs(cowVsRegion) > 0.05 && (
                        <g>
                          {/* 화살표 머리 및 막대선 */}
                          {(() => {
                            const arrowBaseOffset = isMobile ? 10 : 16
                            const arrowTipOffset = isMobile ? 10 : 16
                            const arrowHeight = isMobile ? 8 : 12
                            // 화살표 머리 시작점 (막대기 끝점)
                            const arrowHeadStart = cowVsRegion >= 0
                              ? cowX - arrowBaseOffset - arrowTipOffset
                              : cowX + arrowBaseOffset + arrowTipOffset
                            return (
                              <>
                                {/* 막대선: 화살표 머리 시작점까지만 */}
                                <line
                                  x1={cowVsRegion >= 0 ? regionX + 5 : regionX - 5}
                                  y1={regionArrowY}
                                  x2={arrowHeadStart}
                                  y2={regionArrowY}
                                  stroke={cowVsRegion >= 0 ? '#22c55e' : '#ef4444'}
                                  strokeWidth={isMobile ? 3 : 4}
                                />
                                {/* 화살표 머리: 내 개체선에 딱 맞게 */}
                                <polygon
                                  points={cowVsRegion >= 0
                                    ? `${arrowHeadStart},${regionArrowY - arrowHeight} ${arrowHeadStart},${regionArrowY + arrowHeight} ${cowX},${regionArrowY}`
                                    : `${arrowHeadStart},${regionArrowY - arrowHeight} ${arrowHeadStart},${regionArrowY + arrowHeight} ${cowX},${regionArrowY}`
                                  }
                                  fill={cowVsRegion >= 0 ? '#22c55e' : '#ef4444'}
                                />
                              </>
                            )
                          })()}
                          <rect
                            x={(regionX + cowX) / 2 - (isMobile ? 38 : 48)}
                            y={regionArrowY - (isMobile ? 28 : 34)}
                            width={isMobile ? 76 : 96}
                            height={isMobile ? 24 : 30}
                            rx={6}
                            fill={cowVsRegion >= 0 ? '#22c55e' : '#ef4444'}
                          />
                          <text
                            x={(regionX + cowX) / 2}
                            y={regionArrowY - (isMobile ? 11 : 14)}
                            textAnchor="middle"
                            fill="white"
                            fontSize={isMobile ? 15 : 18}
                            fontWeight={800}
                          >
                            {cowVsRegion >= 0 ? '+' : ''}{cowVsRegion.toFixed(2)}
                          </text>
                        </g>
                      )}

                    </g>
                  )
                }}
              />
            </ComposedChart>
          </ResponsiveContainer>
          )}
        </div>

        {/* 범례 */}
        {/* <div className="flex items-center justify-center gap-4 sm:gap-6 mt-4 pt-4 border-t border-border">
          <div className="flex items-center gap-1.5 sm:gap-2">
            <div className="w-3 h-3 sm:w-4 sm:h-4 rounded bg-slate-500"></div>
            <span className="text-sm sm:text-sm text-muted-foreground">보은군 평균</span>
          </div>
          <div className="flex items-center gap-1.5 sm:gap-2">
            <div className="w-3 h-3 sm:w-4 sm:h-4 rounded bg-[#1F3A8F]"></div>
            <span className="text-sm sm:text-sm text-muted-foreground">농가 평균</span>
          </div>
          <div className="flex items-center gap-1.5 sm:gap-2">
            <div className="w-3 h-3 sm:w-4 sm:h-4 rounded bg-[#1482B0]"></div>
            <span className="text-sm sm:text-sm font-medium text-foreground">{displayCowNumber.slice(-4)} 개체</span>
          </div>
        </div> */}

      </CardContent>
    </Card>
  )
}
