/**
 * ========================================
 * 대시보드 메인 페이지
 * ========================================
 *
 * @description
 * 농장의 유전체/유전자/MPT 검사 현황을 한눈에 보여주는 대시보드
 *
 * @features
 * 1. 총 검사 개체 수 (유전체/유전자/번식능력 구분)
 * 2. 친자감별 결과 (도넛 차트)
 * 3. MPT 검사 현황 (에너지/단백질/간/미네랄)
 * 4. 보은군 내 농가 위치 (정규분포 차트)
 * 5. 연도별 육종가 추이 (막대 차트)
 * 6. 카테고리별 보은군 대비 비교 (레이더 + 바 차트)
 */
'use client'

import { AppSidebar } from "@/components/layout/app-sidebar"
import { SiteHeader } from "@/components/layout/site-header"
import {
  SidebarInset,
  SidebarProvider,
} from "@/components/ui/sidebar"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import apiClient from "@/lib/api-client"
import { farmApi } from "@/lib/api/farm.api"
import { DashboardStatsDto, FarmRegionRankingDto, YearlyTraitTrendDto, genomeApi } from "@/lib/api/genome.api"
import { mptApi, MptStatisticsDto } from "@/lib/api/mpt.api"
import { useAuthStore } from "@/store/auth-store"
import { useFilterStore } from "@/store/filter-store"
import { TRAIT_CATEGORIES, NEGATIVE_TRAITS } from "@/constants/traits"
import {
  AlertCircle,
  CheckCircle2,
  ChevronDown,
  Clock,
  Dna,
  MapPin,
  Target,
  TrendingDown,
  TrendingUp,
  XCircle
} from "lucide-react"
import { useEffect, useMemo, useState } from "react"
import { AuthGuard } from "@/components/auth/auth-guard"
import { useRouter } from "next/navigation"
import {
  Area,
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  ComposedChart,
  Customized,
  Pie,
  PieChart,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis
} from 'recharts'

