'use client'

import { AppSidebar } from "@/components/layout/app-sidebar"
import { SiteHeader } from "@/components/layout/site-header"
import { CowNumberDisplay } from "@/components/common/cow-number-display"
import {
  SidebarInset,
  SidebarProvider,
} from "@/components/ui/sidebar"
import { Button } from "@/components/ui/button"
import { Cow } from "@/types/cow.types"
import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { ChevronLeft, ChevronRight, Search, ChevronsUpDown, Filter, Settings } from "lucide-react"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { ScrollArea } from "@/components/ui/scroll-area"
import { cowApi } from "@/lib/api"
import { useAuthStore } from "@/store/auth-store"
import { useGlobalFilter, GlobalFilterProvider } from "@/contexts/GlobalFilterContext"
import { AnalysisYearProvider } from "@/contexts/AnalysisYearContext"
import { AuthGuard } from "@/components/auth/auth-guard"

/**
 * 개체 리스트 페이지
 */
/**
 * 유전자 정보를 포함한 Cow 타입 (임시 - 실제로는 API에서 가져와야 함)
 */
interface TraitData {
  breedVal: number | null
  traitVal: number | null
}

interface CowWithGenes extends Cow {
  genes?: {
    name: string
    genotype: string
    favorable: boolean // 유리대립유전자 여부
  }[]
  traits?: Record<string, TraitData | number> // 형질명 → { breedVal, traitVal } 또는 number 매핑
  grade?: 'A' | 'B' | 'C' | 'D' | 'E'
  quantityGeneCount?: number
  qualityGeneCount?: number
  quantityHomoCount?: number // 육량형 동형접합(AA) 개수
  quantityHeteroCount?: number // 육량형 이형접합(AG) 개수
  qualityHomoCount?: number // 육질형 동형접합(AA) 개수
  qualityHeteroCount?: number // 육질형 이형접합(AG) 개수
  rankScore?: number // 백엔드 랭킹 API에서 받은 점수
  genomeScore?: number // COMPOSITE 모드에서 유전체 점수
  geneScore?: number // COMPOSITE 모드에서 유전자 점수
  rank?: number // 랭킹 순위
  cowShortNo?: string // 개체 요약번호
  cowReproType?: string // 번식 타입
  anlysDt?: string // 분석일자
  unavailableReason?: string // 분석불가 사유 (부불일치, 모불일치, 모이력제부재 등)
}