export default function DashboardPage() {
  // ========================================
  // 1. 기본 상태 관리
  // ========================================
  const router = useRouter()
  const { user } = useAuthStore()
  const { filters } = useFilterStore()

  // 농장 정보
  const [farmNo, setFarmNo] = useState<number | null>(null)
  const [loading, setLoading] = useState(true)

  // 대시보드 통계 데이터
  const [stats, setStats] = useState<DashboardStatsDto | null>(null)
  const [farmRanking, setFarmRanking] = useState<FarmRegionRankingDto | null>(null)
  const [mptStats, setMptStats] = useState<MptStatisticsDto | null>(null)

  // ========================================
  // 2. 모바일 감지 및 필터 관련 상태
  // ========================================

  // 모바일 감지 (640px 이하)
  const [isMobile, setIsMobile] = useState(false)
  useEffect(() => {
    const checkMobile = () => setIsMobile(window.innerWidth < 640)
    checkMobile()
    window.addEventListener('resize', checkMobile)
    return () => window.removeEventListener('resize', checkMobile)
  }, [])

  /**
   * 대표 형질 선택 로직
   * @description
   * - 고정된(pinnedTraits) 형질 중 selectedTraits 순서상 첫 번째
   * - 고정되지 않은 형질은 무시
   * - 없으면 기본값 '도체중'
   */
  const primaryTrait = (() => {
    const pinnedTraits = filters.pinnedTraits || []
    const selectedTraits = filters.selectedTraits || []
    for (const trait of selectedTraits) {
      if (pinnedTraits.includes(trait)) {
        return trait
      }
    }
    return '도체중'
  })()

  // 연도별 육종가 추이 차트용 형질 선택 (localStorage 연동)
  const [selectedTrait, setSelectedTrait] = useState<string>(() => {
    if (typeof window !== 'undefined') {
      return localStorage.getItem('dashboard_trait') || primaryTrait
    }
    return primaryTrait
  })
  const [traitTrendData, setTraitTrendData] = useState<YearlyTraitTrendDto | null>(null)
  const [traitTrendLoading, setTraitTrendLoading] = useState(false)

  /**
   * 농가 위치 차트 분포 기준
   * @description
   * - 필터 활성: 'overall' (전체 선발지수, 35개 형질 평균)
   * - 필터 비활성: primaryTrait (대표 형질)
   */
  const [distributionBasis, setDistributionBasis] = useState<string>(() => {
    return filters.isActive ? 'overall' : primaryTrait
  })

  // 필터 비활성화 시 'overall' → 대표 형질로 변경
  useEffect(() => {
    if (!filters.isActive && distributionBasis === 'overall') {
      setDistributionBasis(primaryTrait)
    }
  }, [filters.isActive, distributionBasis, primaryTrait])

  // 대표 형질 변경 시 연동
  useEffect(() => {
    setSelectedTrait(primaryTrait)
    if (distributionBasis !== 'overall') {
      setDistributionBasis(primaryTrait)
    }
  }, [primaryTrait])

  // 모든 형질 목록 (카테고리별 평탄화)
  const allTraits = Object.entries(TRAIT_CATEGORIES).flatMap(([cat, traits]) =>
    traits.map(t => ({ category: cat, trait: t }))
  )

  // ========================================
  // 3. 데이터 로드 (useEffect)
  // ========================================

  /**
   * 농장 정보 로드
   * @description 사용자의 첫 번째 농장 정보를 가져옴
   */
  useEffect(() => {
    const fetchFarm = async () => {
      setLoading(true)
      try {
        const userId = user?.pkUserNo
        const farms: any[] = userId
          ? await apiClient.get(`/farm?userId=${userId}`)
          : await farmApi.findAll()

        if (farms && farms.length > 0) {
          setFarmNo(farms[0].pkFarmNo)
        }
      } catch (error) {
        console.error('농장 정보 로드 실패:', error)
      } finally {
        setLoading(false)
      }
    }

    if (user) {
      fetchFarm()
    }
    // user가 없으면 loading 상태 유지 (AuthGuard에서 처리)
  }, [user])

  /**
   * 대시보드 통계 데이터 로드
   * @description
   * - getDashboardStats: 총 검사 개체, 친자감별, 연도별 추이
   * - getFarmRegionRanking: 보은군 내 농가 순위 (필터 가중치 적용)
   * - getMptStatistics: 번식능력검사 통계
   */
  useEffect(() => {
    const fetchStats = async () => {
      if (!farmNo) return

      // 필터가 활성화되고 형질이 선택되어 있으면 가중치 조건 생성
      const traitConditions = filters.isActive && filters.selectedTraits && filters.selectedTraits.length > 0
        ? filters.selectedTraits.map(traitNm => ({
          traitNm,
          weight: (filters.traitWeights as Record<string, number>)[traitNm] || 1
        }))
        : undefined

      try {
        const [statsData, rankingData, mptStatsData] = await Promise.all([
          genomeApi.getDashboardStats(farmNo),
          genomeApi.getFarmRegionRanking(farmNo, traitConditions),
          mptApi.getMptStatistics(farmNo).catch(() => null)
        ])
        setStats(statsData)
        setFarmRanking(rankingData)
        setMptStats(mptStatsData)
      } catch (error) {
        console.error('대시보드 통계 로드 실패:', error)
      }
    }
    fetchStats()
  }, [farmNo, filters.isActive, filters.selectedTraits, filters.traitWeights])

  /**
   * 연도별 형질 추이 데이터 로드
   * @description 선택된 형질의 최근 3년 육종가 추이
   */
  useEffect(() => {
    const fetchTraitTrend = async () => {
      if (!farmNo || !selectedTrait) return
      setTraitTrendLoading(true)
      try {
        const found = allTraits.find(t => t.trait === selectedTrait)
        if (found) {
          const data = await genomeApi.getYearlyTraitTrend(farmNo, found.category, found.trait)
          setTraitTrendData(data)
        }
      } catch (error) {
        console.error('연도별 형질 추이 로드 실패:', error)
      } finally {
        setTraitTrendLoading(false)
      }
    }
    fetchTraitTrend()
  }, [farmNo, selectedTrait])

  /**
   * 선택된 형질을 localStorage에 저장
   * @description 페이지 새로고침 시에도 선택 유지
   */
  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('dashboard_trait', selectedTrait)
    }
  }, [selectedTrait])

  // ========================================
  // 4. 계산된 값들 (파생 데이터)
  // ========================================

  const currentYear = new Date().getFullYear()
  const lastYear = currentYear - 1
  const last3Years = [currentYear - 2, currentYear - 1, currentYear]

  // 올해/작년 통계
  const thisYearStats = stats?.yearlyStats?.find(s => s.year === currentYear)
  const lastYearStats = stats?.yearlyStats?.find(s => s.year === lastYear)

  // 전년 대비 검사 개체 수 변화
  const totalChange = (thisYearStats?.totalRequests || 0) - (lastYearStats?.totalRequests || 0)

  // 분석 완료율 (분석 완료 / 총 의뢰)
  const completionRate = stats?.summary.totalRequests
    ? Math.round((stats.summary.analyzedCount / stats.summary.totalRequests) * 100)
    : 0
  const lastYearCompletionRate = lastYearStats?.analyzeRate || 0
  const completionChange = completionRate - lastYearCompletionRate

  /**
   * 친자 일치율 계산
   * @description
   * - 분자: 분석 완료 (부모 일치)
   * - 분모: 분석 완료 + 부 불일치 + 모 불일치 + 모 이력제부재
   */
  const totalAnalyzed = stats?.paternityStats
    ? (stats.paternityStats.analysisComplete + stats.paternityStats.sireMismatch + stats.paternityStats.damMismatch + stats.paternityStats.damNoRecord)
    : 0
  const paternityMatchRate = totalAnalyzed > 0
    ? Math.round((stats!.paternityStats.analysisComplete / totalAnalyzed) * 100)
    : 0
  const lastYearPaternityRate = lastYearStats?.sireMatchRate || 0
  const paternityChange = paternityMatchRate - lastYearPaternityRate

  // 친자감별 도넛 차트 데이터 (값이 0인 항목 제외)
  const paternityPieData = stats?.paternityStats ? [
    { name: '분석 완료', value: stats.paternityStats.analysisComplete, color: '#1F3A8F' },
    { name: '부 불일치', value: stats.paternityStats.sireMismatch, color: '#ef4444' },
    { name: '모 불일치', value: stats.paternityStats.damMismatch, color: '#f97316' },
    { name: '모 이력제부재', value: stats.paternityStats.damNoRecord, color: '#eab308' },
  ].filter(d => d.value > 0) : []

  /**
   * 변화량 표시 컴포넌트
   * @description 전년 대비 증감을 화살표로 표시
   * @param value - 변화량 (양수: 증가, 음수: 감소)
   * @param suffix - 단위 (%, 두 등)
   */
  const ChangeIndicator = ({ value, suffix = '' }: { value: number, suffix?: string }) => {
    if (value === 0) return null
    const isPositive = value > 0
    return (
      <span className={`text-xs font-medium flex items-center gap-0.5 ${isPositive ? 'text-[#1F3A8F]' : 'text-red-500'}`}>
        {isPositive ? <TrendingUp className="w-3 h-3" /> : <TrendingDown className="w-3 h-3" />}
        {isPositive ? '+' : ''}{value}{suffix}
      </span>
    )
  }

  // ========================================
  // 5. 농가 위치 차트 데이터 계산 (복잡한 로직)
  // ========================================

  /**
   * 보은군 내 농가 위치 차트 데이터
   * @description
   * - 정규분포 히스토그램 생성
   * - 우리농가 vs 보은군 평균 비교
   * - 분포 기준: 전체 선발지수 or 개별 형질
   *
   * @logic
   * 1. 보은군 평균을 기준점(0)으로 설정
   * 2. 우리농가 점수 = 보은군 대비 차이 (±값)
   * 3. 정규분포 곡선 생성 (PDF 기반)
   * 4. X축 범위 자동 계산 (데이터 범위에 맞춤)
   */
  const farmPositionData = useMemo(() => {
    // 데이터 없을 때 기본값
    if (!farmRanking) return {
      histogramData: [],
      xAxisRange: { min: -2.5, max: 2.5 },
      farmScore: 0,
      regionScore: 0,
      originalFarmScore: 0,
      originalRegionScore: 0,
      label: '',
      rank: null as number | null,
      totalFarms: 0,
      percentile: null as number | null
    }

    let farmScore = 0          // 차트용: 보은군 대비 상대값
    let regionScore = 0        // 차트용: 보은군 = 0 (기준점)
    let originalFarmScore = 0  // 툴팁용: 실제 EPD/EBV 값
    let originalRegionScore = 0
    let label = '전체 선발지수'
    let rank: number | null = null
    let totalFarms = farmRanking.totalFarmsInRegion || 0
    let percentile: number | null = null

    if (distributionBasis === 'overall') {
      // ===== 전체 선발지수 모드 =====
      // 35개 형질 평균 EBV (표준화 육종가)
      const rawFarmScore = farmRanking.farmAvgScore ?? 0
      const rawRegionScore = farmRanking.regionAvgScore ?? 0
      farmScore = rawFarmScore - rawRegionScore  // 보은군 대비 차이
      regionScore = 0  // 보은군 = 기준점
      originalFarmScore = rawFarmScore
      originalRegionScore = rawRegionScore
      label = '전체 선발지수'
      rank = farmRanking.farmRankInRegion
      percentile = farmRanking.percentile
    } else {
      // ===== 개별 형질 모드 =====
      const traitData = stats?.traitAverages?.find(t => t.traitName === distributionBasis)
      if (traitData) {
        const farmEpd = traitData.avgEpd ?? 0
        const regionEpd = traitData.regionAvgEpd ?? 0
        let diff = farmEpd - regionEpd  // 보은군 대비 차이

        /**
         * 낮을수록 좋은 형질 처리
         * @example 등지방두께: 낮으면 좋음 → 부호 반전
         * - 농가 EPD < 보은군 EPD → diff는 음수지만 실제로는 더 좋음
         * - 따라서 부호를 반전시켜 양수로 표시
         */
        if (NEGATIVE_TRAITS.includes(distributionBasis)) {
          diff = -diff
        }

        farmScore = diff
        regionScore = 0
        originalFarmScore = farmEpd
        originalRegionScore = regionEpd
        label = distributionBasis
        rank = traitData.rank ?? null
        totalFarms = traitData.totalFarms ?? farmRanking.totalFarmsInRegion ?? 0
        percentile = traitData.percentile ?? null
      }
    }

    /**
     * X축 범위 자동 계산
     * @description
     * - 데이터의 최대값에 맞춰 X축 범위를 동적으로 조정
     * - 범위가 작으면 0.5 단위, 크면 2/10/20 단위로 반올림
     */
    const absMax = Math.max(Math.abs(farmScore), 0.1)
    const rawRange = absMax * 1.5  // 여유 공간 확보 (1.5배)
    let range: number  // X축 범위 (-range ~ +range)
    let step: number   // 구간 간격

    if (rawRange <= 3) {
      // 표준화 육종가 스케일 (전체 선발지수)
      range = Math.max(2.5, Math.ceil(rawRange * 2) / 2)
      step = 0.5
    } else if (rawRange <= 10) {
      range = Math.ceil(rawRange / 2) * 2  // 2 단위로 반올림
      step = range / 5
    } else if (rawRange <= 50) {
      range = Math.ceil(rawRange / 10) * 10  // 10 단위로 반올림
      step = range / 5
    } else {
      range = Math.ceil(rawRange / 20) * 20  // 20 단위로 반올림
      step = range / 5
    }

    /**
     * 정규분포 히스토그램 생성
     * @description
     * - PDF (확률밀도함수)를 사용해 정규분포 곡선 생성
     * - 보은군 평균(0)을 중심으로 대칭 분포
     * - sigma = range/3 (±3σ에 99.7% 포함)
     */
    const numBins = Math.round((range * 2) / step)
    const bins = []

    // 정규분포 PDF 함수
    const normalPDF = (x: number, sigma: number = range / 3) => {
      return Math.exp(-0.5 * Math.pow(x / sigma, 2)) / (sigma * Math.sqrt(2 * Math.PI))
    }

    const total = farmRanking.totalFarmsInRegion || 50
    let totalPercent = 0
    const tempBins = []

    // 각 구간의 비율 계산
    for (let i = 0; i < numBins; i++) {
      const min = -range + i * step
      const max = min + step
      const midPoint = (min + max) / 2
      const percent = normalPDF(midPoint) * step * 100
      totalPercent += percent
      tempBins.push({ min, max, midPoint, percent })
    }

    // 비율 정규화 (총합이 100%가 되도록)
    for (const bin of tempBins) {
      const normalizedPercent = (bin.percent / totalPercent) * 100
      bins.push({
        range: `${bin.min.toFixed(1)}~${bin.max.toFixed(1)}`,
        min: bin.min,
        max: bin.max,
        midPoint: bin.midPoint,
        count: Math.round(total * normalizedPercent / 100),  // 농가 수로 환산
        percent: normalizedPercent
      })
    }

    return {
      histogramData: bins,
      xAxisRange: { min: -range, max: range },
      farmScore,
      regionScore,
      originalFarmScore,
      originalRegionScore,
      label,
      rank,
      totalFarms,
      percentile
    }
  }, [farmRanking, stats, distributionBasis])

  // ========================================
  // 6. 렌더링
  // ========================================

  return (
    <AuthGuard>
      <SidebarProvider>
        <AppSidebar />
        <SidebarInset>
          <SiteHeader />
          <div className="flex flex-1 flex-col gap-6 p-6 bg-gradient-to-br from-blue-50/30 via-white to-amber-50/20 min-h-screen">
            {/* 로딩 상태 */}
            {loading ? (
              <div className="flex items-center justify-center h-96">
                <div className="text-center">
                  <div className="animate-spin rounded-full h-10 w-10 border-2 border-blue-500 border-t-transparent mx-auto" />
                  <p className="mt-4 text-sm text-slate-500">데이터를 불러오는 중...</p>
                </div>
              </div>
            ) : !farmNo ? (
              /* 농장 정보 없음 */
              <div className="flex items-center justify-center h-96">
                <div className="text-center space-y-3 p-8 bg-white rounded-2xl shadow-sm border">
                  <AlertCircle className="w-14 h-14 text-slate-300 mx-auto" />
                  <p className="text-lg font-semibold text-slate-700">농장 정보가 없습니다</p>
                  <p className="text-sm text-slate-500">관리자에게 문의해주세요</p>
                </div>
              </div>
            ) : (
              <>
                {/* ========================================
                    1. 핵심 KPI 카드 영역
                    - 총 검사 개체 수 (유전체/유전자/번식능력)
                    - 친자감별 결과 (도넛 차트)
                    ======================================== */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 max-sm:gap-3">
                  {/* 총 검사 개체 수 (합집합) */}
                  <div
                    className="bg-gradient-to-br from-primary/5 to-primary/10 rounded-xl border border-primary/20 p-5 pb-5 max-sm:p-4 max-sm:pb-4 shadow-sm hover:shadow-lg hover:border-primary/30 transition-all cursor-pointer"
                    onClick={() => router.push('/cow')}
                  >
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-base max-sm:text-sm font-semibold text-primary/70">총 검사 개체 수</p>
                    </div>
                    <p className="text-4xl max-sm:text-3xl font-bold text-primary">
                      {stats?.summary.totalCows || 0}
                      <span className="text-lg max-sm:text-base font-normal text-primary/60 ml-1">두</span>
                    </p>
                    <div className="flex flex-wrap items-center gap-3 max-sm:gap-2 mt-3 pt-3 border-t border-primary/10 text-sm max-sm:text-xs text-primary/60">
                      <span>유전체 <span className="font-bold text-primary">{stats?.summary.genomeCowCount || 0}</span></span>
                      <span className="text-primary/30">·</span>
                      <span>유전자 <span className="font-bold text-primary">{stats?.summary.geneCowCount || 0}</span></span>
                      <span className="text-primary/30">·</span>
                      <span>번식능력 <span className="font-bold text-primary">{stats?.summary.mptCowCount || 0}</span></span>
                    </div>
                  </div>

                  {/* 친자감별 결과 (넓게) */}
                  <div className="md:col-span-2 bg-white rounded-xl border border-slate-200 p-5 max-sm:p-4 shadow-sm hover:shadow-md transition-shadow">
                    <p className="text-base max-sm:text-sm font-semibold text-slate-700 mb-4">유전체 친자감별 결과</p>
                    {(stats?.summary.genomeCowCount || 0) === 0 ? (
                      <div className="flex items-center justify-center h-32 text-slate-400">
                        <div className="text-center">
                          <Dna className="w-8 h-8 mx-auto mb-2 opacity-50" />
                          <p className="text-sm">유전체 검사 데이터가 없습니다</p>
                        </div>
                      </div>
                    ) : (
                    <div className="flex items-center gap-6 max-sm:flex-col max-sm:gap-4">
                      {/* 도넛 차트 */}
                      <div className="w-28 h-28 max-sm:w-24 max-sm:h-24 shrink-0 relative">
                        <ResponsiveContainer width="100%" height="100%">
                          <PieChart>
                            <Pie
                              data={[
                                { name: '분석 완료', value: stats?.paternityStats?.analysisComplete || 0, color: '#1F3A8F' },
                                { name: '부 불일치', value: stats?.paternityStats?.sireMismatch || 0, color: '#ef4444' },
                                { name: '모 불일치', value: stats?.paternityStats?.damMismatch || 0, color: '#f97316' },
                                { name: '모 이력제부재', value: stats?.paternityStats?.damNoRecord || 0, color: '#eab308' },
                              ].filter(d => d.value > 0)}
                              cx="50%"
                              cy="50%"
                              innerRadius={32}
                              outerRadius={48}
                              dataKey="value"
                              stroke="none"
                              paddingAngle={2}
                            >
                              {[
                                { name: '분석 완료', value: stats?.paternityStats?.analysisComplete || 0, color: '#1F3A8F' },
                                { name: '부 불일치', value: stats?.paternityStats?.sireMismatch || 0, color: '#ef4444' },
                                { name: '모 불일치', value: stats?.paternityStats?.damMismatch || 0, color: '#f97316' },
                                { name: '모 이력제부재', value: stats?.paternityStats?.damNoRecord || 0, color: '#eab308' },
                              ].filter(d => d.value > 0).map((entry, index) => (
                                <Cell key={`cell-${index}`} fill={entry.color} />
                              ))}
                            </Pie>
                            <Tooltip
                              formatter={(value: number, name: string) => [`${value}건`, name]}
                              contentStyle={{ borderRadius: '8px', border: '1px solid #e2e8f0', fontSize: '12px' }}
                            />
                          </PieChart>
                        </ResponsiveContainer>
                        {/* 중앙 총합 표시 */}
                        <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
                          <span className="text-xl max-sm:text-lg font-bold text-slate-700">
                            {(stats?.paternityStats?.analysisComplete || 0) +
                              (stats?.paternityStats?.sireMismatch || 0) +
                              (stats?.paternityStats?.damMismatch || 0) +
                              (stats?.paternityStats?.damNoRecord || 0)}
                          </span>
                        </div>
                      </div>
                      {/* 범례 - 가로 배치 */}
                      <div className="flex-1 grid grid-cols-2 gap-x-8 max-sm:gap-x-4 gap-y-3 text-base max-sm:text-sm max-sm:w-full">
                        <div className="flex items-center justify-between">
                          <span className="flex items-center gap-2.5 max-sm:gap-2 text-slate-700">
                            <span className="w-4 h-4 max-sm:w-3 max-sm:h-3 rounded-full bg-[#1F3A8F] shrink-0"></span>
                            <span className="truncate font-medium">분석 완료</span>
                          </span>
                          <span className="font-bold text-lg max-sm:text-base text-[#1F3A8F] ml-2">{stats?.paternityStats?.analysisComplete || 0}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="flex items-center gap-2.5 max-sm:gap-2 text-slate-700">
                            <span className="w-4 h-4 max-sm:w-3 max-sm:h-3 rounded-full bg-red-500 shrink-0"></span>
                            <span className="truncate font-medium">부 불일치</span>
                          </span>
                          <span className="font-bold text-lg max-sm:text-base text-red-500 ml-2">{stats?.paternityStats?.sireMismatch || 0}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="flex items-center gap-2.5 max-sm:gap-2 text-slate-700">
                            <span className="w-4 h-4 max-sm:w-3 max-sm:h-3 rounded-full bg-orange-500 shrink-0"></span>
                            <span className="truncate font-medium">모 불일치</span>
                          </span>
                          <span className="font-bold text-lg max-sm:text-base text-orange-500 ml-2">{stats?.paternityStats?.damMismatch || 0}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="flex items-center gap-2.5 max-sm:gap-2 text-slate-700">
                            <span className="w-4 h-4 max-sm:w-3 max-sm:h-3 rounded-full bg-yellow-500 shrink-0"></span>
                            <span className="truncate font-medium">모 이력제부재</span>
                          </span>
                          <span className="font-bold text-lg max-sm:text-base text-yellow-600 ml-2">{stats?.paternityStats?.damNoRecord || 0}</span>
                        </div>
                      </div>
                    </div>
                    )}
                  </div>
                </div>

                {/* ========================================
                    2. MPT (번식능력검사) 현황
                    - 에너지 균형 / 단백질 상태 / 간 건강 / 미네랄 균형
                    - 안전/주의 구분
                    ======================================== */}
                {mptStats && mptStats.totalMptCows > 0 && (
                  <div className="bg-white rounded-xl border border-slate-200 p-5 max-sm:p-4 shadow-sm hover:shadow-md transition-shadow">
                    <div className="flex items-center justify-between mb-4">
                      <p className="text-base max-sm:text-sm font-semibold text-slate-700">번식능력검사 현황</p>
                      {/* <span className="text-xs max-sm:text-[10px] px-2 py-1 rounded-full bg-pink-50 text-pink-700 font-medium">
                        검사 {mptStats.totalMptCows}두
                      </span> */}
                    </div>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 max-sm:gap-3">
                      {/* 에너지 균형 */}
                      <div className="bg-slate-50 rounded-lg p-4 max-sm:p-3">
                        <p className="text-sm max-sm:text-xs text-slate-500 mb-3 font-medium">에너지 균형</p>
                        <div className="space-y-2">
                          <div className="flex items-center justify-between">
                            <span className="flex items-center gap-1.5 text-sm max-sm:text-xs text-green-600">
                              <CheckCircle2 className="w-4 h-4 max-sm:w-3 max-sm:h-3" /> 안전
                            </span>
                            <span className="text-lg max-sm:text-base font-bold text-green-600">{mptStats.categories.energy.safe}</span>
                          </div>
                          {mptStats.categories.energy.caution > 0 && (
                            <div className="flex items-center justify-between">
                              <span className="flex items-center gap-1.5 text-sm max-sm:text-xs text-amber-600">
                                <AlertCircle className="w-4 h-4 max-sm:w-3 max-sm:h-3" /> 주의
                              </span>
                              <span className="text-lg max-sm:text-base font-bold text-amber-600">{mptStats.categories.energy.caution}</span>
                            </div>
                          )}
                        </div>
                      </div>
                      {/* 단백질 상태 */}
                      <div className="bg-slate-50 rounded-lg p-4 max-sm:p-3">
                        <p className="text-sm max-sm:text-xs text-slate-500 mb-3 font-medium">단백질 상태</p>
                        <div className="space-y-2">
                          <div className="flex items-center justify-between">
                            <span className="flex items-center gap-1.5 text-sm max-sm:text-xs text-green-600">
                              <CheckCircle2 className="w-4 h-4 max-sm:w-3 max-sm:h-3" /> 안전
                            </span>
                            <span className="text-lg max-sm:text-base font-bold text-green-600">{mptStats.categories.protein.safe}</span>
                          </div>
                          {mptStats.categories.protein.caution > 0 && (
                            <div className="flex items-center justify-between">
                              <span className="flex items-center gap-1.5 text-sm max-sm:text-xs text-amber-600">
                                <AlertCircle className="w-4 h-4 max-sm:w-3 max-sm:h-3" /> 주의
                              </span>
                              <span className="text-lg max-sm:text-base font-bold text-amber-600">{mptStats.categories.protein.caution}</span>
                            </div>
                          )}
                        </div>
                      </div>
                      {/* 간 건강 */}
                      <div className="bg-slate-50 rounded-lg p-4 max-sm:p-3">
                        <p className="text-sm max-sm:text-xs text-slate-500 mb-3 font-medium">간 건강</p>
                        <div className="space-y-2">
                          <div className="flex items-center justify-between">
                            <span className="flex items-center gap-1.5 text-sm max-sm:text-xs text-green-600">
                              <CheckCircle2 className="w-4 h-4 max-sm:w-3 max-sm:h-3" /> 안전
                            </span>
                            <span className="text-lg max-sm:text-base font-bold text-green-600">{mptStats.categories.liver.safe}</span>
                          </div>
                          {mptStats.categories.liver.caution > 0 && (
                            <div className="flex items-center justify-between">
                              <span className="flex items-center gap-1.5 text-sm max-sm:text-xs text-amber-600">
                                <AlertCircle className="w-4 h-4 max-sm:w-3 max-sm:h-3" /> 주의
                              </span>
                              <span className="text-lg max-sm:text-base font-bold text-amber-600">{mptStats.categories.liver.caution}</span>
                            </div>
                          )}
                        </div>
                      </div>
                      {/* 미네랄 균형 */}
                      <div className="bg-slate-50 rounded-lg p-4 max-sm:p-3">
                        <p className="text-sm max-sm:text-xs text-slate-500 mb-3 font-medium">미네랄 균형</p>
                        <div className="space-y-2">
                          <div className="flex items-center justify-between">
                            <span className="flex items-center gap-1.5 text-sm max-sm:text-xs text-green-600">
                              <CheckCircle2 className="w-4 h-4 max-sm:w-3 max-sm:h-3" /> 안전
                            </span>
                            <span className="text-lg max-sm:text-base font-bold text-green-600">{mptStats.categories.mineral.safe}</span>
                          </div>
                          {mptStats.categories.mineral.caution > 0 && (
                            <div className="flex items-center justify-between">
                              <span className="flex items-center gap-1.5 text-sm max-sm:text-xs text-amber-600">
                                <AlertCircle className="w-4 h-4 max-sm:w-3 max-sm:h-3" /> 주의
                              </span>
                              <span className="text-lg max-sm:text-base font-bold text-amber-600">{mptStats.categories.mineral.caution}</span>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {/* ========================================
                    3. 메인 차트 영역 (좌우 2열)
                    - 좌: 보은군 내 농가 위치 (정규분포 차트)
                    - 우: 연도별 육종가 추이 (막대 차트)
                    ======================================== */}
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 max-sm:gap-4">
                  {/* === 좌측: 보은군 내 농가 위치 차트 === */}
                  <div className="bg-white rounded-xl border border-slate-200 p-5 max-sm:p-4 shadow-sm flex flex-col">
                    <div className="flex items-center justify-between mb-4 max-sm:flex-col max-sm:items-start max-sm:gap-2">
                      <div className="flex items-center gap-3 max-sm:gap-2">
                        <h3 className="font-semibold text-slate-900 text-lg max-sm:text-sm">보은군 내 농가 위치</h3>
                        <Select value={distributionBasis} onValueChange={setDistributionBasis}>
                          <SelectTrigger className="w-[160px] max-sm:w-[140px] h-9 max-sm:h-8 text-sm max-sm:text-xs font-medium">
                            <SelectValue placeholder="전체 선발지수" />
                          </SelectTrigger>
                          <SelectContent>
                            {filters.isActive && (
                              <SelectItem value="overall" className="text-sm font-medium">전체 선발지수</SelectItem>
                            )}
                            {Object.entries(TRAIT_CATEGORIES).map(([category, traits]) => (
                              <div key={category}>
                                <div className="px-2 py-1.5 text-sm font-semibold text-slate-500 bg-slate-50">{category}</div>
                                {traits.map(trait => (
                                  <SelectItem key={trait} value={trait} className="pl-4 text-sm">
                                    {trait}
                                  </SelectItem>
                                ))}
                              </div>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="flex items-center gap-4 text-base max-sm:text-xs max-sm:gap-2">
                        <span className="flex items-center gap-1.5 max-sm:gap-1 font-medium"><span className="w-3.5 h-3.5 max-sm:w-2.5 max-sm:h-2.5 rounded bg-[#1F3A8F]"></span> 우리농가</span>
                        <span className="flex items-center gap-1.5 max-sm:gap-1 font-medium"><span className="w-3.5 h-3.5 max-sm:w-2.5 max-sm:h-2.5 rounded bg-slate-400"></span> 보은군</span>
                      </div>
                    </div>
                    {(stats?.summary.genomeCowCount || 0) > 0 && farmRanking && (farmRanking.farmAvgScore !== null || distributionBasis !== 'overall') ? (
                      <div className="bg-gradient-to-b from-slate-50 to-slate-100/50 rounded-xl p-4 max-sm:p-2 max-sm:-mx-2">
                        <ResponsiveContainer width="100%" height={350}>
                          <ComposedChart
                            data={farmPositionData.histogramData}
                            margin={{ top: 70, right: 20, left: 10, bottom: 30 }}
                          >
                            <defs>
                              <linearGradient id="dashboardAreaGradient" x1="0" y1="0" x2="0" y2="1">
                                <stop offset="0%" stopColor="#3b82f6" stopOpacity={0.5} />
                                <stop offset="50%" stopColor="#60a5fa" stopOpacity={0.3} />
                                <stop offset="100%" stopColor="#93c5fd" stopOpacity={0.1} />
                              </linearGradient>
                              {/* 녹색 화살표 - 좋을 때: 오른쪽 방향 */}
                              <marker id="dashArrowGreenRight" markerWidth="10" markerHeight="10" refX="0" refY="3" orient="auto">
                                <path d="M0,0 L0,6 L9,3 z" fill="#16a34a" />
                              </marker>
                              {/* 빨간색 화살표 - 나쁠 때: 왼쪽 방향 */}
                              <marker id="dashArrowRedLeft" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
                                <path d="M9,0 L9,6 L0,3 z" fill="#dc2626" />
                              </marker>
                            </defs>
                            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false} />
                            <XAxis
                              dataKey="midPoint"
                              type="number"
                              domain={[farmPositionData.xAxisRange.min, farmPositionData.xAxisRange.max]}
                              ticks={(() => {
                                const ticks: number[] = []
                                for (let t = farmPositionData.xAxisRange.min; t <= farmPositionData.xAxisRange.max; t += 1) {
                                  ticks.push(Math.round(t * 10) / 10)
                                }
                                return ticks
                              })()}
                              tick={{ fontSize: 12, fill: '#64748b', fontWeight: 500 }}
                              tickFormatter={(value) => value === 0 ? '평균' : value > 0 ? `+${value}` : `${value}`}
                              axisLine={{ stroke: '#cbd5e1', strokeWidth: 2 }}
                              tickLine={false}
                            />
                            <YAxis
                              tick={{ fontSize: 10, fill: '#64748b' }}
                              tickFormatter={(value) => `${value}%`}
                              axisLine={false}
                              tickLine={false}
                              width={32}
                            />
                            <Area
                              type="natural"
                              dataKey="percent"
                              stroke="#3b82f6"
                              strokeWidth={3}
                              fill="url(#dashboardAreaGradient)"
                              dot={false}
                            />
                            {/* 보은군 평균 */}
                            <ReferenceLine x={farmPositionData.regionScore} stroke="#64748b" strokeWidth={2} strokeDasharray="6 4" />
                            {/* 우리 농가 위치 */}
                            <ReferenceLine x={farmPositionData.farmScore} stroke="#1F3A8F" strokeWidth={4} />
                            {/* 커스텀 라벨 */}
                            <Customized
                              component={(props: any) => {
                                const { xAxisMap, yAxisMap } = 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 chartX = xAxis.x
                                const chartWidth = xAxis.width
                                const chartTop = yAxis.y
                                const chartBottom = yAxis.y + yAxis.height
                                const [domainMin, domainMax] = xAxis.domain || [-2.5, 2.5]
                                const domainRange = domainMax - domainMin

                                const sigmaToX = (sigma: number) => {
                                  const ratio = (sigma - domainMin) / domainRange
                                  return chartX + ratio * chartWidth
                                }

                                const farmScore = farmPositionData.farmScore
                                const regionScore = farmPositionData.regionScore
                                const originalFarmScore = farmPositionData.originalFarmScore
                                const originalRegionScore = farmPositionData.originalRegionScore
                                const farmX = sigmaToX(farmScore)
                                const regionX = sigmaToX(regionScore)
                                const diff = farmScore - regionScore

                                // 배지 크기
                                const badgeWidth = 110
                                const badgeHeight = 36

                                // 클램핑
                                const clampedFarmX = Math.min(Math.max(farmX, chartX + badgeWidth / 2 + 5), chartX + chartWidth - badgeWidth / 2 - 5)

                                return (
                                  <g>
                                    {/* 좋음/나쁨 표시 - 더 크게 */}
                                    <text x={chartX + chartWidth - 10} y={chartTop - 45} textAnchor="end" fill="#16a34a" fontSize={14} fontWeight={700}>
                                      좋음 →
                                    </text>
                                    <text x={chartX + 10} y={chartTop - 45} textAnchor="start" fill="#dc2626" fontSize={14} fontWeight={700}>
                                      ← 나쁨
                                    </text>

                                    {/* 우리 농가 배지 - 더 크게 */}
                                    <rect
                                      x={clampedFarmX - badgeWidth / 2}
                                      y={chartTop - 32}
                                      width={badgeWidth}
                                      height={badgeHeight}
                                      rx={8}
                                      fill="#1F3A8F"
                                      filter="drop-shadow(0 4px 6px rgba(31, 58, 143, 0.3))"
                                    />
                                    <text x={clampedFarmX} y={chartTop - 18} textAnchor="middle" fill="white" fontSize={11} fontWeight={500}>
                                      우리농가평균
                                    </text>
                                    <text x={clampedFarmX} y={chartTop - 2} textAnchor="middle" fill="white" fontSize={16} fontWeight={800}>
                                      {originalFarmScore >= 0 ? '+' : ''}{originalFarmScore.toFixed(2)}
                                    </text>
                                    {/* 배지에서 라인으로 연결 */}
                                    <line x1={clampedFarmX} y1={chartTop + 4} x2={farmX} y2={chartTop + 20} stroke="#1F3A8F" strokeWidth={2} />

                                    {/* 보은군 평균 라벨 */}
                                    <rect x={regionX - 50} y={chartBottom - 50} width={100} height={28} rx={6} fill="#64748b" />
                                    <text x={regionX} y={chartBottom - 32} textAnchor="middle" fill="white" fontSize={13} fontWeight={700}>
                                      보은군평균 {originalRegionScore >= 0 ? '+' : ''}{originalRegionScore.toFixed(2)}
                                    </text>

                                    {/* 차이 화살표 또는 동일 표시 */}
                                    {Math.abs(diff) >= 0.01 ? (
                                      <g>
                                        {(() => {
                                          const arrowY = chartTop + 60
                                          const color = diff >= 0 ? '#16a34a' : '#dc2626'
                                          const isMobileView = chartWidth < 300

                                          // 화살표 머리 크기 (모바일/데스크탑)
                                          const arrowBaseOffset = isMobileView ? 10 : 16
                                          const arrowTipOffset = isMobileView ? 10 : 16
                                          const arrowHeight = isMobileView ? 8 : 12

                                          // 막대선 최소 길이 (모바일에서도 꼬리가 보이도록)
                                          const minLineLength = isMobileView ? 25 : 30
                                          const actualLineLength = Math.abs(farmX - regionX)
                                          const lineStartX = diff >= 0
                                            ? (actualLineLength < minLineLength ? farmX - minLineLength : regionX + 5)
                                            : (actualLineLength < minLineLength ? farmX + minLineLength : regionX - 5)

                                          // 화살표 머리 시작점 (막대기 끝점)
                                          const arrowHeadStart = diff >= 0
                                            ? farmX - arrowBaseOffset - arrowTipOffset
                                            : farmX + arrowBaseOffset + arrowTipOffset

                                          return (
                                            <g>
                                              {/* 막대선: 화살표 머리 시작점까지만 */}
                                              <line
                                                x1={lineStartX}
                                                y1={arrowY}
                                                x2={arrowHeadStart}
                                                y2={arrowY}
                                                stroke={color}
                                                strokeWidth={isMobileView ? 3 : 4}
                                              />
                                              {/* 화살표 머리 (농가선에 딱 맞게) */}
                                              <polygon
                                                points={diff >= 0
                                                  ? `${arrowHeadStart},${arrowY - arrowHeight} ${arrowHeadStart},${arrowY + arrowHeight} ${farmX},${arrowY}`
                                                  : `${arrowHeadStart},${arrowY - arrowHeight} ${arrowHeadStart},${arrowY + arrowHeight} ${farmX},${arrowY}`
                                                }
                                                fill={color}
                                              />
                                            </g>
                                          )
                                        })()}
                                        {/* 차이값 배지 */}
                                        <rect
                                          x={(farmX + regionX) / 2 - 40}
                                          y={chartTop + 72}
                                          width={80}
                                          height={30}
                                          rx={6}
                                          fill={diff >= 0 ? '#16a34a' : '#dc2626'}
                                          filter="drop-shadow(0 2px 4px rgba(0,0,0,0.2))"
                                        />
                                        <text
                                          x={(farmX + regionX) / 2}
                                          y={chartTop + 93}
                                          textAnchor="middle"
                                          fill="white"
                                          fontSize={15}
                                          fontWeight={800}
                                        >
                                          {diff >= 0 ? '+' : ''}{diff.toFixed(2)}
                                        </text>
                                      </g>
                                    ) : (
                                      <g>
                                        {/* 동일 표시 (diff가 0에 가까울 때) */}
                                        <rect
                                          x={farmX - 35}
                                          y={chartTop + 50}
                                          width={70}
                                          height={28}
                                          rx={6}
                                          fill="#64748b"
                                          filter="drop-shadow(0 2px 4px rgba(0,0,0,0.2))"
                                        />
                                        <text
                                          x={farmX}
                                          y={chartTop + 70}
                                          textAnchor="middle"
                                          fill="white"
                                          fontSize={14}
                                          fontWeight={700}
                                        >
                                          = 동일
                                        </text>
                                      </g>
                                    )}
                                  </g>
                                )
                              }}
                            />
                          </ComposedChart>
                        </ResponsiveContainer>
                      </div>
                    ) : (
                      <div className="h-[280px] flex items-center justify-center text-slate-400 text-sm bg-slate-50 rounded-xl">
                        <div className="text-center">
                          <Dna className="w-10 h-10 mx-auto mb-3 opacity-50" />
                          <p className="text-base">유전체 검사 데이터가 없습니다</p>
                        </div>
                      </div>
                    )}

                    {/* 순위 정보 (차트 하단에 통합) - 드롭다운 선택에 따라 연동 */}
                    {(stats?.summary.genomeCowCount || 0) > 0 && (farmPositionData.rank !== null || farmRanking?.farmAvgScore !== null) && (
                      <div className="mt-4 pt-4 border-t border-slate-200">
                        {/* 현재 선택된 기준 표시 */}
                        <p className="text-xs text-slate-400 mb-2 text-center">
                          {farmPositionData.label} 기준
                        </p>
                        {/* 모바일/웹 모두 3열 */}
                        <div className="grid grid-cols-3 gap-3 max-sm:gap-1.5">
                          {/* 순위 카드 */}
                          <div className="rounded-xl p-4 max-sm:p-3 border border-amber-200 text-center bg-amber-50/30">
                            <p className="text-sm max-sm:text-xs text-amber-700 font-medium mb-2">순위</p>
                            <p className="text-2xl max-sm:text-lg font-extrabold text-amber-600">
                              {farmPositionData.rank ?? '-'}<span className="text-base max-sm:text-sm font-bold text-amber-500">위</span>
                            </p>
                            <p className="text-xs text-amber-600 font-medium mt-1">/{farmPositionData.totalFarms}개 농가</p>
                          </div>
                          {/* 백분율 카드 */}
                          <div className="rounded-xl p-4 max-sm:p-3 border border-blue-200 text-center bg-blue-50/30">
                            <p className="text-sm max-sm:text-xs text-blue-700 font-medium mb-2">상위</p>
                            <p className="text-2xl max-sm:text-lg font-extrabold text-blue-600">
                              {farmPositionData.percentile ?? '-'}<span className="text-base max-sm:text-sm font-bold text-blue-500">%</span>
                            </p>
                            <p className="text-xs text-blue-500 font-medium mt-1">보은군 내</p>
                          </div>
                          {/* 점수 비교 카드 */}
                          <div className={`rounded-xl p-4 max-sm:p-3 border text-center ${farmPositionData.farmScore >= 0
                            ? 'border-emerald-200 bg-emerald-50/30'
                            : 'border-red-200 bg-red-50/30'
                            }`}>
                            <p className="text-sm max-sm:text-xs text-slate-600 font-medium mb-2">평균대비</p>
                            <p className={`text-2xl max-sm:text-lg font-extrabold ${farmPositionData.farmScore >= 0 ? 'text-emerald-600' : 'text-red-500'}`}>
                              {farmPositionData.farmScore > 0 ? '+' : ''}{farmPositionData.farmScore.toFixed(2)}
                            </p>
                            <p className={`text-xs flex items-center justify-center gap-1 font-medium mt-1 ${farmPositionData.farmScore >= 0 ? 'text-emerald-500' : 'text-red-400'}`}>
                              {farmPositionData.farmScore >= 0 ? (
                                <><TrendingUp className="w-4 h-4 max-sm:w-3 max-sm:h-3" />높음</>
                              ) : (
                                <><TrendingDown className="w-4 h-4 max-sm:w-3 max-sm:h-3" />낮음</>
                              )}
                            </p>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>

                  {/* === 우측: 연도별 육종가 추이 차트 === */}
                  <div className="bg-white rounded-xl border border-slate-200 p-5 max-sm:p-4 shadow-sm flex flex-col">
                    <div className="flex items-center justify-between mb-4 max-sm:flex-col max-sm:items-start max-sm:gap-2">
                      <h3 className="font-semibold text-slate-900 text-lg max-sm:text-base">연도별 육종가 추이</h3>
                      <div className="flex items-center gap-4 text-base max-sm:text-sm max-sm:gap-2">
                        <span className="flex items-center gap-1.5 max-sm:gap-1 font-medium"><span className="w-3.5 h-3.5 max-sm:w-2.5 max-sm:h-2.5 rounded bg-[#1F3A8F]"></span> 우리농가</span>
                        <span className="flex items-center gap-1.5 max-sm:gap-1 font-medium"><span className="w-3.5 h-3.5 max-sm:w-2.5 max-sm:h-2.5 rounded bg-slate-400"></span> 보은군</span>
                      </div>
                    </div>
                    {/* 형질 선택 드롭다운 (카테고리별 그룹화) */}
                    <div className="mb-4">
                      <Select value={selectedTrait} onValueChange={setSelectedTrait}>
                        <SelectTrigger className="w-full h-14 text-sm font-medium">
                          <SelectValue placeholder="형질 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {Object.entries(TRAIT_CATEGORIES).map(([category, traits]) => (
                            <div key={category}>
                              <div className="px-2 py-1.5 text-sm font-semibold text-slate-500 bg-slate-50">{category}</div>
                              {traits.map(trait => (
                                <SelectItem key={trait} value={trait} className="pl-4 text-sm">
                                  {trait}
                                </SelectItem>
                              ))}
                            </div>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    {/* 차트 */}
                    {(stats?.summary.genomeCowCount || 0) === 0 ? (
                      <div className="h-[280px] flex items-center justify-center text-slate-400 bg-slate-50 rounded-xl">
                        <div className="text-center">
                          <Dna className="w-10 h-10 mx-auto mb-3 opacity-50" />
                          <p className="text-base">유전체 검사 데이터가 없습니다</p>
                        </div>
                      </div>
                    ) : traitTrendLoading ? (
                      <div className="h-[180px] flex items-center justify-center text-slate-400">
                        <div className="animate-spin rounded-full h-6 w-6 border-2 border-[#1F3A8F] border-t-transparent"></div>
                      </div>
                    ) : (
                      (() => {
                        // 먼저 실제 데이터만으로 chartData 구성
                        const rawChartData = last3Years.map(year => {
                          const yearData = traitTrendData?.yearlyData.find(d => d.year === year)
                          const hasData = yearData && (yearData.farmCount > 0 || yearData.regionCount > 0)
                          return {
                            year: `${year}`,
                            농가: hasData ? yearData.farmAvgEbv : 0,
                            보은군: hasData ? yearData.regionAvgEbv : 0,
                            hasData,
                          }
                        })
                        // 실제 데이터의 최대 절대값을 기준으로 최소 막대 높이 계산 (약 0.5% - 아주 살짝만)
                        const validValues = rawChartData.filter(d => d.hasData).flatMap(d => [d.농가, d.보은군])
                        const maxAbsValue = validValues.length > 0 ? Math.max(...validValues.map(Math.abs), 0.5) : 1
                        const minBarValue = maxAbsValue * 0.005
                        // 데이터 없는 항목에 최소값 적용
                        const chartData = rawChartData.map(d => ({
                          ...d,
                          농가: d.hasData ? d.농가 : minBarValue,
                          보은군: d.hasData ? d.보은군 : minBarValue,
                        }))
                        // 모바일/웹 차트 설정
                        const labelFontSize = isMobile ? 12 : 16
                        const barMaxSize = isMobile ? 50 : 70   // 막대 너비 설정
                        const chartHeight = isMobile ? 300 : 350 // 막대 높이 설정
                        const chartMarginBottom = isMobile ? 40 : 70
                        return (
                          <ResponsiveContainer width="100%" height={chartHeight}>
                            <BarChart data={chartData} margin={{ top: 40, right: 10, left: 0, bottom: chartMarginBottom }} barGap={8} style={{ overflow: 'visible' }}>
                              <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false} />
                              <XAxis
                                dataKey="year"
                                tick={{ fontSize: 16, fill: '#1e293b', fontWeight: 700, dy: 15 }}
                                axisLine={{ stroke: '#cbd5e1', strokeWidth: 1 }}
                                tickLine={false}
                              />
                              <YAxis
                                tick={{ fontSize: 11, fill: '#64748b', fontWeight: 500, dx: 5 }}
                                axisLine={false}
                                tickLine={false}
                                domain={['auto', 'auto']}
                                width={35}
                              />
                              <ReferenceLine y={0} stroke="#64748b" strokeWidth={1.5} strokeDasharray="4 4" />
                              <Tooltip
                                formatter={(value: number, name: string, props: any) => {
                                  if (!props.payload.hasData) return ['데이터 없음', name]
                                  return [`${value > 0 ? '+' : ''}${value.toFixed(2)}`, name]
                                }}
                                contentStyle={{ borderRadius: '10px', border: '1px solid #e2e8f0', fontSize: '14px', fontWeight: 600 }}
                              />
                              <Bar
                                dataKey="농가"
                                radius={[6, 6, 0, 0]}
                                maxBarSize={barMaxSize}
                                label={({ x, y, width, height, index }: any) => {
                                  const item = chartData[index]
                                  if (!item.hasData) return <text x={x + width / 2} y={y - 14} textAnchor="middle" fontSize={labelFontSize} fontWeight={700} fill="#94a3b8">-</text>
                                  const v = item.농가
                                  // 양수: 막대 위에, 음수: 막대 바로 아래
                                  const labelY = height < 0 ? y + 20 : y - 14
                                  return <text x={x + width / 2} y={labelY} textAnchor="middle" fontSize={labelFontSize} fontWeight={800} fill="#1F3A8F">{(v > 0 ? '+' : '') + v.toFixed(2)}</text>
                                }}
                              >
                                {chartData.map((entry, index) => (
                                  <Cell key={`farm-${index}`} fill={entry.hasData ? '#1F3A8F' : '#E2E8F0'} />
                                ))}
                              </Bar>
                              <Bar
                                dataKey="보은군"
                                radius={[6, 6, 0, 0]}
                                maxBarSize={barMaxSize}
                                label={({ x, y, width, height, index }: any) => {
                                  const item = chartData[index]
                                  if (!item.hasData) return <text x={x + width / 2} y={y - 14} textAnchor="middle" fontSize={labelFontSize} fontWeight={700} fill="#94a3b8">-</text>
                                  const v = item.보은군
                                  // 양수: 막대 위에, 음수: 막대 바로 아래
                                  const labelY = height < 0 ? y + 20 : y - 14
                                  return <text x={x + width / 2} y={labelY} textAnchor="middle" fontSize={labelFontSize} fontWeight={800} fill="#475569">{(v > 0 ? '+' : '') + v.toFixed(2)}</text>
                                }}
                              >
                                {chartData.map((entry, index) => (
                                  <Cell key={`region-${index}`} fill={entry.hasData ? '#94a3b8' : '#F1F5F9'} />
                                ))}
                              </Bar>
                            </BarChart>
                          </ResponsiveContainer>
                        )
                      })()
                    )}
                    {/* 농가 순위 정보 */}
                    <div className="mt-3 pt-3 border-t border-slate-100 flex flex-col sm:flex-row items-center sm:justify-between gap-1 text-base max-sm:text-sm text-center sm:text-left">
                      <span className="text-slate-500"><span className="font-medium text-slate-700">{selectedTrait}</span> 보은군 내 순위</span>
                      {traitTrendData?.farmRank?.rank !== null && traitTrendData?.farmRank?.rank !== undefined ? (
                        <span className="font-bold text-[#1F3A8F]">
                          상위 {traitTrendData.farmRank.percentile}%
                          <span className="text-slate-400 font-normal ml-1">
                            ({traitTrendData.farmRank.rank}위/{traitTrendData.farmRank.totalFarms}개 농가)
                          </span>
                        </span>
                      ) : (
                        <span className="text-slate-400">데이터 없음</span>
                      )}
                    </div>
                    {/* 전년대비 / 보은군대비 / 3년추세 카드 */}
                    {(() => {
                      const thisYearData = traitTrendData?.yearlyData.find(d => d.year === currentYear)
                      const lastYearData = traitTrendData?.yearlyData.find(d => d.year === lastYear)
                      const threeYearsAgoData = traitTrendData?.yearlyData.find(d => d.year === currentYear - 2)

                      // 전년대비 변화 (농가)
                      const yearOverYear = thisYearData && lastYearData && thisYearData.farmCount > 0 && lastYearData.farmCount > 0
                        ? thisYearData.farmAvgEbv - lastYearData.farmAvgEbv
                        : null

                      // 보은군 대비 (올해 기준)
                      const vsRegion = thisYearData && thisYearData.farmCount > 0
                        ? thisYearData.farmAvgEbv - thisYearData.regionAvgEbv
                        : null

                      // 3년 추세 계산
                      let trend: '상승' | '유지' | '하락' | null = null
                      if (threeYearsAgoData && thisYearData && threeYearsAgoData.farmCount > 0 && thisYearData.farmCount > 0) {
                        const diff = thisYearData.farmAvgEbv - threeYearsAgoData.farmAvgEbv
                        if (diff > 0.1) trend = '상승'
                        else if (diff < -0.1) trend = '하락'
                        else trend = '유지'
                      }

                      return (
                        <div className="mt-4 grid grid-cols-3 gap-3 max-sm:gap-1.5">
                          {/* 전년대비 */}
                          <div className={`rounded-xl p-4 max-sm:p-3 text-center border ${yearOverYear !== null ? (yearOverYear >= 0 ? 'border-blue-200 bg-blue-50/30' : 'border-red-200 bg-red-50/30') : 'border-slate-200 bg-slate-50/30'}`}>
                            <p className="text-sm max-sm:text-xs text-slate-500 font-medium mb-2">전년대비</p>
                            {yearOverYear !== null ? (
                              <p className={`text-2xl max-sm:text-lg font-extrabold flex items-center justify-center gap-1 ${yearOverYear >= 0 ? 'text-[#1F3A8F]' : 'text-red-500'}`}>
                                {yearOverYear >= 0 ? '+' : ''}{yearOverYear.toFixed(2)}
                                {yearOverYear >= 0 ? <TrendingUp className="w-5 h-5 max-sm:w-4 max-sm:h-4" /> : <TrendingDown className="w-5 h-5 max-sm:w-4 max-sm:h-4" />}
                              </p>
                            ) : (
                              <p className="text-2xl max-sm:text-lg font-extrabold text-slate-400">-</p>
                            )}
                          </div>
                          {/* 보은군대비 */}
                          <div className={`rounded-xl p-4 max-sm:p-3 text-center border ${vsRegion !== null ? (vsRegion >= 0 ? 'border-emerald-200 bg-emerald-50/30' : 'border-amber-200 bg-amber-50/30') : 'border-slate-200 bg-slate-50/30'}`}>
                            <p className="text-sm max-sm:text-xs text-slate-500 font-medium mb-2">보은군대비</p>
                            {vsRegion !== null ? (
                              <p className={`text-2xl max-sm:text-lg font-extrabold ${vsRegion >= 0 ? 'text-emerald-600' : 'text-amber-600'}`}>
                                {vsRegion >= 0 ? '+' : ''}{vsRegion.toFixed(2)}
                              </p>
                            ) : (
                              <p className="text-2xl max-sm:text-lg font-extrabold text-slate-400">-</p>
                            )}
                          </div>
                          {/* 3년 추세 */}
                          <div className={`rounded-xl p-4 max-sm:p-3 text-center border ${trend === '상승' ? 'border-blue-200 bg-blue-50/30' : trend === '하락' ? 'border-red-200 bg-red-50/30' : 'border-slate-200 bg-slate-50/30'}`}>
                            <p className="text-sm max-sm:text-xs text-slate-500 font-medium mb-2">3년 추세</p>
                            {trend !== null ? (
                              <p className={`text-2xl max-sm:text-lg font-extrabold flex items-center justify-center gap-1 ${trend === '상승' ? 'text-[#1F3A8F]' : trend === '하락' ? 'text-red-500' : 'text-slate-500'}`}>
                                {trend}
                                {trend === '상승' && <TrendingUp className="w-5 h-5 max-sm:w-4 max-sm:h-4" />}
                                {trend === '하락' && <TrendingDown className="w-5 h-5 max-sm:w-4 max-sm:h-4" />}
                              </p>
                            ) : (
                              <p className="text-2xl max-sm:text-lg font-extrabold text-slate-400">-</p>
                            )}
                          </div>
                        </div>
                      )
                    })()}
                  </div>
                </div>

                {/* ========================================
                    4. 카테고리별 보은군 대비 비교
                    - 레이더 차트 (좌측): 5개 카테고리 시각화
                    - 바 차트 (우측): 카테고리별 상세 육종가
                    ======================================== */}
                <div className="bg-white rounded-xl border border-slate-200 p-5 max-sm:p-4 shadow-sm">
                  <h3 className="font-semibold text-slate-900 text-lg max-sm:text-base mb-4 max-sm:mb-3">보은군 대비 카테고리별 육종가 평균</h3>
                  {(stats?.summary.genomeCowCount || 0) > 0 && stats?.traitAverages && stats.traitAverages.length > 0 ? (
                    (() => {
                      // 5개 카테고리 분류 (성장/생산/체형/무게/비율)
                      const categories = ['성장', '생산', '체형', '무게', '비율']

                      /**
                       * 카테고리별 평균 계산
                       * @description
                       * - 각 카테고리에 속한 형질들의 EPD 평균
                       * - 백분위(percentile)도 평균 계산
                       */
                      const categoryData = categories.map(cat => {
                        const traits = stats.traitAverages.filter(t => t.category === cat)
                        const avgEpd = traits.length > 0
                          ? traits.reduce((sum, t) => sum + (t.avgEpd ?? 0), 0) / traits.length
                          : 0
                        const avgPercentile = traits.length > 0
                          ? traits.reduce((sum, t) => sum + (t.percentile ?? 50), 0) / traits.length
                          : 50
                        return {
                          category: cat,
                          avgEpd: Math.round(avgEpd * 100) / 100,
                          avgPercentile: Math.round(avgPercentile),
                          traitCount: traits.length
                        }
                      })

                      // 바 차트 최대 길이 계산용
                      const maxAbs = Math.max(...categoryData.map(d => Math.abs(d.avgEpd)), 1)

                      /**
                       * 레이더 차트 좌표 계산
                       * @description
                       * - 중심점: (140, 150)
                       * - 반지름: 95px
                       * - 5개 카테고리를 정오각형으로 배치
                       */
                      const centerX = 140
                      const centerY = 150
                      const maxRadius = 95
                      const angleStep = (2 * Math.PI) / categories.length  // 72도씩
                      const startAngle = -Math.PI / 2  // 12시 방향부터 시작

                      /**
                       * 농가 데이터 다각형 좌표 계산
                       * @description
                       * - 보은군 평균(0) = 반지름 50%
                       * - ±epdScale = 반지름 0%/100%
                       * - EPD 값을 반지름으로 변환
                       */
                      const epdScale = Math.max(...categoryData.map(d => Math.abs(d.avgEpd)), 10)
                      const farmPoints = categoryData.map((d, i) => {
                        const angle = startAngle + i * angleStep
                        // 보은군 평균(0)을 50%로, ±epdScale를 0%/100%로 매핑
                        const normalizedValue = Math.min(100, Math.max(0, (d.avgEpd / epdScale + 1) / 2 * 100))
                        const radius = (normalizedValue / 100) * maxRadius
                        return { x: centerX + radius * Math.cos(angle), y: centerY + radius * Math.sin(angle) }
                      })

                      /**
                       * 보은군 평균 다각형 (기준선)
                       * @description
                       * - 항상 50% 위치 (EBV = 0)
                       * - 점선으로 표시
                       */
                      const regionPoints = categories.map((_, i) => {
                        const angle = startAngle + i * angleStep
                        const radius = 0.5 * maxRadius  // 50% 고정
                        return { x: centerX + radius * Math.cos(angle), y: centerY + radius * Math.sin(angle) }
                      })

                      const farmPolygon = farmPoints.map(p => `${p.x},${p.y}`).join(' ')
                      const regionPolygon = regionPoints.map(p => `${p.x},${p.y}`).join(' ')

                      /**
                       * 레이더 차트 SVG 컴포넌트
                       * @description
                       * - 호버/클릭으로 카테고리별 상세 정보 표시
                       * - 모바일에서는 터치로 토글
                       * - 툴팁은 차트 중앙에 고정 표시
                       */
                      const RadarChart = () => {
                        const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)
                        const [clickedIndex, setClickedIndex] = useState<number | null>(null)

                        // 실제 표시할 인덱스 (클릭 우선, 없으면 호버)
                        const activeIndex = clickedIndex !== null ? clickedIndex : hoveredIndex

                        // 클릭/터치 핸들러: 토글 방식 (같은 거 다시 누르면 닫힘)
                        const handleClick = (e: React.MouseEvent | React.TouchEvent, index: number) => {
                          e.preventDefault()
                          e.stopPropagation()
                          setClickedIndex(prev => prev === index ? null : index)
                        }

                        // 호버 핸들러: 클릭 상태가 아닐 때만 동작
                        const handleMouseEnter = (index: number) => {
                          if (clickedIndex === null) {
                            setHoveredIndex(index)
                          }
                        }

                        const handleMouseLeave = () => {
                          if (clickedIndex === null) {
                            setHoveredIndex(null)
                          }
                        }

                        return (
                          <svg width="280" height="280" className="overflow-visible">
                            {/* 그리드 라인 */}
                            {[0.25, 0.5, 0.75, 1].map((level, idx) => (
                              <polygon
                                key={idx}
                                points={categories.map((_, i) => {
                                  const angle = startAngle + i * angleStep
                                  const r = level * maxRadius
                                  return `${centerX + r * Math.cos(angle)},${centerY + r * Math.sin(angle)}`
                                }).join(' ')}
                                fill="none"
                                stroke={level === 0.5 ? '#94a3b8' : '#e2e8f0'}
                                strokeWidth={level === 0.5 ? 2 : 1}
                                strokeDasharray={level === 0.5 ? '4 2' : undefined}
                              />
                            ))}
                            {/* 축 라인 */}
                            {categories.map((_, i) => {
                              const angle = startAngle + i * angleStep
                              return (
                                <line key={i} x1={centerX} y1={centerY}
                                  x2={centerX + maxRadius * Math.cos(angle)}
                                  y2={centerY + maxRadius * Math.sin(angle)}
                                  stroke="#e2e8f0" strokeWidth={1}
                                />
                              )
                            })}
                            {/* 보은군 평균 다각형 */}
                            <polygon points={regionPolygon} fill="rgba(148, 163, 184, 0.35)" stroke="#64748b" strokeWidth={2.5} />
                            {/* 농가 데이터 다각형 */}
                            <polygon points={farmPolygon} fill="rgba(31, 58, 143, 0.3)" stroke="#1F3A8F" strokeWidth={3} />
                            {/* 농가 데이터 포인트 */}
                            {farmPoints.map((p, i) => (
                              <g key={i} className="cursor-pointer"
                                onMouseEnter={() => handleMouseEnter(i)}
                                onMouseLeave={handleMouseLeave}
                                onClick={(e) => handleClick(e, i)}
                                onTouchEnd={(e) => handleClick(e, i)}
                              >
                                <circle cx={p.x} cy={p.y} r={4}
                                  fill={categoryData[i].avgEpd >= 0 ? '#1F3A8F' : '#ef4444'}
                                  stroke="white" strokeWidth={1.5}
                                />
                                {/* 호버/터치 영역 확대 */}
                                <circle cx={p.x} cy={p.y} r={20} fill="transparent" />
                              </g>
                            ))}
                            {/* 카테고리 라벨 (클릭/호버 가능) - 배지 스타일 */}
                            {categories.map((cat, i) => {
                              const angle = startAngle + i * angleStep
                              const labelRadius = maxRadius + 22
                              const labelX = centerX + labelRadius * Math.cos(angle)
                              const labelY = centerY + labelRadius * Math.sin(angle)
                              const isActive = activeIndex === i
                              const textWidth = cat.length * 14 + 20
                              const textHeight = 28
                              return (
                                <g key={cat}
                                  className="cursor-pointer"
                                  onMouseEnter={() => handleMouseEnter(i)}
                                  onMouseLeave={handleMouseLeave}
                                  onClick={(e) => handleClick(e, i)}
                                  onTouchEnd={(e) => handleClick(e, i)}
                                >
                                  {/* 선택 시 배지 배경 */}
                                  {isActive && (
                                    <rect
                                      x={labelX - textWidth / 2}
                                      y={labelY - textHeight / 2}
                                      width={textWidth}
                                      height={textHeight}
                                      rx={6}
                                      fill="#1F3A8F"
                                    />
                                  )}
                                  {/* 호버/터치 영역 확대 */}
                                  <rect
                                    x={labelX - 30}
                                    y={labelY - 16}
                                    width={60}
                                    height={32}
                                    fill="transparent"
                                  />
                                  <text
                                    x={labelX}
                                    y={labelY}
                                    textAnchor="middle" dominantBaseline="middle"
                                    fontSize={14}
                                    fontWeight={isActive ? 700 : 600}
                                    fill={isActive ? '#ffffff' : '#475569'}
                                  >
                                    {cat}
                                  </text>
                                </g>
                              )
                            })}
                            {/* 툴팁 - 맨 마지막에 렌더링하여 항상 위에 표시 */}
                            {activeIndex !== null && (() => {
                              const data = categoryData[activeIndex]
                              // 라벨 위치 계산 (카테고리 라벨 근처에 툴팁 표시)
                              const angle = startAngle + activeIndex * angleStep
                              const labelRadius = maxRadius + 22
                              const labelX = centerX + labelRadius * Math.cos(angle)
                              const labelY = centerY + labelRadius * Math.sin(angle)

                              // 툴팁 위치 조정 (차트 밖으로 배치)
                              const tooltipWidth = 150
                              const tooltipHeight = 120

                              // 툴팁 위치 - 차트 중앙에 고정 (어느 화면에서든 잘리지 않음)
                              const tooltipX = centerX
                              const tooltipY = centerY - tooltipHeight / 2

                              return (
                                <g className="pointer-events-none">
                                  {/* 배경 */}
                                  <rect
                                    x={tooltipX - tooltipWidth / 2}
                                    y={tooltipY}
                                    width={tooltipWidth}
                                    height={tooltipHeight}
                                    rx={10}
                                    fill="#1e293b"
                                    filter="drop-shadow(0 4px 10px rgba(0,0,0,0.25))"
                                  />
                                  {/* 카테고리명 + 형질 개수 */}
                                  <text x={tooltipX} y={tooltipY + 20} textAnchor="middle" fontSize={15} fontWeight={700} fill="#ffffff">
                                    {data.category}
                                  </text>
                                  <text x={tooltipX} y={tooltipY + 36} textAnchor="middle" fontSize={11} fill="#94a3b8">
                                    {data.traitCount}개 형질 평균
                                  </text>
                                  {/* 구분선 */}
                                  <line x1={tooltipX - 60} y1={tooltipY + 46} x2={tooltipX + 60} y2={tooltipY + 46} stroke="#475569" strokeWidth={1} />
                                  {/* 보은군 대비 차이 */}
                                  <text x={tooltipX} y={tooltipY + 68} textAnchor="middle" fontSize={20} fontWeight={800} fill={data.avgEpd >= 0 ? '#60a5fa' : '#f87171'}>
                                    {data.avgEpd >= 0 ? '+' : ''}{data.avgEpd.toFixed(2)}
                                  </text>
                                  <text x={tooltipX} y={tooltipY + 84} textAnchor="middle" fontSize={11} fill="#94a3b8">
                                    보은군 대비
                                  </text>
                                  {/* 순위 배지 */}
                                  <rect
                                    x={tooltipX - 38}
                                    y={tooltipY + 92}
                                    width={76}
                                    height={22}
                                    rx={11}
                                    fill="#16a34a"
                                  />
                                  <text x={tooltipX} y={tooltipY + 107} textAnchor="middle" fontSize={12} fontWeight={700} fill="#ffffff">
                                    상위 {data.avgPercentile}%
                                  </text>
                                </g>
                              )
                            })()}
                          </svg>
                        )
                      }

                      return (
                        <div className="flex flex-col lg:flex-row gap-4 sm:gap-4 items-center">
                          {/* 레이더 차트 - 32% */}
                          <div className="w-full lg:w-[32%] flex justify-center flex-shrink-0">
                            <RadarChart />
                          </div>

                          {/* 우측: 상세 바 차트 - 68% */}
                          <div className="w-full lg:flex-1 space-y-3 sm:space-y-3">
                            {categoryData.map(({ category, avgEpd, avgPercentile, traitCount }, index) => {
                              const isPositive = avgEpd >= 0
                              // 바 너비: 육종가 스케일에 맞게 계산
                              const barWidth = Math.min(Math.abs(avgEpd) / maxAbs * 45, 48)
                              const isFirst = index === 0
                              return (
                                <div key={category} className={`flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-2 ${isFirst ? 'sm:mt-4' : ''}`}>
                                  {/* 모바일: 카테고리명 + 값을 한 줄에 */}
                                  <div className="flex items-center justify-between sm:hidden">
                                    <span className="text-sm font-bold text-slate-700">{category}</span>
                                    <div className="flex items-center gap-2">
                                      <span className={`text-sm font-bold ${isPositive ? 'text-[#1F3A8F]' : 'text-red-500'}`}>
                                        {isPositive ? '+' : ''}{avgEpd.toFixed(2)}
                                      </span>
                                      <span className="flex flex-col items-center w-[52px] px-1.5 py-0.5 rounded bg-slate-100 text-slate-600">
                                        <span className="text-[10px] font-medium">상위</span>
                                        <span className="text-xs font-bold">{avgPercentile}%</span>
                                      </span>
                                    </div>
                                  </div>
                                  {/* 모바일: 바 차트 전체 너비 */}
                                  <div className="sm:hidden h-7 bg-slate-100 rounded-full relative overflow-hidden">
                                    <div className="absolute left-1/2 top-0 bottom-0 w-0.5 bg-slate-400 z-10"></div>
                                    <div
                                      className={`absolute top-1 bottom-1 rounded-full transition-all duration-500 ${isPositive ? 'bg-[#1F3A8F]' : 'bg-red-400'}`}
                                      style={{
                                        left: isPositive ? '50%' : `${50 - barWidth}%`,
                                        width: `${barWidth}%`,
                                      }}
                                    />
                                  </div>
                                  {/* 데스크톱: 한 줄 레이아웃 */}
                                  <span className="hidden sm:block w-12 text-base font-bold text-slate-700 flex-shrink-0">{category}</span>
                                  <div className={`hidden sm:block w-[70%] h-10 relative ${isFirst ? 'mt-5' : ''}`}>
                                    {/* 보은군 평균 라벨 (첫 번째 바 위에만 표시) */}
                                    {isFirst && (
                                      <span className="absolute left-1/2 -translate-x-1/2 -top-5 text-[11px] text-slate-500 font-medium whitespace-nowrap">보은군 평균</span>
                                    )}
                                    {/* 바 차트 */}
                                    <div className="absolute inset-0 bg-slate-100 rounded-full overflow-hidden">
                                      <div className="absolute left-1/2 top-0 bottom-0 w-0.5 bg-slate-400 z-10"></div>
                                      <div
                                        className={`absolute top-1 bottom-1 rounded-full transition-all duration-500 ${isPositive ? 'bg-[#1F3A8F]' : 'bg-red-400'}`}
                                        style={{
                                          left: isPositive ? '50%' : `${50 - barWidth}%`,
                                          width: `${barWidth}%`,
                                        }}
                                      />
                                    </div>
                                  </div>
                                  <span className={`hidden sm:block w-20 text-right text-lg font-bold flex-shrink-0 ml-3 ${isPositive ? 'text-[#1F3A8F]' : 'text-red-500'}`}>
                                    {isPositive ? '+' : ''}{avgEpd.toFixed(2)}
                                  </span>
                                  <span className="hidden sm:flex flex-col items-center w-[72px] px-2 py-2 rounded-xl flex-shrink-0 bg-slate-100 text-slate-600 ml-3">
                                    <span className="text-xs font-medium leading-tight">상위</span>
                                    <span className="text-lg font-bold leading-tight">{avgPercentile}%</span>
                                  </span>
                                </div>
                              )
                            })}
                          </div>
                        </div>
                      )
                    })()
                  ) : (
                    <div className="h-[280px] flex items-center justify-center text-slate-400 bg-slate-50 rounded-xl">
                      <div className="text-center">
                        <Dna className="w-10 h-10 mx-auto mb-3 opacity-50" />
                        <p className="text-base">유전체 검사 데이터가 없습니다</p>
                      </div>
                    </div>
                  )}
                  {/* 범례 */}
                  {(stats?.summary.genomeCowCount || 0) > 0 && (
                  <div className="mt-4 pt-3 border-t border-slate-100 flex flex-wrap items-center justify-center gap-4 text-xs text-slate-500">
                    <span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded bg-[#1F3A8F]"></span>우리농가</span>
                    <span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded bg-slate-400 opacity-50"></span>보은군평균</span>
                  </div>
                  )}
                </div>

              </>
            )}
          </div>
        </SidebarInset>
      </SidebarProvider>
    </AuthGuard>
  )
}