function MyCowContent() {
  const [cows, setCows] = useState<CowWithGenes[]>([])
  const [filteredCows, setFilteredCows] = useState<CowWithGenes[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const router = useRouter()
  const { user } = useAuthStore()
  const { filters, isLoading: isFilterLoading } = useGlobalFilter()
  const [markerTypes, setMarkerTypes] = useState<Record<string, string>>({}) // 마커명 → 타입(QTY/QLT) 매핑

  // 로컬 필터 상태 (검색, 랭킹모드, 정렬)
  const [searchKeyword, setSearchKeyword] = useState('')
  const [rankingMode, setRankingMode] = useState<'gene' | 'genome'>('gene') // 유전자순/유전체순
  const [sortBy, setSortBy] = useState<string>('rank') // 정렬 기준 (기본: 순위)
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc') // 정렬 방향
  const [analysisFilter, setAnalysisFilter] = useState<'all' | 'completed' | 'unavailable'>('all') // 분석 상태 필터

  // 커스텀 컬럼 표시 필터
  const [selectedDisplayGenes, setSelectedDisplayGenes] = useState<string[]>([]) // 테이블에 표시할 유전자
  const [selectedDisplayTraits, setSelectedDisplayTraits] = useState<string[]>([]) // 테이블에 표시할 형질
  const [availableGenes, setAvailableGenes] = useState<string[]>([]) // 선택 가능한 유전자 목록
  const [availableTraits, setAvailableTraits] = useState<string[]>([]) // 선택 가능한 형질 목록 (전역 필터 순서 유지)
  const [expandedRows, setExpandedRows] = useState<Set<number | string>>(new Set()) // 유전자형 더보기 펼침 상태 (pkCowNo 또는 "pkCowNo-traits" 형태)

  // 페이지네이션
  const [currentPage, setCurrentPage] = useState(1)
  const itemsPerPage = 12


  // 필터가 설정되었는지 확인 (형질 가중치가 1개 이상 설정됨 - 유전체 필수)
  const isFilterSet = filters.isActive && Object.values(filters.traitWeights).some(w => w > 0)

  // 마커 타입 정보 로드 (gene.api 제거됨 - 추후 백엔드 구현 시 복구)
  useEffect(() => {
    // TODO: gene API 구현 후 마커 타입 정보 로드 복구
    setMarkerTypes({})
  }, [])

  // 전역 필터의 선택된 유전자를 선택 가능한 목록으로 설정 + 자동 랭킹 모드 설정
  // 필터 변경 시 표시 항목 업데이트
  useEffect(() => {
    // 필터 로딩 중이면 건너뛰기
    if (isFilterLoading) {
      return
    }
    const hasGenes = filters.isActive && filters.selectedGenes && filters.selectedGenes.length > 0
    const hasTraits = filters.isActive && Object.values(filters.traitWeights).some(w => w > 0)

    // 유전자 처리 (고정 항목 우선)
    if (hasGenes) {
      const pinnedGenes = filters.pinnedGenes || []
      const restGenes = filters.selectedGenes.filter(g => !pinnedGenes.includes(g))
      const orderedGenes = [...pinnedGenes, ...restGenes]

      setAvailableGenes(orderedGenes)
      // 고정된 항목이 있으면 고정 항목만, 없으면 전체 선택
      setSelectedDisplayGenes(pinnedGenes.length > 0 ? pinnedGenes : orderedGenes)
    } else {
      setAvailableGenes([])
      setSelectedDisplayGenes([])
    }

    // 형질 처리 (고정 항목 우선)
    if (filters.isActive && filters.selectedTraits && filters.selectedTraits.length > 0) {
      const pinnedTraits = filters.pinnedTraits || []
      const restTraits = filters.selectedTraits.filter(t => !pinnedTraits.includes(t))
      const orderedTraits = [...pinnedTraits, ...restTraits]

      setAvailableTraits(orderedTraits)
      // 고정된 항목이 있으면 고정 항목만, 없으면 전체 선택
      setSelectedDisplayTraits(pinnedTraits.length > 0 ? pinnedTraits : orderedTraits)
    } else {
      setAvailableTraits([])
      setSelectedDisplayTraits([])
    }

    // 자동 랭킹 모드 설정
    if (filters.isActive) {
      if (hasGenes) {
        // 유전자가 선택되어 있으면 → 유전자순 (형질 유무 상관없이)
        setRankingMode('gene')
      } else if (hasTraits) {
        // 유전자 없이 형질만 선택 → 유전체순
        setRankingMode('genome')
      }
    }
  }, [isFilterLoading, filters.isActive, filters.selectedGenes, filters.selectedTraits, filters.pinnedGenes, filters.pinnedTraits, filters.traitWeights])

  useEffect(() => {
    const fetchCows = async () => {
      // 필터가 설정되지 않았으면 API 호출하지 않음
      if (!isFilterSet) {
        setLoading(false)
        setCows([])
        setFilteredCows([])
        return
      }

      try {
        setLoading(true)
        // 사용자의 농장 목록 조회하여 농장 필터 생성
        let farmFilters: { field: string; operator: 'in'; value: number[] }[] = []
        try {
          const userNo = user?.pkUserNo
          if (userNo) {
            const { default: apiClient } = await import('@/lib/api-client')
            const farmsResponse = await apiClient.get(`/farm?userId=${userNo}`)
            const farms = (farmsResponse.data || farmsResponse) as { pkFarmNo: number }[]
            if (farms && Array.isArray(farms) && farms.length > 0) {
              const farmNos = farms.map((f) => f.pkFarmNo)
              farmFilters = [{ field: 'cow.fkFarmNo', operator: 'in', value: farmNos }]
            }
          }
        } catch (err) {
          console.error('Failed to fetch farms:', err)
        }

        setError(null)

        // 마커 타입 정보 (gene.api 제거됨 - 추후 백엔드 구현 시 복구)
        const currentMarkerTypes = markerTypes

        // 전역 필터 + 랭킹 모드를 기반으로 랭킹 옵션 구성
        // 타입을 any로 지정하여 백엔드 API와의 호환성 유지
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let rankingOptions: any

        // 형질 가중치 조건 (유전체 점수 계산용)
        const traitConditions = Object.entries(filters.traitWeights)
          .filter(([, weight]) => weight > 0)
          .map(([traitNm, weight]) => ({
            traitNm,
            weight  // 0-10 가중치 그대로 사용
          }))

        // 랭킹 모드에 따라 criteriaType 결정
        if (rankingMode === 'gene' && filters.isActive && filters.selectedGenes && filters.selectedGenes.length > 0) {
          // 유전자순 랭킹 → GENE 모드
          // 정렬 기준: 1차 AA 개수, 2차 Aa 개수, 3차 유전체 점수
          rankingOptions = {
            criteriaType: 'GENE',
            geneConditions: filters.selectedGenes.map(markerNm => ({
              markerNm,
              order: 'DESC'
            })),
            traitConditions // 유전체 점수 계산용
          }
        } else if (rankingMode === 'genome' || !filters.isActive || !filters.selectedGenes || filters.selectedGenes.length === 0) {
          // 유전체순 랭킹 또는 필터 비활성화 → GENOME 모드
          // 정렬 기준: 유전체 점수 (형질 가중치 평균)

          // 전역 필터가 비활성화되어 있으면 기본 가중치로 전체 개체 표시
          if (!filters.isActive) {
            rankingOptions = {
              criteriaType: 'GENOME',
              traitConditions: [], // 빈 배열 → 백엔드 기본 가중치 사용
              inbreedingCondition: {
                maxThreshold: 0,
                order: 'ASC'
              }
            }
          } else if (rankingMode === 'genome' && traitConditions.length === 0) {
            // 유전체순인데 형질 가중치가 비어있으면 기본 가중치 사용
            rankingOptions = {
              criteriaType: 'GENOME',
              traitConditions: [], // 빈 배열 → 백엔드 기본 가중치 사용
              inbreedingCondition: {
                maxThreshold: filters.inbreedingThreshold !== undefined ? filters.inbreedingThreshold : 0,
                order: 'ASC'
              }
            }
          } else {
            // 정상적으로 가중치가 있는 경우
            rankingOptions = {
              criteriaType: 'GENOME',
              traitConditions, // 가중치 > 0인 형질만
              inbreedingCondition: {
                maxThreshold: filters.inbreedingThreshold !== undefined ? filters.inbreedingThreshold : 0,
                order: 'ASC'
              }
            }
          }
        } else {
          // 기본값 (유전체순)
          rankingOptions = {
            criteriaType: 'GENOME',
            traitConditions: [], // 빈 배열
            inbreedingCondition: {
              maxThreshold: 0,
              order: 'ASC'
            }
          }
        }

        // 백엔드 ranking API 호출
        const rankingRequest = {
          filterOptions: {
            filters: farmFilters // 농장 필터 적용
          },
          rankingOptions
        }

        const response = await cowApi.getRanking(rankingRequest)

        // ==========================================================================================================
        // response는 { items: RankingResultItem[], total, criteriaType, timestamp } 형식
        // items의 각 요소는 { entity, rank, sortValue, grade, details } 형식
        interface RankingItem {
          entity: Cow & { genes?: Record<string, number>; calvingCount?: number; bcs?: number; inseminationCount?: number; inbreedingPercent?: number; sireKpn?: string; anlysDt?: string; unavailableReason?: string };
          rank: number;
          sortValue: number;
          grade: string;
          compositeScores?: { geneScore?: number };
          ranking?: { traits?: { traitName: string; traitEbv: number | null; traitVal: number | null }[] }; // 랭킹 형질
        }
        const cowsWithMockGenes = response.items.map((item: RankingItem) => {
          // 백엔드에서 genes 객체를 배열로 변환
          // genes 객체 형식: { "PLAG1": 2, "NCAPG": 1, ... }
          // 배열 형식으로 변환: [{ name: "PLAG1", genotype: "AA", favorable: true }, ...]
          let genesArray = []

          if (item.entity.genes && typeof item.entity.genes === 'object') {
            // 백엔드 genes 객체를 배열로 변환
            genesArray = Object.entries(item.entity.genes).map(([markerName, count]) => {
              const favorableCount = count as number
              let genotype = 'N/A'
              let favorable = false

              // favorableCount에 따라 유전자형 결정
              if (favorableCount === 2) {
                genotype = 'AA' // 동형 접합 (유리)
                favorable = true
              } else if (favorableCount === 1) {
                genotype = 'AG' // 이형 접합 (중간)
                favorable = true
              } else {
                genotype = 'GG' // 동형 접합 (불리)
                favorable = false
              }

              return {
                name: markerName,
                genotype,
                favorable,
              }
            })
          } else {
            // 백엔드에서 genes 데이터가 없으면 mock 생성
            genesArray = generateMockGenes()
          }

          // currentMarkerTypes를 사용하여 동적으로 육량형/육질형 개수 계산
          // 동형접합(AA)과 이형접합(AG)을 구분하여 계산
          const isHomozygous = (genotype: string) => genotype.length === 2 && genotype[0] === genotype[1]

          const quantityHomoCount = genesArray.filter(g =>
            currentMarkerTypes[g.name] === 'QTY' && g.favorable && isHomozygous(g.genotype)
          ).length
          const quantityHeteroCount = genesArray.filter(g =>
            currentMarkerTypes[g.name] === 'QTY' && g.favorable && !isHomozygous(g.genotype)
          ).length
          const qualityHomoCount = genesArray.filter(g =>
            currentMarkerTypes[g.name] === 'QLT' && g.favorable && isHomozygous(g.genotype)
          ).length
          const qualityHeteroCount = genesArray.filter(g =>
            currentMarkerTypes[g.name] === 'QLT' && g.favorable && !isHomozygous(g.genotype)
          ).length

          return {
            ...item.entity, // 실제 cow 데이터
            rank: item.rank, // 백엔드에서 계산한 랭킹
            rankScore: item.sortValue, // 백엔드에서 계산한 점수
            grade: item.grade, // 백엔드에서 계산한 등급 (A~E)
            genes: genesArray,
            quantityGeneCount: quantityHomoCount + quantityHeteroCount,
            qualityGeneCount: qualityHomoCount + qualityHeteroCount,
            quantityHomoCount,
            quantityHeteroCount,
            qualityHomoCount,
            qualityHeteroCount,
            // 유전체 점수는 sortValue에서 가져옴 (백엔드 랭킹 엔진이 계산한 값)
            genomeScore: item.sortValue,
            geneScore: item.compositeScores?.geneScore,
            // 번식 정보 (백엔드에서 가져옴 - 암소만)
            calvingCount: item.entity.calvingCount,
            bcs: item.entity.bcs,
            inseminationCount: item.entity.inseminationCount,
            // 근친도 (백엔드에서 계산된 근친계수 백분율)
            inbreedingPercent: item.entity.inbreedingPercent ?? 0,
            // 아비 KPN 번호 (genome trait에서 가져옴)
            sireKpn: item.entity.sireKpn ?? null,
            // 분석일자
            anlysDt: item.entity.anlysDt ?? null,
            // 분석불가 사유
            unavailableReason: item.entity.unavailableReason ?? null,
            //====================================================================================================================
            // 형질 데이터 (백엔드에서 계산됨, 형질명 → 표준화육종가 매핑)
            // 백엔드 응답: { traitName: string, traitVal: number, traitEbv: number, traitPercentile: number }
            traits: item.ranking?.traits?.reduce((acc: Record<string,
              { breedVal: number | null, traitVal: number | null }>, t: { traitName: string; traitEbv: number | null; traitVal: number | null }) => {
              acc[t.traitName] = { breedVal: t.traitEbv, traitVal: t.traitVal };
              return acc
            }, {}) || {},
          }
        })

        setCows(cowsWithMockGenes)
        setFilteredCows(cowsWithMockGenes)
      } catch (err) {
        console.error('개체 데이터 조회 실패:', err)
        setError(err instanceof Error ? err.message : '데이터를 불러오는데 실패했습니다')
      } finally {
        setLoading(false)
      }
    }

    fetchCows()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters, rankingMode, isFilterSet])

  // Mock 유전자 생성 함수 (실제로는 API에서 가져와야 함)
  const generateMockGenes = () => {
    // 모든 소가 다양한 유전자를 가지도록 더 많은 유전자 풀 생성
    const genePool = [
      // 육량형 유전자
      { name: 'PLAG1', genotypes: ['AA', 'AG', 'GG'], favorable: ['AA', 'AG'] },
      { name: 'NCAPG', genotypes: ['AA', 'AG', 'GG'], favorable: ['AA', 'AG'] },
      { name: 'LCORL', genotypes: ['AA', 'AG', 'GG'], favorable: ['AA', 'AG'] },
      { name: 'MSTN', genotypes: ['AA', 'AG', 'GG'], favorable: ['AA'] },
      { name: 'IGF1', genotypes: ['AA', 'AG', 'GG'], favorable: ['AA', 'AG'] },
      { name: 'GH1', genotypes: ['CC', 'CT', 'TT'], favorable: ['CC', 'CT'] },
      { name: 'LAP3', genotypes: ['AA', 'AG', 'GG'], favorable: ['AA'] },
      { name: 'ARRDC3', genotypes: ['AA', 'AG', 'GG'], favorable: ['AA', 'AG'] },
      // 육질형 유전자
      { name: 'CAPN1', genotypes: ['CC', 'CG', 'GG'], favorable: ['CC', 'CG'] },
      { name: 'CAST', genotypes: ['AA', 'AG', 'GG'], favorable: ['GG', 'AG'] },
      { name: 'FASN', genotypes: ['AA', 'AG', 'GG'], favorable: ['GG', 'AG'] },
      { name: 'SCD', genotypes: ['AA', 'AV', 'VV'], favorable: ['VV', 'AV'] },
      { name: 'FABP4', genotypes: ['AA', 'AG', 'GG'], favorable: ['AA', 'AG'] },
      { name: 'SREBP1', genotypes: ['CC', 'CT', 'TT'], favorable: ['CC', 'CT'] },
      { name: 'DGAT1', genotypes: ['AA', 'AK', 'KK'], favorable: ['KK', 'AK'] },
      { name: 'LEP', genotypes: ['CC', 'CT', 'TT'], favorable: ['TT', 'CT'] },
    ]

    // 모든 유전자를 포함 (랜덤 유전자형)
    return genePool.map(gene => {
      const genotype = gene.genotypes[Math.floor(Math.random() * gene.genotypes.length)]
      return {
        name: gene.name,
        genotype,
        favorable: gene.favorable.includes(genotype),
      }
    })
  }

  // ============================================
  // 유전자형 판단 및 스타일 정의
  // ============================================

  /**
   * 동형접합 여부 판단
   * AA, GG, CC, TT 등 → true
   * AG, CT, AK 등 → false
   */
  const isHomozygous = (genotype: string): boolean => {
    return genotype.length === 2 && genotype[0] === genotype[1]
  }

  /**
   * 유전자 뱃지 스타일 정의
   * @param genotype 유전자형 (AA, AG, GG 등)
   * @param favorable 우량 유전자 여부
   * @param geneCategory 유전자 카테고리 ('QTY': 육량형, 'QLT': 육질형)
   */
  type GeneBadgeStyle = {
    className: string
    icon: 'star' | 'circle' | 'double-circle' | 'minus' | 'none'
  }

  const getGeneBadgeStyle = (
    genotype: string,
    favorable: boolean,
    geneCategory: 'QTY' | 'QLT'
  ): GeneBadgeStyle => {
    const isHomo = isHomozygous(genotype)

    // 1. 동형접합 우량 (AA형) → 진한 색 (육량: 파랑, 육질: 주황)
    if (isHomo && favorable) {
      return {
        className: geneCategory === 'QTY'
          ? 'bg-blue-600 text-white border-blue-700'
          : 'bg-orange-600 text-white border-orange-700',
        icon: 'none',
      }
    }

    // 2. 이형접합 우량 (AG형) → 중간 색 (육량: 파랑, 육질: 주황)
    if (!isHomo && favorable) {
      return {
        className: geneCategory === 'QTY'
          ? 'bg-blue-400 text-white border-blue-500'
          : 'bg-orange-400 text-white border-orange-500',
        icon: 'none',
      }
    }

    // 3. 불량형 (GG형) → 연한 회색
    return {
      className: 'bg-gray-300 text-gray-600 border-gray-400',
      icon: 'none',
    }
  }

  // ============================================
  // 컬럼 스타일은 globals.css의 CSS 변수로 관리됨
  // .cow-col-* 클래스 사용
  // ============================================

  // 필터링 및 정렬
  useEffect(() => {
    let result = [...cows]

    // 검색 필터 (전체 개체번호 또는 4자리 약식 번호로 검색)
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase()
      result = result.filter(cow =>
        (cow.cowId && cow.cowId.toLowerCase().includes(keyword)) ||
        (cow.cowShortNo && cow.cowShortNo.toLowerCase().includes(keyword)) ||
        String(cow.pkCowNo).includes(searchKeyword)
      )
    }


    // 전역 필터 적용 (유전자 기반 분석)
    if (filters.isActive && filters.analysisIndex === 'GENE' && filters.selectedGenes.length > 0) {
      result = result.filter(cow => {
        if (!cow.genes || !Array.isArray(cow.genes)) return false
        // 선택된 유전자를 모두 보유한 개체만 표시
        return filters.selectedGenes.every(selectedGene =>
          cow.genes!.some(g => g.name === selectedGene)
        )
      })
    }

    // 전역 필터 적용 (유전능력 기반 분석)
    // TODO: 유전능력 데이터가 있을 경우 형질 기반 필터링 추가
    if (filters.isActive && filters.analysisIndex === 'ABILITY' && (filters.selectedTraits?.length ?? 0) > 0) {
      // 현재는 mock 데이터이므로 필터링하지 않음
      // 실제로는 API에서 가져온 유전능력 데이터를 기반으로 필터링
    }

    // 분석 상태 필터
    if (analysisFilter === 'completed') {
      result = result.filter(cow => cow.genomeScore !== undefined && cow.genomeScore !== null)
    } else if (analysisFilter === 'unavailable') {
      result = result.filter(cow => cow.genomeScore === undefined || cow.genomeScore === null)
    }

    // 정렬 (sortBy가 'none'이면 정렬하지 않음 - 전역 필터 순서 유지)
    if (sortBy !== 'none') {
      switch (sortBy) {
        case 'rank':
          // 순위 정렬
          result.sort((a, b) => {
            const rankA = a.rank ?? 9999
            const rankB = b.rank ?? 9999
            return sortOrder === 'asc' ? rankA - rankB : rankB - rankA
          })
          break
        case 'number':
          // 개체번호 정렬 (cowId 문자열 기준)
          result.sort((a, b) => {
            const comparison = (a.cowId || '').localeCompare(b.cowId || '')
            return sortOrder === 'asc' ? comparison : -comparison
          })
          break
        case 'age':
          // 월령 정렬 (생년월일 기준)
          result.sort((a, b) => {
            const dateA = a.cowBirthDt ? new Date(a.cowBirthDt).getTime() : 0
            const dateB = b.cowBirthDt ? new Date(b.cowBirthDt).getTime() : 0
            // 오름차순: 오래된 것(작은 날짜) → 최근 것(큰 날짜), 즉 나이가 많은 순
            // 내림차순: 최근 것(큰 날짜) → 오래된 것(작은 날짜), 즉 나이가 적은 순
            return sortOrder === 'asc' ? dateA - dateB : dateB - dateA
          })
          break
        case 'score':
          // 점수 정렬
          result.sort((a, b) => {
            const scoreA = a.genomeScore ?? 0
            const scoreB = b.genomeScore ?? 0
            return sortOrder === 'asc' ? scoreA - scoreB : scoreB - scoreA
          })
          break
      }
    }

    setFilteredCows(result)
    setCurrentPage(1) // 필터 변경시 첫 페이지로
  }, [searchKeyword, sortBy, sortOrder, cows, filters, analysisFilter])

  // 페이지네이션
  const totalPages = Math.ceil(filteredCows.length / itemsPerPage)
  const startIndex = (currentPage - 1) * itemsPerPage
  const paginatedCows = filteredCows.slice(startIndex, startIndex + itemsPerPage)

  // handleCowClick - cowId 또는 pkCowNo로 상세 페이지 이동
  const handleCowClick = (cowNo: number | string) => {
    router.push(`/cow/${cowNo}`)
  }

  const handlePageChange = (page: number) => {
    setCurrentPage(page)
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }

  // 랭킹 가져오기 (백엔드에서 계산된 값 사용)
  const getRank = (cow: CowWithGenes): number => {
    return cow.rank ?? 9999
  }



  // 형질 카테고리 정의
  const traitCategories = {
    production: {
      name: '생산',
      traits: ['12개월령체중', '도체중', '등심단면적', '등지방두께', '근내지방도']
    },
    body: {
      name: '체형',
      traits: ['체고', '십자', '체장', '흉심', '흉폭', '고장', '요각폭', '좌골폭', '곤폭', '흉위']
    },
    weight: {
      name: '부분육중량',
      traits: ['안심weight', '등심weight', '채끝weight', '목심weight', '앞다리weight', '우둔weight', '설도weight', '사태weight', '양지weight', '갈비weight']
    },
    rate: {
      name: '부분육비율',
      traits: ['안심rate', '등심rate', '채끝rate', '목심rate', '앞다리rate', '우둔rate', '설도rate', '사태rate', '양지rate', '갈비rate']
    }
  }

  // traitCategories는 형질 카테고리 정보 제공용으로 유지
  void traitCategories

  if (loading) {
    return (
      <SidebarProvider>
        <AppSidebar />
        <SidebarInset>
          <SiteHeader />
          <div className="flex flex-1 flex-col items-center justify-center">
            <p>로딩 중...</p>
          </div>
        </SidebarInset>
      </SidebarProvider>
    )
  }

  if (error) {
    return (
      <SidebarProvider>
        <AppSidebar />
        <SidebarInset>
          <SiteHeader />
          <div className="flex flex-1 flex-col items-center justify-center">
            <p className="text-red-500">에러: {error}</p>
          </div>
        </SidebarInset>
      </SidebarProvider>
    )
  }

  // 필터 미설정 시 안내 화면
  if (!isFilterSet) {
    return (
      <SidebarProvider>
        <AppSidebar />
        <SidebarInset>
          <SiteHeader />
          <div className="flex flex-1 flex-col items-center justify-center p-8">
            <div className="w-20 h-20 rounded-full bg-muted flex items-center justify-center mb-6">
              <Filter className="h-10 w-10 text-muted-foreground" />
            </div>
            <h2 className="text-xl font-semibold mb-3">필터 설정이 필요합니다</h2>
            <p className="text-sm text-muted-foreground mb-6 text-center max-w-md">
              개체 목록을 조회하려면 먼저 분석에 사용할 형질(유전체)을 1개 이상 선택해주세요.
            </p>
            <Button
              onClick={() => {
                // SiteHeader의 필터 버튼 클릭
                const filterButton = document.querySelector('[data-filter-button]') as HTMLButtonElement
                if (filterButton) filterButton.click()
              }}
              className="gap-2"
            >
              <Settings className="h-4 w-4" />
              필터 설정하기
            </Button>
          </div>
        </SidebarInset>
      </SidebarProvider>
    )
  }

  // 본문시작 ====================================================================================================
  return (
    <SidebarProvider>
      <AppSidebar />
      <SidebarInset>
        <SiteHeader />
        <div className="flex flex-1 flex-col">
          <div className="@container/main flex flex-1 flex-col gap-2">
            <div className="flex flex-col gap-4 sm:gap-4 md:gap-5 lg:gap-6 py-5 sm:py-5 md:py-6 lg:py-8">
              {/* 헤더 */}
              <div className="px-4 sm:px-6 md:px-8 lg:px-10 mx-2 sm:mx-0">
                <div className="flex flex-col gap-3 sm:gap-4">
                  {/* 제목 */}
                  <div>
                    <h1 className="text-3xl max-sm:text-2xl font-bold text-slate-900">개체 목록</h1>
                    <p className="text-base max-sm:text-sm text-slate-500 mt-1">{'농장'} 보유 개체 현황</p>
                  </div>

                  {/* 분석 상태 탭 필터 */}
                  <div className="flex rounded-lg border border-slate-200 bg-slate-50 p-1.5 gap-1.5 max-sm:p-1 max-sm:gap-1">
                    <button
                      onClick={() => setAnalysisFilter('all')}
                      className={`flex-1 px-3 py-2.5 max-sm:px-2 max-sm:py-2 rounded-md text-base max-sm:text-sm font-medium transition-colors ${analysisFilter === 'all'
                        ? 'bg-white text-slate-900 shadow-sm border border-slate-200'
                        : 'text-slate-500 hover:text-slate-700'
                        }`}
                    >
                      전체 <span className="font-bold">{cows.length}</span>
                    </button>
                    <button
                      onClick={() => setAnalysisFilter('completed')}
                      className={`flex-1 px-3 py-2.5 max-sm:px-2 max-sm:py-2 rounded-md text-base max-sm:text-sm font-medium transition-colors ${analysisFilter === 'completed'
                        ? 'bg-white text-emerald-600 shadow-sm border border-slate-200'
                        : 'text-slate-500 hover:text-slate-700'
                        }`}
                    >
                      <span className="flex items-center justify-center gap-1.5 max-sm:gap-1">
                        <span className="w-2 h-2 rounded-full bg-emerald-500"></span>
                        완료 <span className="font-bold">{cows.filter(c => c.genomeScore !== undefined && c.genomeScore !== null).length}</span>
                      </span>
                    </button>
                    <button
                      onClick={() => setAnalysisFilter('unavailable')}
                      className={`flex-1 px-3 py-2.5 max-sm:px-2 max-sm:py-2 rounded-md text-base max-sm:text-sm font-medium transition-colors ${analysisFilter === 'unavailable'
                        ? 'bg-white text-slate-600 shadow-sm border border-slate-200'
                        : 'text-slate-500 hover:text-slate-700'
                        }`}
                    >
                      <span className="flex items-center justify-center gap-1.5 max-sm:gap-1">
                        <span className="w-2 h-2 rounded-full bg-slate-400"></span>
                        불가 <span className="font-bold">{cows.filter(c => c.genomeScore === undefined || c.genomeScore === null).length}</span>
                      </span>
                    </button>
                  </div>

                  {/* 필터 및 검색 통합 박스 */}
                  <div className="flex flex-col gap-3 sm:gap-3 p-3.5 max-sm:p-3 sm:px-4 sm:py-3 rounded-xl bg-slate-50/50 border border-slate-200/50">
                    {/* 검색창 */}
                    <div className="relative w-full">
                      <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                      <Input
                        placeholder="개체번호 검색..."
                        className="pl-9 h-11 max-sm:h-10 text-base max-sm:text-sm border-slate-200 bg-white focus:border-blue-400 focus:ring-blue-100"
                        value={searchKeyword}
                        onChange={(e) => setSearchKeyword(e.target.value)}
                      />
                    </div>

                    {/* 필터 옵션들 - 모바일: 2행, 데스크톱: 1행 */}
                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4 border-t border-slate-200/70 pt-3 sm:pt-3">
                      {/* 랭킹/정렬 그룹 */}
                      <div className="grid grid-cols-3 sm:flex sm:items-center gap-2.5 max-sm:gap-2 sm:gap-2">
                        <Select
                          value={rankingMode}
                          onValueChange={(value: 'gene' | 'genome') => setRankingMode(value)}
                        >
                          <SelectTrigger className="w-full sm:w-[120px] h-10 sm:h-9 text-sm border-slate-200 bg-white">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="gene">유전자순</SelectItem>
                            <SelectItem value="genome">유전체순</SelectItem>
                          </SelectContent>
                        </Select>
                        <Select value={sortBy} onValueChange={setSortBy}>
                          <SelectTrigger className="w-full sm:w-[110px] h-10 sm:h-9 text-sm border-slate-200 bg-white">
                            <SelectValue placeholder="정렬" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="rank">순위</SelectItem>
                            <SelectItem value="number">개체번호</SelectItem>
                            <SelectItem value="age">월령</SelectItem>
                            <SelectItem value="score">점수</SelectItem>
                          </SelectContent>
                        </Select>
                        <Select
                          value={sortOrder}
                          onValueChange={(value) => setSortOrder(value as 'asc' | 'desc')}
                        >
                          <SelectTrigger className="w-full sm:w-[100px] h-10 sm:h-9 text-sm border-slate-200 bg-white">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="asc">오름차순</SelectItem>
                            <SelectItem value="desc">내림차순</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      {/* 표시항목 그룹 */}
                      <div className="grid grid-cols-2 sm:flex sm:items-center gap-2.5 max-sm:gap-2 sm:gap-2">
                        <Popover>
                          <PopoverTrigger asChild>
                            <Button variant="outline" className="h-10 sm:h-9 text-sm justify-between w-full sm:w-[100px] border-slate-200 bg-white">
                              <span>유전자</span>
                              <ChevronsUpDown className="ml-1 h-4 w-4 shrink-0 opacity-50" />
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent className="w-[250px] p-0" align="start">
                            <ScrollArea className="h-[300px]">
                              <div className="p-4 space-y-2">
                                {availableGenes.map((gene) => (
                                  <div key={gene} className="flex items-center space-x-2">
                                    <Checkbox
                                      id={`gene-${gene}`}
                                      checked={selectedDisplayGenes.includes(gene)}
                                      onCheckedChange={(checked) => {
                                        if (checked) {
                                          // 전역 필터 순서대로 추가 (순서 유지)
                                          const orderedGenes = availableGenes.filter(g =>
                                            selectedDisplayGenes.includes(g) || g === gene
                                          )
                                          setSelectedDisplayGenes(orderedGenes)
                                        } else {
                                          setSelectedDisplayGenes(selectedDisplayGenes.filter(g => g !== gene))
                                        }
                                      }}
                                    />
                                    <Label
                                      htmlFor={`gene-${gene}`}
                                      className="text-sm font-normal cursor-pointer"
                                    >
                                      {gene}
                                    </Label>
                                  </div>
                                ))}
                              </div>
                            </ScrollArea>
                            <div className="border-t">
                              <div className="p-2 flex justify-between">
                                <Button
                                  size="sm"
                                  variant="ghost"
                                  onClick={() => {
                                    if (selectedDisplayGenes.length === availableGenes.length) {
                                      setSelectedDisplayGenes([])
                                    } else {
                                      setSelectedDisplayGenes(availableGenes)
                                    }
                                  }}
                                >
                                  {selectedDisplayGenes.length === availableGenes.length ? '전체 해제' : '전체 선택'}
                                </Button>
                                <span className="text-xs text-muted-foreground self-center">
                                  {selectedDisplayGenes.length}/{availableGenes.length}개
                                </span>
                              </div>
                              <div className="px-2 pb-2">
                                <p className="text-xs text-muted-foreground">
                                  순서는 전역 필터에서 설정하세요
                                </p>
                              </div>
                            </div>
                          </PopoverContent>
                        </Popover>
                        <Popover>
                          <PopoverTrigger asChild>
                            <Button variant="outline" className="h-10 sm:h-9 text-sm justify-between w-full sm:w-[100px] border-slate-200 bg-white">
                              <span>형질</span>
                              <ChevronsUpDown className="ml-1 h-4 w-4 shrink-0 opacity-50" />
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent className="w-[250px] p-0" align="end">
                            <ScrollArea className="h-[300px]">
                              <div className="p-4 space-y-2">
                                {availableTraits.map((trait) => (
                                  <div key={trait} className="flex items-center space-x-2">
                                    <Checkbox
                                      id={`trait-${trait}`}
                                      checked={selectedDisplayTraits.includes(trait)}
                                      onCheckedChange={(checked) => {
                                        if (checked) {
                                          // 전역 필터 순서대로 추가 (순서 유지)
                                          const orderedTraits = availableTraits.filter(t =>
                                            selectedDisplayTraits.includes(t) || t === trait
                                          )
                                          setSelectedDisplayTraits(orderedTraits)
                                        } else {
                                          setSelectedDisplayTraits(selectedDisplayTraits.filter(t => t !== trait))
                                        }
                                      }}
                                    />
                                    <Label
                                      htmlFor={`trait-${trait}`}
                                      className="text-sm font-normal cursor-pointer"
                                    >
                                      {trait}
                                    </Label>
                                  </div>
                                ))}
                              </div>
                            </ScrollArea>
                            <div className="border-t">
                              <div className="p-2 flex justify-between">
                                <Button
                                  size="sm"
                                  variant="ghost"
                                  onClick={() => {
                                    if (selectedDisplayTraits.length === availableTraits.length) {
                                      setSelectedDisplayTraits([])
                                    } else {
                                      setSelectedDisplayTraits(availableTraits)
                                    }
                                  }}
                                >
                                  {selectedDisplayTraits.length === availableTraits.length ? '전체 해제' : '전체 선택'}
                                </Button>
                                <span className="text-xs text-muted-foreground self-center">
                                  {selectedDisplayTraits.length}/{availableTraits.length}개
                                </span>
                              </div>
                              <div className="px-2 pb-2">
                                <p className="text-xs text-muted-foreground">
                                  순서는 전역 필터에서 설정하세요
                                </p>
                              </div>
                            </div>
                          </PopoverContent>
                        </Popover>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* 리스트 뷰 */}
              <div className="px-4 sm:px-6 md:px-8 lg:px-10 mx-2 sm:mx-0">
                {/* 데스크톱 테이블 뷰 */}
                {(
                  <div className="hidden md:block border rounded-lg overflow-hidden">
                    <div className="overflow-x-auto">
                      <table className="w-full">
                        <thead className="bg-muted/50 border-b">
                          <tr>
                            <th className="cow-table-header" style={{ width: '50px' }}>순위</th>
                            <th className="cow-table-header" style={{ width: '220px' }}>개체번호</th>
                            <th className="cow-table-header" style={{ width: '90px' }}>생년월일</th>
                            <th className="cow-table-header" style={{ width: '70px' }}>월령</th>
                            <th className="cow-table-header" style={{ width: '60px' }}>성별</th>
                            <th className="cow-table-header" style={{ width: '100px' }}>모개체번호</th>
                            <th className="cow-table-header" style={{ width: '90px' }}>아비 KPN</th>
                            <th className="cow-table-header" style={{ width: '90px' }}>분석일자</th>
                            <th className="cow-table-header border-r-2 border-r-gray-300" style={{ width: '100px' }}>
                              선발지수
                            </th>
                            {selectedDisplayGenes.length > 0 && (
                              <th className="cow-table-header bg-blue-50" style={{ width: '140px' }}>유전자형</th>
                            )}
                            {selectedDisplayTraits.length > 0 && (
                              <th className="cow-table-header bg-teal-50" style={{ width: '140px' }}>형질</th>
                            )}
                          </tr>
                        </thead>
                        <tbody>
                          {paginatedCows.map((cow) => {
                            const rank = getRank(cow)

                            return (
                              <tr
                                key={cow.pkCowNo}
                                className="border-b cursor-pointer transition-colors hover:bg-muted/50"
                                onClick={() => handleCowClick(cow.cowId)} // cowId 개체번호로 이동
                              >
                                <td className="cow-table-cell">
                                  <span className="font-semibold">{rank}</span>
                                </td>
                                <td className="cow-table-cell">
                                  <div className="font-medium">
                                    <CowNumberDisplay cowId={cow.cowId || cow.pkCowNo} cowShortNo={cow.cowShortNo} />
                                  </div>
                                </td>
                                <td className="cow-table-cell">
                                  {cow.cowBirthDt && new Date(cow.cowBirthDt).toLocaleDateString('ko-KR', {
                                    year: '2-digit',
                                    month: '2-digit',
                                    day: '2-digit'
                                  })}
                                </td>
                                <td className="cow-table-cell">
                                  {cow.cowBirthDt ? (() => {
                                    const birthDate = new Date(cow.cowBirthDt)
                                    const today = new Date()
                                    const ageInMonths = Math.floor((today.getTime() - birthDate.getTime()) / (1000 * 60 * 60 * 24 * 30.44))
                                    return `${ageInMonths}개월`
                                  })() : '-'}
                                </td>
                                <td className="cow-table-cell">
                                  {cow.cowSex === "암" ? "암소" : "수소"}
                                </td>
                                <td className="cow-table-cell">
                                  {cow.damCowId && cow.damCowId !== '0' ? cow.damCowId : '-'}
                                </td>
                                <td className="cow-table-cell">
                                  {cow.sireKpn && cow.sireKpn !== '0' ? cow.sireKpn : '-'}
                                </td>
                                <td className="cow-table-cell">
                                  {cow.anlysDt ? new Date(cow.anlysDt).toLocaleDateString('ko-KR', {
                                    year: '2-digit',
                                    month: '2-digit',
                                    day: '2-digit'
                                  }) : (
                                    <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold ${
                                      cow.unavailableReason?.includes('부') ? 'bg-red-100 text-red-700' :
                                      cow.unavailableReason?.includes('모') ? 'bg-orange-100 text-orange-700' :
                                      'bg-slate-100 text-slate-600'
                                    }`}>
                                      {cow.unavailableReason || '분석불가'}
                                    </span>
                                  )}
                                </td>
                                <td className="cow-table-cell border-r-2 border-r-gray-300 !py-2 !px-0.5">
                                  {(cow.genomeScore !== undefined && cow.genomeScore !== null) ? (
                                    <div className="font-bold text-primary text-base">
                                      {cow.genomeScore.toFixed(2)}
                                    </div>
                                  ) : (
                                    <Badge className="text-xs px-2 py-1 bg-slate-600 text-white border-0 font-semibold">
                                      분석불가
                                    </Badge>
                                  )}
                                </td>
                                {selectedDisplayGenes.length > 0 && (
                                  <td
                                    className="py-2 px-2 text-sm bg-blue-50/30"
                                    onClick={(e) => e.stopPropagation()}
                                  >
                                    {(() => {
                                      const isExpanded = expandedRows.has(cow.pkCowNo)
                                      const displayGenes = isExpanded ? selectedDisplayGenes : selectedDisplayGenes.slice(0, 3)
                                      const remainingCount = selectedDisplayGenes.length - 3

                                      return (
                                        <div className="flex flex-col gap-1">
                                          {displayGenes.map((geneName) => {
                                            const gene = cow.genes?.find(g => g.name === geneName)
                                            const genotype = gene?.genotype || '-'
                                            const favorable = gene?.favorable || false
                                            const geneCategory = markerTypes[geneName] as 'QTY' | 'QLT'
                                            const badgeStyle = gene ? getGeneBadgeStyle(genotype, favorable, geneCategory) : null

                                            return (
                                              <div key={geneName} className="flex items-center gap-2">
                                                <span className="text-xs text-slate-600 min-w-[60px]">{geneName}</span>
                                                {gene ? (
                                                  <Badge className={`text-xs font-semibold ${badgeStyle?.className}`}>
                                                    {genotype}
                                                  </Badge>
                                                ) : (
                                                  <Badge variant="outline" className="text-xs text-muted-foreground">
                                                    -
                                                  </Badge>
                                                )}
                                              </div>
                                            )
                                          })}
                                          {selectedDisplayGenes.length > 3 && (
                                            <button
                                              onClick={() => {
                                                const newExpanded = new Set(expandedRows)
                                                if (isExpanded) {
                                                  newExpanded.delete(cow.pkCowNo)
                                                } else {
                                                  newExpanded.add(cow.pkCowNo)
                                                }
                                                setExpandedRows(newExpanded)
                                              }}
                                              className="text-xs text-blue-600 hover:text-blue-800 font-semibold cursor-pointer text-center mt-0.5"
                                            >
                                              {isExpanded ? '접기' : `+${remainingCount}개 더보기`}
                                            </button>
                                          )}
                                        </div>
                                      )
                                    })()}
                                  </td>
                                )}
                                {selectedDisplayTraits.length > 0 && (
                                  <td
                                    className="py-2 px-2 text-sm bg-teal-50/30"
                                    onClick={(e) => e.stopPropagation()}
                                  >
                                    <div className="flex flex-col items-start gap-1.5">
                                      {(() => {
                                        const isExpanded = expandedRows.has(`${cow.pkCowNo}-traits`)
                                        const displayTraits = isExpanded ? selectedDisplayTraits : selectedDisplayTraits.slice(0, 3)
                                        const remainingCount = selectedDisplayTraits.length - 3

                                        return (
                                          <>
                                            {displayTraits.map((trait) => {
                                              let traitValue = '-'
                                              if (cow.traits && cow.traits[trait] !== undefined) {
                                                const traitData = cow.traits[trait]
                                                if (typeof traitData === 'object' && traitData.traitVal !== undefined && traitData.traitVal !== null) {
                                                  traitValue = Number(traitData.traitVal).toFixed(1)
                                                } else if (typeof traitData === 'object' && traitData.breedVal !== undefined) {
                                                  traitValue = Number(traitData.breedVal).toFixed(1)
                                                } else if (typeof traitData === 'number') {
                                                  traitValue = Number(traitData).toFixed(1)
                                                }
                                              }

                                              return (
                                                <div key={trait} className="flex items-center gap-1.5">
                                                  <span className="text-[10px] text-muted-foreground min-w-[65px]">{trait}</span>
                                                  <span className="font-semibold text-xs">{traitValue}</span>
                                                </div>
                                              )
                                            })}
                                            {selectedDisplayTraits.length > 3 && (
                                              <button
                                                onClick={() => {
                                                  const newExpanded = new Set(expandedRows)
                                                  const key = `${cow.pkCowNo}-traits`
                                                  if (isExpanded) {
                                                    newExpanded.delete(key)
                                                  } else {
                                                    newExpanded.add(key)
                                                  }
                                                  setExpandedRows(newExpanded)
                                                }}
                                                className="text-[10px] text-teal-600 hover:text-teal-800 font-medium mt-0.5 cursor-pointer"
                                              >
                                                {isExpanded ? '접기' : `+${remainingCount}개 더보기`}
                                              </button>
                                            )}
                                          </>
                                        )
                                      })()}
                                    </div>
                                  </td>
                                )}
                              </tr>
                            )
                          })}
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}

                {/* 모바일 컴팩트 카드 뷰 */}
                {(
                  <div className="md:hidden space-y-2.5">
                    {paginatedCows.map((cow) => {
                      const rank = getRank(cow)
                      const isFemale = cow.cowSex === '암'

                      return (
                        <div
                          key={cow.pkCowNo}
                          className="relative border rounded-lg p-3.5 hover:bg-muted/50 cursor-pointer transition-colors overflow-hidden"
                          onClick={() => handleCowClick(cow.cowId)}
                        >
                          {/* 1행: 순위, 개체번호, 성별, 선발지수 */}
                          <div className="flex items-center justify-between mb-2.5">
                            <div className="flex items-center gap-2 min-w-0 flex-1">
                              <span className="text-base font-bold text-muted-foreground">{rank}위</span>
                              <span className="font-bold text-lg truncate">
                                <CowNumberDisplay cowId={cow.cowId || cow.pkCowNo} cowShortNo={cow.cowShortNo} format="noKor" />
                              </span>
                              <Badge className={`text-xs px-1.5 py-0 font-medium flex-shrink-0 ${isFemale ? 'bg-slate-500 text-white' : 'bg-blue-500 text-white'}`}>
                                {isFemale ? '암' : '수'}
                              </Badge>
                            </div>
                            <div className="flex-shrink-0 ml-2">
                              {cow.genomeScore !== undefined && cow.genomeScore !== null ? (
                                <span className="font-bold text-xl text-primary">
                                  {cow.genomeScore.toFixed(2)}
                                </span>
                              ) : (
                                <Badge className="text-[11px] px-1.5 py-0.5 bg-slate-500 text-white border-0 font-medium">
                                  분석불가
                                </Badge>
                              )}
                            </div>
                          </div>

                          {/* 2행: 기본 정보 */}
                          <div className="grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm border-t pt-2.5">
                            <div className="flex justify-between">
                              <span className="text-muted-foreground">생년월일</span>
                              <span className="font-medium">
                                {cow.cowBirthDt ? new Date(cow.cowBirthDt).toLocaleDateString('ko-KR', { year: '2-digit', month: 'numeric', day: 'numeric' }) : '-'}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-muted-foreground">월령</span>
                              <span className="font-medium">
                                {cow.cowBirthDt ? `${Math.floor((new Date().getTime() - new Date(cow.cowBirthDt).getTime()) / (1000 * 60 * 60 * 24 * 30.44))}개월` : '-'}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-muted-foreground">모</span>
                              <span className="font-medium">
                                {cow.damCowId && cow.damCowId !== '0' ? (() => {
                                  const digits = cow.damCowId.replace(/\D/g, '')
                                  if (digits.length === 12) {
                                    return `${digits.slice(0, 3)} ${digits.slice(3, 7)} ${digits.slice(7, 11)} ${digits.slice(11)}`
                                  }
                                  return cow.damCowId
                                })() : '-'}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-muted-foreground">부</span>
                              <span className="font-medium">{cow.sireKpn && cow.sireKpn !== '0' ? cow.sireKpn : '-'}</span>
                            </div>
                            <div className="flex justify-between items-center">
                              <span className="text-muted-foreground">{cow.anlysDt ? '분석일' : '분석결과'}</span>
                              <span className="font-medium">
                                {cow.anlysDt ? new Date(cow.anlysDt).toLocaleDateString('ko-KR', { year: '2-digit', month: 'numeric', day: 'numeric' }) : (
                                  <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold ${
                                    cow.unavailableReason?.includes('부') ? 'bg-red-100 text-red-700' :
                                    cow.unavailableReason?.includes('모') ? 'bg-orange-100 text-orange-700' :
                                    'bg-slate-100 text-slate-600'
                                  }`}>
                                    {cow.unavailableReason || '분석불가'}
                                  </span>
                                )}
                              </span>
                            </div>
                          </div>

                          {/* 유전자형 섹션 */}
                          {selectedDisplayGenes.length > 0 && (
                            <div className="pt-2.5 border-t mt-2.5" onClick={(e) => e.stopPropagation()}>
                              <div className="flex items-center gap-1.5 flex-wrap">
                                <span className="text-xs text-muted-foreground mr-0.5">유전자</span>
                                {(() => {
                                  const isExpanded = expandedRows.has(`${cow.pkCowNo}-mobile-genes`)
                                  const pinnedGenes = filters.pinnedGenes || []
                                  const unpinnedGenes = selectedDisplayGenes.filter(g => !pinnedGenes.includes(g))
                                  const allGenes = [...pinnedGenes, ...unpinnedGenes]
                                  const displayGenes = isExpanded ? allGenes : allGenes.slice(0, 4)
                                  const remainingCount = allGenes.length - 4

                                  return (
                                    <>
                                      {displayGenes.map((geneName) => {
                                        const gene = cow.genes?.find(g => g.name === geneName)
                                        const geneCategory = markerTypes[geneName] as 'QTY' | 'QLT'
                                        const genotype = gene?.genotype || 'GG'
                                        const favorable = gene?.favorable || false
                                        const badgeStyle = getGeneBadgeStyle(genotype, favorable, geneCategory)

                                        return (
                                          <Badge key={geneName} className={`text-xs px-1.5 py-0.5 font-medium ${badgeStyle.className}`}>
                                            {geneName} {genotype}
                                          </Badge>
                                        )
                                      })}
                                      {selectedDisplayGenes.length > 4 && (
                                        <button
                                          onClick={() => {
                                            const newExpanded = new Set(expandedRows)
                                            const key = `${cow.pkCowNo}-mobile-genes`
                                            if (isExpanded) {
                                              newExpanded.delete(key)
                                            } else {
                                              newExpanded.add(key)
                                            }
                                            setExpandedRows(newExpanded)
                                          }}
                                          className="text-xs text-blue-600 hover:text-blue-800 font-medium"
                                        >
                                          {isExpanded ? '접기' : `+${remainingCount}개 더`}
                                        </button>
                                      )}
                                    </>
                                  )
                                })()}
                              </div>
                            </div>
                          )}

                          {/* 형질 섹션 */}
                          {selectedDisplayTraits.length > 0 && (
                            <div className="pt-2.5 border-t mt-2.5" onClick={(e) => e.stopPropagation()}>
                              {(() => {
                                const isExpanded = expandedRows.has(`${cow.pkCowNo}-mobile-traits`)
                                const displayTraits = isExpanded ? selectedDisplayTraits : selectedDisplayTraits.slice(0, 4)
                                const remainingCount = selectedDisplayTraits.length - 4

                                return (
                                  <>
                                    <div className="grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm">
                                      {displayTraits.map((trait) => {
                                        let traitValue = '-'
                                        if (cow.traits && cow.traits[trait] !== undefined) {
                                          const traitData = cow.traits[trait]
                                          if (typeof traitData === 'object' && traitData.traitVal !== undefined && traitData.traitVal !== null) {
                                            traitValue = Number(traitData.traitVal).toFixed(1)
                                          } else if (typeof traitData === 'object' && traitData.breedVal !== undefined) {
                                            traitValue = Number(traitData.breedVal).toFixed(1)
                                          } else if (typeof traitData === 'number') {
                                            traitValue = Number(traitData).toFixed(1)
                                          }
                                        }
                                        return (
                                          <div key={trait} className="flex items-center justify-between">
                                            <span className="text-muted-foreground">{trait}</span>
                                            <span className="font-medium">{traitValue}</span>
                                          </div>
                                        )
                                      })}
                                    </div>
                                    {selectedDisplayTraits.length > 4 && (
                                      <button
                                        onClick={() => {
                                          const newExpanded = new Set(expandedRows)
                                          const key = `${cow.pkCowNo}-mobile-traits`
                                          if (isExpanded) {
                                            newExpanded.delete(key)
                                          } else {
                                            newExpanded.add(key)
                                          }
                                          setExpandedRows(newExpanded)
                                        }}
                                        className="text-xs text-teal-600 hover:text-teal-800 font-medium w-full text-center mt-1.5"
                                      >
                                        {isExpanded ? '접기' : `+${remainingCount}개 더`}
                                      </button>
                                    )}
                                  </>
                                )
                              })()}
                            </div>
                          )}
                        </div>
                      )
                    })}
                  </div>
                )}
              </div>

              {filteredCows.length === 0 && selectedDisplayGenes.length > 0 && (
                <div className="text-center py-12 text-muted-foreground">
                  {searchKeyword
                    ? '검색 결과가 없습니다.'
                    : '등록된 소가 없습니다.'}
                </div>
              )}

              {/* 페이지네이션 */}
              {totalPages > 1 && (
                <div className="flex items-center justify-center gap-1.5 mt-5 sm:mt-6 px-4 sm:px-6 md:px-8 lg:px-10 mx-2 sm:mx-0 mb-4">
                  <Button
                    variant="outline"
                    size="icon"
                    className="h-8 w-8 sm:h-9 sm:w-9"
                    onClick={() => handlePageChange(currentPage - 1)}
                    disabled={currentPage === 1}
                  >
                    <ChevronLeft className="h-3.5 w-3.5" />
                  </Button>

                  <div className="flex gap-1">
                    {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => {
                      // 모바일: 앞뒤 1개씩만, 데스크톱: 앞뒤 2개씩
                      const isMobileVisible = page === 1 || page === totalPages || (page >= currentPage - 1 && page <= currentPage + 1)
                      if (isMobileVisible) {
                        return (
                          <Button
                            key={page}
                            variant={currentPage === page ? "default" : "outline"}
                            size="icon"
                            className="h-8 w-8 sm:h-9 sm:w-9 text-xs"
                            onClick={() => handlePageChange(page)}
                          >
                            {page}
                          </Button>
                        )
                      } else if (page === currentPage - 2 || page === currentPage + 2) {
                        return <span key={page} className="px-0.5 text-xs text-muted-foreground">...</span>
                      }
                      return null
                    })}
                  </div>

                  <Button
                    variant="outline"
                    size="icon"
                    className="h-8 w-8 sm:h-9 sm:w-9"
                    onClick={() => handlePageChange(currentPage + 1)}
                    disabled={currentPage === totalPages}
                  >
                    <ChevronRight className="h-3.5 w-3.5" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>

      </SidebarInset>
    </SidebarProvider >
  )
}

export default function MyCowPage() {
  return (
    <AuthGuard>
      <GlobalFilterProvider>
        <AnalysisYearProvider>
          <MyCowContent />
        </AnalysisYearProvider>
      </GlobalFilterProvider>
    </AuthGuard>
  )
}
